diff --git a/.agents/notes/archived/manifest.json b/.agents/notes/archived/manifest.json index 2dbf920a69..e42398340b 100644 --- a/.agents/notes/archived/manifest.json +++ b/.agents/notes/archived/manifest.json @@ -2662,6 +2662,9 @@ "simplification/2026-09-19-deepseek-messages-only.i18n.yaml": "sha256:7ffd708c5823c39cc9536178292e7e7fa57db5267bbc9acdda0a87e4953d5ba8", "simplification/2026-09-19-deepseek-messages-only.md": "sha256:241861200ce73e02f77d182633d6ea10b1f29c696c81bff002680762db01d9b5", "simplification/2026-09-19-deepseek-messages-only.zh.md": "sha256:311ef6f8f4cf60dae2a43ca94d772028b645631501fb3648aaeb406ba174991e", + "simplification/2026-09-26-team-direct-inbox.i18n.yaml": "sha256:9a6f1137f0c68d976fda4f44c5c301b851a8ee8e46965f3ea808ec5551045fb0", + "simplification/2026-09-26-team-direct-inbox.md": "sha256:88f7d9be3ae0b740ddb5a61a16e3c64044a207584b973acab8c3a40c36a7ff30", + "simplification/2026-09-26-team-direct-inbox.zh.md": "sha256:d6d1fafa4aa7035a11930cca3bf998d676a62b5f9b75176dff69c3c5ff6b92f0", "testing/2026-06-11-property-based-testing.i18n.yaml": "sha256:9d378912101ad30203f1fcbcad23e0f5d6ec6f39e04a83f17f90887b5c5d761e", "testing/2026-06-11-property-based-testing.md": "sha256:cca3b6299784cff94965f21b6d59966109a0bb41fdc2f8cf56653fa6c417a20a", "testing/2026-06-11-property-based-testing.zh.md": "sha256:09f3d1e2defd2792f87fb0e9892fb7e1db006f3c75ea4581f97e9cde4ea98175", diff --git a/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.i18n.yaml b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.i18n.yaml new file mode 100644 index 0000000000..50788468df --- /dev/null +++ b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.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 .agents/notes/archived/simplification/2026-09-26-team-direct-inbox.md +2026-09-26-team-direct-inbox.md: 9b90d7ae30e0b711c602de9280cc11845d0525f0 +2026-09-26-team-direct-inbox.zh.md: 8838fb4a2824838b76142f30a6ff4d0aedf0276b diff --git a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.md similarity index 99% rename from .agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md rename to .agents/notes/archived/simplification/2026-09-26-team-direct-inbox.md index 58d18d0ecf..9b90d7ae30 100644 --- a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md +++ b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.md @@ -1,6 +1,7 @@ # Agent Note: Team messages use the target inbox Status: implemented +Archived: 2026-10-15 English | [中文](2026-09-26-team-direct-inbox.zh.md) diff --git a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.zh.md similarity index 99% rename from .agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md rename to .agents/notes/archived/simplification/2026-09-26-team-direct-inbox.zh.md index 6928631c8f..8838fb4a28 100644 --- a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.zh.md +++ b/.agents/notes/archived/simplification/2026-09-26-team-direct-inbox.zh.md @@ -1,6 +1,7 @@ # Agent Note: Team 消息使用目标 inbox Status: implemented +Archived: 2026-10-15 [English](2026-09-26-team-direct-inbox.md) | 中文 diff --git a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.i18n.yaml index 30244c0085..fb1ee4e295 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.i18n.yaml @@ -9,11 +9,11 @@ en: fca00eeb7a8d9abd zh: d7a9766f5322dff9 /agent-note-session-projections-as-a-required-reader-seam/decision: - en: 8d38ed9356085c7e - zh: e15ede51415192f3 + en: ed3ee779d31afdba + zh: 2ffad21003be59c5 /agent-note-session-projections-as-a-required-reader-seam/alternatives-considered: - en: aea3da939c90d240 - zh: 21e91c481cdd23b7 + en: 778e12e73a9a6900 + zh: 5d4f313e4ea87372 /agent-note-session-projections-as-a-required-reader-seam/consequences: - en: ab45eb87f7c22cdb - zh: e65a97991a45164f + en: b1935fb4cc8d9cc6 + zh: 0611d7033f5702a3 diff --git a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.md b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.md index 091e8b277a..3256c6dbb0 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.md +++ b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.md @@ -18,6 +18,8 @@ Owners acquire state through [awaited registration and retained handles](2026-10 `onChanged` publishes client-visible value changes only. Registration changes do not create a second Host event stream or client tombstone protocol. A later authoritative history or list baseline reflects the active key set. +`onEventChanged` groups the changes of one committed event. After every unit has been driven, it receives one `{ key, val }` entry per client-visible key whose view changed, in registration order, where `val` is the key's view. If a unit or an `onChanged` listener throws, it still receives the entries collected before the throw. Remote projection frames follow this grouping: `session/control` and `session/observeProjections` emit one frame per committed event with a `changes` array of the same entries, so a Client applies one event's changes and publishes its Session list once instead of once per key. Each entry names its key, so a key changed to `null` stays distinct from an unchanged key and no consumer pairs values with keys by position. `onChanged` remains for Host consumers that react to one key. + ## Alternatives considered - **Default missing projected state.** This preserves more partial compositions but makes missing host state indistinguishable from a valid empty value. Rejected because official profiles mount the registry and configuration errors must fail explicitly. @@ -25,9 +27,14 @@ Owners acquire state through [awaited registration and retained handles](2026-10 - **Use `snapshot()` for every read.** This keeps one method but computes unrelated wire views and encourages consumers to depend on batch transport data for host logic. Rejected in favor of typed single-key state reads. - **Send full host values to clients.** This avoids separate view types but exposes producer identities and policy knobs that no client consumes. Rejected in favor of explicit cropped views. - **Broadcast registry additions and removals across Host and mux streams.** The streams have no shared ordering, so clients need tombstones, buffered frames, and baseline retries to reconcile them. Rejected because plugin-key churn does not justify a second synchronization protocol. +- **Coalesce per-key frames in the controller or Client.** Microtask batching or grouping frames by sequence number needs buffering and timing assumptions, while the registry already knows where each event's drive ends. Rejected in favor of grouping at the drive. +- **Carry frame changes as a key-to-value object.** Consumers would infer the changed keys from object members and lose the registration order. Rejected in favor of an ordered array of `{ key, val }` entries. +- **Carry parallel `keys` and `values` arrays.** This avoids repeating the entry field names, but every consumer must keep the two arrays aligned by index, and the wire types cannot express their equal length. Rejected in favor of self-contained entries. +- **Replace `onChanged` with the event-level feed.** Host consumers such as forge react to one key and gain nothing from grouping. Rejected; both feeds remain. ## Consequences - Missing projection composition fails during activation; it never degrades to a default value. - Host consumers avoid repeated whole-registry snapshots and log scans. - Wire payloads exclude host-only fields and per-key watermark wrappers; ordinary baselines communicate the active key set. +- One committed event produces at most one Remote projection frame per Session, whose `seq` is that event's sequence number. diff --git a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.zh.md b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.zh.md index c30f7bd35d..26644a05d9 100644 --- a/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-19-session-projection-mandatory-seam.zh.md @@ -18,6 +18,8 @@ Status: implemented `onChanged` 只发布客户端可见值的变化。注册变化不会创建第二条 Host 事件流或客户端 tombstone 协议。后续权威 history 或 list 基线会反映活跃 key 集。 +`onEventChanged` 把一个已提交事件的变化归为一组。所有单元驱动完成后,它按注册顺序收到视图发生变化的每个客户端可见 key 一项 `{ key, val }`,`val` 是该 key 的视图。某个单元或 `onChanged` 监听器抛错时,它仍会收到抛错前已收集的各项。Remote projection 帧沿用这一分组:`session/control` 与 `session/observeProjections` 每个已提交事件发出一帧,携带由同样各项组成的 `changes` 数组,因此 Client 一次应用一个事件的变化,Session 列表只发布一次,而不是每个 key 一次。每项都写明自己的 key,因此改为 `null` 的 key 与未变化的 key 可以区分,消费方也不必按位置把值和 key 配对。`onChanged` 保留给只关心单个 key 的 Host 消费方。 + ## 考虑过的替代方案 - **为缺失的投影状态提供默认值。** 这会保留更多不完整组合,但缺失 host 状态将无法与合法空值区分。正式 profile 已挂载注册表,配置错误必须显式失败,因此否决。 @@ -25,9 +27,14 @@ Status: implemented - **每次读取都使用 `snapshot()`。** 这只保留一个方法,但会计算无关 wire view,并鼓励消费方让 host 逻辑依赖批量传输数据。改用类型化单 key 状态读取。 - **向客户端发送完整 host 值。** 这避免单独的 view 类型,但会暴露客户端不消费的来源信息和策略旋钮。改用显式裁剪的 view。 - **跨 Host 和 mux stream 广播注册表新增和移除。** 两条 stream 没有共享顺序,客户端因此需要 tombstone、缓冲帧和基线重试来协调。插件 key 变化不值得引入第二套同步协议。 +- **在 controller 或 Client 中合并逐 key 帧。** 按 microtask 攒批或按序号分组都需要缓冲和时序假设,而注册表本来就知道每个事件的驱动在哪里结束。改为在驱动处分组。 +- **把帧内的变化做成 key 到值的对象。** 消费方要从对象成员推断哪些 key 变化,也会丢失注册顺序。改用有序的 `{ key, val }` 数组。 +- **使用平行的 `keys` 与 `values` 两个数组。** 这样不必重复每项的字段名,但每个消费方都要按下标保持两个数组对齐,线路类型也无法表达两者等长。改用自带 key 的各项。 +- **用事件级变更流取代 `onChanged`。** forge 等 Host 消费方只关心单个 key,分组对它们没有好处。两条变更流都保留。 ## 后果 - 缺少投影组合会在激活期间失败,绝不会降级为默认值。 - host 消费方避免重复的全注册表快照和日志扫描。 - 协议负载排除 host 内部字段和逐 key 水位包装;普通基线会传达活跃 key 集。 +- 一个已提交事件对每个 Session 至多产生一个 Remote projection 帧,其 `seq` 是该事件的序号。 diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml index c67dff0722..0bb6fa05e0 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.i18n.yaml @@ -30,8 +30,8 @@ en: efded09f0cd30a8e zh: 5e16580a39ff3359 /agent-note-session-observations-and-projection-owned-client-state/decision/client-merge-rules: - en: fb8740be674e4708 - zh: 7dc0c89558f51792 + en: 135a93a2acecaf2a + zh: 87b69116a64b80b5 /agent-note-session-observations-and-projection-owned-client-state/decision/domain-applications: en: 4dcae9e00148b11e zh: acfd1b6831cf50fe diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md index 530aeb36e1..f10764daab 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.md @@ -106,7 +106,7 @@ These distinctions prevent one overloaded `undefined` from representing cache mi |---|---|---|---| | Session list hints | Partial | Last durable checkpoint or bounded fallback cut | Unknown | | Follow opening baseline | Complete for the Host composition | Exact opening cursor | Capability absent | -| Projection frame | One whole key | Event sequence carried by the frame | Not applicable | +| Projection frame | Every key the frame lists, each a whole value | Event sequence carried by the frame | Unchanged | The Client stores one row per key. A row the connected Host computed carries its sequence number: a newer baseline or frame replaces it, an equal or older input is ignored, and reconnect can therefore replace the event window without rolling back a projection frame that was already accepted at a later sequence. A list hint viewed from the persisted cache carries no comparable sequence number and yields to every Host-sequenced write ([projection cache listing identity and cached rows](2026-09-19-projection-cache-listing-identity-and-cached-rows.md)). diff --git a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md index 62ac9db852..96b4a70242 100644 --- a/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-25-session-observations-and-projection-owned-client-state.zh.md @@ -106,7 +106,7 @@ Projection 的三种交付状态含义不同: |---|---|---|---| | Session list hints | 部分 | 上次持久 checkpoint 或有界 fallback cut | 未知 | | Follow opening baseline | 对当前 Host composition 完整 | 精确 opening cursor | Capability 不存在 | -| Projection frame | 单个完整 key | Frame 携带的 event sequence | 不适用 | +| Projection frame | 帧列出的每个 key,各为完整值 | Frame 携带的 event sequence | 未变化 | Client 为每个 key 保存一行。由建连 Host 算出的行带 sequence number:更新的 baseline 或 frame 会替换它,相同或更旧的输入被忽略,因此 reconnect 可以替换 event window,而不会回退已经在更晚 sequence 接受的 projection frame。从持久化缓存看出来的 list hint 不带可比的 sequence number,让位于所有 Host 排序过的写入([Projection cache 只读面按 lifecycle 身份匹配,客户端 store 区分 cached 与 sequenced 行](2026-09-19-projection-cache-listing-identity-and-cached-rows.zh.md))。 diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml index 260adf6610..97e7927b58 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md /agent-note-adjacent-agents-share-one-steer-send-message-operation: - en: 758d31ae04ce0d4f - zh: 112475efbd52b9f6 + en: 9d0af2bae38b1eec + zh: 8a6e8502a5195548 /agent-note-adjacent-agents-share-one-steer-send-message-operation/problem: - en: c988b8a3be4e6f19 - zh: b58011fd8d2e878e + en: 5dc4c218f648c27e + zh: b48531fac94b25db /agent-note-adjacent-agents-share-one-steer-send-message-operation/decision: - en: 1188c699ce6e6ca2 - zh: 4d5b974cd1216f06 + en: f4789878ac0e79b2 + zh: 68eb68d34cba810d /agent-note-adjacent-agents-share-one-steer-send-message-operation/decision/one-model-tool-and-one-return-instruction: - en: 4b0a25389324fa91 - zh: c2cdd9f7e40ef43b + en: 62284bd7dd804188 + zh: b3a8dfebffc01bdb /agent-note-adjacent-agents-share-one-steer-send-message-operation/decision/complete-removal-and-reintroduction-condition: - en: 5a9ec6478cf7430c - zh: f4c2f067cc72040e + en: 8c6d355d91ec83d2 + zh: fcc74d1e6ef477bf /agent-note-adjacent-agents-share-one-steer-send-message-operation/alternatives-considered: - en: 1f62d5d938144666 - zh: dec0f30228c5b7a7 + en: 7386e88e7051dce7 + zh: dcea5b9e30374be3 /agent-note-adjacent-agents-share-one-steer-send-message-operation/consequences: - en: d55de74742c3af4b - zh: d894f9a33c8e4691 + en: 9c23dd6ace029ec3 + zh: f08ef3f142534843 diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md index 4efb9d334e..a4cfbc91cb 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.md @@ -4,26 +4,25 @@ Status: implemented English | [中文](2026-08-27-adjacent-agent-steer-messaging.zh.md) +The adjacency, discovery, and parent-lifetime restrictions below are superseded by [tree-wide communication](2026-10-16-tree-wide-agent-communication.md); the remaining decisions stay active. The tool identity marker and initial-task communication guidance below are superseded by [tool-owned communication](2026-10-22-subagent-tool-owned-communication.md). + ## Problem Continuable Agents originally used direction-specific model controls. A parent called `send_message({ subagent_id, message })`, which delegated to a FIFO `followup` service operation. A child instead received a child-scoped `report({ output })` tool, a `tool:report` system-prompt section, and deployment-selected quiet or waking delivery. The tools described one adjacent-Agent operation through different schemas, service paths, source attribution, and scheduling. -A continuable child owns its own Session, so its parent does not automatically receive the child's transcript, tool output, or reasoning. The return path must therefore remain explicit and repeatable: a child may send progress before it finishes, remain available after sending, or fail before it can cooperate. Turning every final assistant message into an implicit result would conflate turn completion with model-selected communication and would not cover abnormal endings. +A continuable child owns its own Session, so its parent does not automatically receive the child's transcript, tool output, or reasoning. Explicit messages let a child send actionable findings before finishing. The runtime separately delivers terminal output in a settlement notice when the direct creator is still online. The child-only tool and system-prompt section also preceded every inherited fork turn. They made a continuable fork child's request head differ from its parent's before the history that fork exists to reuse, forcing the provider to prefill the entire copied transcript again. ## Decision -`SubagentRuntime.sendMessage(sender, targetId, content, { signal })` is the only public model-authored message operation. The continuation manager accepts only the exact live sender and a target on one adjacent edge: +`SubagentRuntime.sendMessage(sender, targetId, content, { signal })` is the only public model-authored message operation. The continuation manager accepts only the exact live sender and a target in the same root tree; [tree-wide communication](2026-10-16-tree-wide-agent-communication.md) owns authorization and discovery. -- parent to direct continuable child, authorized by the child's durable `SessionHeader.parentSession`; -- resident continuable child to its exact live direct parent, authorized by the child's Activation. +Self-targets, stale Agent objects, unknown targets, and external executions are not alternate routes. The operation has no caller-supplied source, delivery mode, offline root mailbox, or provider dispatch. -Siblings, self-targets, ancestors beyond one edge, stale Agent objects, unknown targets, and one-shot children are not alternate routes. The operation has no caller-supplied source, delivery mode, offline parent mailbox, or provider dispatch. +Every accepted message uses `Agent.steer()`. A running target receives it at the nearest step boundary; an idle target starts a turn. An absent target is cold-resumed under the root before the same Steer delivery; its creation ancestors can remain offline. The manager retains waking-send accounting so a continuation-managed target cannot settle between synchronous inbox insertion and driver admission. -Every accepted message uses `Agent.steer()`. A running target receives it at the nearest step boundary; an idle target starts a turn. An absent direct child is cold-resumed through the existing continuation lifecycle before the same Steer delivery. The manager retains waking-send accounting so a continuation-managed target cannot settle between synchronous inbox insertion and driver admission. - -Every direction uses one durable source. The service derives `senderSessionId` from the authorized Agent and frames the model-visible content as `Agent sent a message:`, so attribution cannot diverge from authority. +Every direction uses one durable source. The service derives `senderSessionId` from the exact live sender and frames content as `Agent sent a message:`. ```ts import type { SessionId } from '@deepseek-ai/dsh-session' @@ -46,15 +45,15 @@ interface SendMessageInput { } ``` -Parents and children inherit the same definition in the same registry order. The standard definition carries a process-stable internal identity that a scoped same-name tool does not satisfy. An independently selected preset may omit the tool, a historical descriptor filter may remove it on resume, and a scoped replacement may provide different semantics; neither case receives the standard call instruction. When the standard tool remains visible, the continuation manager appends the JSON-encoded direct parent id and the instruction to send one self-contained result before finishing, plus earlier actionable findings, to the child's initial user task. For a fork child this task follows the inherited completed-turn prefix; no child-only system-prompt section or tool schema precedes that prefix. +Parents and children inherit the same definition in the same registry order. The standard definition carries a process-stable internal identity that a scoped same-name tool does not satisfy. An independently selected preset may omit the tool, a historical descriptor filter may remove it on resume, and a scoped replacement may provide different semantics; none receives the standard call instruction. When the standard tool remains visible, the continuation manager appends the JSON-encoded direct parent id, automatic final-answer delivery conditions, and guidance to send earlier actionable findings to the child's initial user task. For a fork child this task follows the inherited completed-turn prefix; no child-only system-prompt section or tool schema precedes that prefix. -The instruction is guidance, not settlement enforcement. Sending does not end the child's turn, zero or several calls remain mechanically valid, and the runtime never rejects a child for staying silent. The manager-owned `subagent-settled` notice remains unconditional and separately attributed because it records how an Activation ended and preserves terminal output when the child cannot cooperate. +The instruction is guidance, not settlement enforcement. Sending does not end the child's turn, zero or several calls remain mechanically valid, and the runtime never rejects a child for staying silent. The separately attributed `subagent-settled` notice records the Activation's outcome and terminal output only when its direct creator is still online and delivery is `parent`. Human browser prompts are not model-authored Agent messages. The remote prompt path keeps a private Queue delivery so each human prompt remains a distinct turn. Interrupt behavior and settlement delivery remain independent. ### Complete removal and reintroduction condition -The standalone `@deepseek-ai/dsh-tool-subagent-report` package, `report` schema, `tool:report` prompt section, `reportDelivery` configuration, report-specific message source, catalog entries, composition rows, and supported-behavior snapshots are absent. The unified tool gives up the recipient-free child shortcut and the old ability for a structural return tool to survive an explicit child allow-list. Those capabilities return only if a concrete use case requires semantics that an adjacent `agent_id` and fixed Steer cannot express; reintroducing them requires a distinct model operation and prefix-cost evidence, not an alias over `sendMessage()`. +The standalone `@deepseek-ai/dsh-tool-subagent-report` package, `report` schema, `tool:report` prompt section, `reportDelivery` configuration, report-specific message source, catalog entries, composition rows, and supported-behavior snapshots are absent. The unified tool gives up the recipient-free child shortcut and the old ability for a structural return tool to survive an explicit child allow-list. Those capabilities return only if a concrete use case requires semantics that a tree member’s `agent_id` and fixed Steer cannot express; reintroducing them requires a distinct model operation and prefix-cost evidence, not an alias over `sendMessage()`. ## Alternatives considered @@ -64,16 +63,16 @@ The standalone `@deepseek-ai/dsh-tool-subagent-report` package, `report` schema, **Make `report` global.** Roots, one-shot children, remote children, and agentless callers cannot derive a report recipient. Advertising it globally would make schema visibility disagree with authority, while `send_message` already makes the recipient explicit. -**Turn every child final message into an implicit send.** A long-lived child may have nothing useful to send in one turn and several findings in another. Automatic delivery would merge model-authored communication with the runtime's settlement account and could not replace the unconditional notice on errors, cancellation, or token exhaustion. +**Treat the final answer as a model-authored send.** A settlement notice must preserve terminal output and abnormal endings even when the child cannot cooperate. It keeps runtime attribution distinct from findings the child explicitly chose to send. -**Rely only on the tool description.** A tool description helps after the model considers that tool; the failure mode is a child that believes it is finished without considering any return call. Initial-task guidance reaches that decision without changing the inherited system or tool prefix. +**Rely only on the tool description.** A tool description helps after the model considers that tool; initial-task guidance also explains which earlier findings should reach the parent and what the final answer must contain, without changing the inherited system or tool prefix. **Keep quiet delivery as deployment policy.** A quiet model-authored message can be accepted while an idle target never reads it. Fixed Steer gives both directions one delivery meaning and preserves accepted order with later settlement notices. ## Consequences - Model consumers expose one `send_message({ agent_id, message })` definition to parents and children, with no model-selected Queue versus Steer parameter. -- The continuation manager remains the sole owner of adjacency authorization, residency, cold resume, waking admission, and teardown races. +- The continuation manager remains the sole owner of tree authorization, residency, cold resume, waking admission, and teardown races. - Accepted messages may extend a running target's current turn; messages waiting together share next-step FIFO ordering. - Caller cancellation owns work only until inbox acceptance and does not retract an accepted message or dispose the target. - The initial task carries JSON-encoded dynamic parent addressing after a fork prefix, while the request-head system prompt and tool ordering remain reusable. diff --git a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md index b7ed157f54..d907eaeac0 100644 --- a/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-27-adjacent-agent-steer-messaging.zh.md @@ -4,26 +4,25 @@ Status: implemented [English](2026-08-27-adjacent-agent-steer-messaging.md) | 中文 +邻接消息、发现范围和父子生命周期限制已由[整树通信](2026-10-16-tree-wide-agent-communication.zh.md)替代;其余决策仍然有效。 下文的工具身份标记和初始任务通信指导由[工具拥有通信指导](2026-10-22-subagent-tool-owned-communication.zh.md)取代。 + ## 问题 可继续 Agent 最初使用方向专属的模型控制。parent 调用 `send_message({ subagent_id, message })`,委托给 FIFO `followup` 服务操作。child 则获得 child 作用域的 `report({ output })` 工具、`tool:report` 系统提示词 section,以及由部署选择的静默或唤醒投递。两个工具用不同 schema、服务路径、来源与调度描述同一个相邻 Agent 操作。 -可继续 child 拥有自己的 Session,因此 parent 不会自动收到 child 的 transcript(文本记录)、工具输出或推理。返回路径必须保持显式且可重复:child 可以在结束前发送进度、发送后仍保持可用,也可能在来得及配合前失败。把每条最终 assistant 消息变成隐式结果会混淆轮次完成与模型选择的通信,而且无法覆盖异常结束。 +可继续 child 拥有自己的 Session,因此 parent 不会自动收到 child 的 transcript(文本记录)、工具输出或推理。显式消息让 child 在结束前发送可操作的发现。直接创建者仍在线时,runtime 另行通过结算通知投递终态输出。 child 专属工具与系统提示词 section 还位于每个继承 fork 轮次之前。它们让可继续 fork child 的请求头在 fork 旨在复用的历史之前就与 parent 不同,迫使提供方重新预填充整份复制 transcript。 ## 决策 -`SubagentRuntime.sendMessage(sender, targetId, content, { signal })` 是唯一公开的模型编写消息操作。继续执行管理器只接受确切在线 sender 与一条相邻边上的目标: +`SubagentRuntime.sendMessage(sender, targetId, content, { signal })` 是唯一公开的模型编写消息操作。继续执行管理器只接受确切在线 sender 与同一根树中的目标;[整树通信](2026-10-16-tree-wide-agent-communication.zh.md)负责授权与发现规则。 -- parent 到直接可继续 child,由 child 的持久化 `SessionHeader.parentSession` 授权; -- 驻留的可继续 child 到其确切在线直接 parent,由 child 的 Activation 授权。 +自身目标、过期 Agent 对象、未知目标和外部执行不是替代路由。操作不接受调用方提供的 source、投递模式、离线根邮箱或提供方分发。 -sibling、自身目标、超过一条边的 ancestor、陈旧 Agent 对象、未知目标与一次性 child 都不是替代路由。该操作没有调用方提供的 source、投递模式、离线 parent mailbox 或提供方分发。 +每条被接受的消息都使用 `Agent.steer()`。运行中目标在最近 step 边界接收消息;空闲目标启动轮次。不在线目标先在根下冷恢复,再接受同一 Steer 投递;其创建祖先可以保持离线。管理器保留唤醒发送记账,因此受继续执行管理的目标不会在同步 inbox 插入与 driver 准入之间结算。 -每条被接受的消息都使用 `Agent.steer()`。运行中目标在最近 step 边界接收消息;空闲目标启动轮次。缺失的直接 child 会先通过现有继续执行生命周期冷恢复,再接受同一 Steer 投递。管理器保留唤醒发送记账,因此受继续执行管理的目标不会在同步 inbox 插入与 driver 准入之间结算。 - -两个方向使用同一种持久来源。服务从已授权 Agent 推导 `senderSessionId`,并把模型可见内容组装为 `Agent sent a message:`,因此来源信息不会偏离权限。 +所有方向使用同一种持久 source。服务从确切在线发送方推导 `senderSessionId`,并以 `Agent sent a message:` 包装内容。 ```ts import type { SessionId } from '@deepseek-ai/dsh-session' @@ -46,15 +45,15 @@ interface SendMessageInput { } ``` -parent 与 child 以相同注册表顺序继承相同定义。标准定义携带进程稳定的内部身份,同名的作用域工具不满足该身份。独立选择的 preset 可以省略该工具,历史 descriptor 过滤器可在恢复时移除该工具,作用域替代工具也可以提供不同语义;两种情况都不会收到标准调用指令。当标准工具仍可见时,继续执行管理器会把经过 JSON 编码的直接 parent id、结束前发送一份自包含结果的指令,以及更早发送可操作发现的指令追加到 child 初始用户任务。对 fork child 而言,该任务位于继承的已完成轮次前缀之后;没有 child 专属系统提示词 section 或工具 schema 位于此前缀之前。 +parent 与 child 以相同注册表顺序继承相同定义。标准定义携带进程稳定的内部身份,同名的作用域工具不满足该身份。独立选择的 preset 可以省略该工具,历史 descriptor 过滤器可在恢复时移除该工具,作用域替代工具也可以提供不同语义;这些情况都不会收到标准调用指令。当标准工具仍可见时,继续执行管理器会把经过 JSON 编码的直接 parent id、最终回答的自动投递条件,以及提前发送可操作发现的指导追加到 child 初始用户任务。对 fork child 而言,该任务位于继承的已完成轮次前缀之后;没有 child 专属系统提示词 section 或工具 schema 位于此前缀之前。 -该指令是指导,不是结算强制。发送不会结束 child 轮次,机制仍允许零次或多次调用,runtime 绝不会因 child 保持沉默而拒绝它。由管理器负责的 `subagent-settled` 通知仍无条件发送并采用独立来源,因为它记录 Activation 如何结束,并在 child 无法配合时保留终态输出。 +该指令是指导,不是结算强制。发送不会结束 child 轮次,机制仍允许零次或多次调用,runtime 绝不会因 child 保持沉默而拒绝它。采用独立来源的 `subagent-settled` 通知仅在直接创建者仍在线且投递方式为 `parent` 时,记录 Activation 的结果与终态输出。 浏览器中的人类提示不是模型编写的 Agent 消息。远程提示路径保留私有 Queue 投递,使每条人类提示保持为独立轮次。中断行为与结算投递保持独立。 ### 完整移除与重新引入条件 -独立的 `@deepseek-ai/dsh-tool-subagent-report` 包、`report` schema、`tool:report` 提示词 section、`reportDelivery` 配置、report 专属消息来源、目录项、组合行和受支持行为快照均已不存在。统一工具放弃了无需接收方的 child 快捷方式,也放弃了让结构性返回工具绕过显式 child allow-list 的旧能力。只有具体用例需要相邻 `agent_id` 与固定 Steer 无法表达的语义时,这些能力才会重新出现;重新引入需要独立的模型操作与前缀成本证据,而非 `sendMessage()` 之上的别名。 +独立的 `@deepseek-ai/dsh-tool-subagent-report` 包、`report` schema、`tool:report` 提示词 section、`reportDelivery` 配置、report 专属消息来源、目录项、组合行和受支持行为快照均已不存在。统一工具放弃了无需接收方的 child 快捷方式,也放弃了让结构性返回工具绕过显式 child allow-list 的旧能力。只有具体用例需要树成员的 `agent_id` 与固定 Steer 无法表达的语义时,这些能力才会重新出现;重新引入需要独立的模型操作与前缀成本证据,而非 `sendMessage()` 之上的别名。 ## 考虑过的替代方案 @@ -64,16 +63,16 @@ parent 与 child 以相同注册表顺序继承相同定义。标准定义携带 **让 `report` 全局可见。** 根 Agent、一次性 child、远程 child 与无 Agent 调用方无法推导 report 接收方。全局宣传它会让 schema 可见性与权限不一致,而 `send_message` 已显式给出接收方。 -**把每条 child 最终消息变成隐式发送。** 长期运行的 child 可能在某个轮次没有值得发送的内容,在另一个轮次却有多条发现。自动投递会混合模型编写通信与 runtime 结算说明,而且无法替代错误、取消或 token 耗尽时的无条件通知。 +**将最终回答当作模型编写的发送。** 即使 child 无法配合,结算通知仍须保留终态输出与异常结束信息。它将 runtime 来源与 child 显式选择发送的发现区分开。 -**只依赖工具描述。** 工具描述会在模型考虑该工具后提供帮助;失败模式是 child 认为自己已经完成而根本没有考虑返回调用。初始任务指导能触及该决策,又不会改变继承的系统或工具前缀。 +**只依赖工具描述。** 工具描述会在模型考虑该工具后提供帮助;初始任务指导还说明哪些早期发现应发送给 parent,以及最终回答须包含什么,又不会改变继承的系统或工具前缀。 **保留静默投递作为部署策略。** 静默的模型编写消息可能被接受,但空闲目标永远不会读取它。固定 Steer 为两个方向提供一种投递含义,并保持与后续结算通知的接受顺序。 ## 后果 - 模型 Consumer 向 parent 与 child 公开一个 `send_message({ agent_id, message })` 定义,不提供模型选择的 Queue 与 Steer 参数。 -- 继续执行管理器仍是相邻关系授权、驻留、冷恢复、唤醒准入与拆卸竞态的唯一所有者。 +- 继续执行管理器仍是整树授权、驻留、冷恢复、唤醒准入与拆卸竞态的唯一所有者。 - 被接受的消息可以延长运行中目标的当前轮次;一起等待的消息共享 next-step FIFO 顺序。 - 调用方取消只在 inbox 接受前掌管工作,不会撤回已接受消息或 dispose(资源释放)目标。 - 初始任务在 fork 前缀之后携带经过 JSON 编码的动态 parent 地址,而请求头系统提示词与工具顺序保持可复用。 diff --git a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.i18n.yaml b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.i18n.yaml index ddf55f9063..f8de1ed3b1 100644 --- a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.i18n.yaml @@ -9,14 +9,14 @@ en: 98b49b900b8d2f84 zh: 557faac2976592be /agent-note-explicit-agent-identity-at-runtime-boundaries/decision: - en: 1c628cf9c743c639 - zh: d969b2475fe4a155 + en: 4a3ab5108f37520f + zh: d13fcd448101a95d /agent-note-explicit-agent-identity-at-runtime-boundaries/verification: - en: 85130faaa171036b - zh: 06e5e9fab32dbfb4 + en: ce1733edf03f0387 + zh: 8e1ca2b69e81968e /agent-note-explicit-agent-identity-at-runtime-boundaries/alternatives-considered: - en: 2c41456509d54d21 - zh: 5704ee9a2274e300 + en: 34f5f8571b21897c + zh: cf16094bc0027ca1 /agent-note-explicit-agent-identity-at-runtime-boundaries/consequences: - en: 08ab86b89fc3ec6f - zh: 3866e6557858543a + en: 0b5914067f14282e + zh: c41d21aeb28e357f diff --git a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.md b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.md index 16cd668f65..336151fa83 100644 --- a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.md +++ b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.md @@ -14,34 +14,34 @@ Without an explicit owner, `SubagentManager` creates and resumes children throug ## Decision -Runtime interfaces carry Agent identity at the point that owns it. `AgentSetup` receives `(agentCtx, agent)`; Agent creation and resume options carry `parentAgent` for a runtime child; scoped events carry their Agent in the payload; Remote forwarding verifies that `request.agent` is the carrier key; and Host Typert Context resolution maps wire identity to a live Agent Context without a reverse scan. `agent.ctx` remains the registration and lifecycle owner and exposes no reverse Agent property. +Runtime interfaces carry Agent identity at the point that owns it. `AgentSetup` receives `(agentCtx, agent)`; each subagent Activation retains its exact runtime root; scoped events carry their Agent in the payload; Remote forwarding verifies that `request.agent` is the carrier key; and Host Typert Context resolution maps wire identity to a live Agent Context without a reverse scan. `agent.ctx` remains the registration and lifecycle owner and exposes no reverse Agent property. -Scope-aware registries continue to use the opaque scope key only for registration membership. Tool-subagent does not classify that key or resolve an Agent from Context. A direct `AgentSetup` passes the unpublished Session explicitly and installs through the supplied Context before publication. For a settings-backed standing preset, the event payload supplies the Agent, its Session supplies the policy target, and its Context owns the registrations. +Scope-aware registries continue to use the opaque scope key only for registration membership. Tool-subagent does not classify that key or resolve an Agent from Context. A direct `AgentSetup` receives the Agent explicitly and installs through the supplied Context before Agent publication. For a settings-backed standing preset, the event payload supplies the Agent, its Session supplies the policy target, and its Context owns the registrations. -`SubagentManager` puts the exact parent in both fresh-creation and cold-resume options. A live continuable child is therefore excluded from `AgentRegistry.roots()` and satisfies `isOwnedBy(child.id, parent)`. Durable `parentSession` metadata does not substitute for this relation: a fork or resumed Session may be a runtime root when no live Agent owns it. +`SubagentManager.rootOf(agent)` reads runtime membership from existing Activations; both the child and root must match their live registry objects. Ordinary Sessions resolve to themselves, and unmanaged subagent headers grant no membership. Durable `parentSession` describes creation edges; an Activation retains the exact root while intermediate creators are offline, and same-id replacements cannot inherit it. Root-only consumers classify the explicit subagent origin. The [scope reference](../../../../packages/core/scope/README.md) and [Agent loop reference](../../../../packages/core/agent-loop/README.md) document registration and lifecycle behavior. The [initiator-scope decision](2026-07-15-agent-initiator-scope.md) owns private-chain rationale; explicit runtime ownership does not change causal initiation or registration lifetime. ## Verification -Agent creation tests pin explicit root and child ownership. Continuation integration tests keep a real child live long enough to assert both `roots()` exclusion and `isOwnedBy()` membership. Existing Schedule tests verify that root-only registrations stay absent from an explicitly owned child. +Managed-child tests verify intermediate-creator disposal and exact-instance checks after child or root replacement. SDK approval tests verify routing during a turn after the direct creator exits. Schedule and user-question tests reject delegated Sessions while ordinary historical forks remain independent. -Remote-event tests reject a missing or mismatched Agent before forwarding a scoped waterfall. Tool-subagent tests verify that direct setup installs before Session publication; standing-preset tests verify per-Session policy sampling and inheritance. +Remote-event tests reject a missing or mismatched Agent before forwarding a scoped waterfall. Tool-subagent tests verify that direct setup installs before Agent publication; standing-preset tests verify per-Session policy sampling and inheritance. ## Alternatives considered **Keep `Context.agent`.** A reverse accessor makes registration ownership look like operation identity and requires every Context derivation, adapter, and test double to preserve an association unrelated to Cordis service selection or effect cleanup. -**Infer runtime ownership from the caller Context.** A private manager Context, an Agent Context, and a standing preset Context can all call the same factory. Context ancestry therefore does not state which live Agent owns the result; the creator must put the parent it already knows in the request options. +**Infer runtime ownership from the caller Context.** A private manager Context, an Agent Context, and a standing preset Context can all call the same factory. Context ancestry therefore does not state which live Agent owns the result; the subagent Activation retains the exact root supplied at admission. **Classify Agent scope keys.** An opaque scope key states routing membership, not domain identity. Classifying it would make Agent the center of composition and would still couple a plugin's effect owner to the Session whose policy it needs. **Use the initiating Agent as creation ownership.** Initiator scope records causal asynchronous execution, not lifetime ownership. A parent may initiate work that intentionally creates a root, and setup remains outside the child's driver boundary. -**Use durable Session lineage.** `parentSession` records conversation ancestry across process lifetimes. Runtime ownership controls live roots and teardown, so equating the two would prevent a legitimately resumed fork from becoming a top-level Agent. +**Use durable Session lineage.** `parentSession` records creation ancestry across process lifetimes. An intermediate creator can be offline while its descendant remains managed by a live root; durable ids also cannot distinguish replaced Agent instances. Historical ordinary forks may retain parent metadata without being delegated. ## Consequences Lifecycle options, events, service requests, and transport requests carry explicit Agent identities, so each operation states the identity it uses and TypeScript checks both sides. Context remains reusable for dependency access and effect ownership without becoming an alternate domain-object locator. -Continuable children have the same runtime parent relation as one-shot in-process children. Root-only consumers exclude them, parent teardown can reason from one live ownership graph, and durable lineage remains free to describe history rather than process-local lifetime. +Continuable children have one runtime root independent of creator residency. The subagent manager owns tree teardown and local membership; the core factory and registry retain only instance creation, publication, and disposal. Third-party callers create managed children through the subagent service rather than assigning ownership to arbitrary factory-created Agents. diff --git a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.zh.md b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.zh.md index 3d4131af01..063f0490bb 100644 --- a/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.zh.md +++ b/.agents/notes/implemented/architecture/2026-08-31-explicit-agent-runtime-identity.zh.md @@ -14,34 +14,34 @@ Agent 的 Cordis Context 拥有注册及其清理。Agent 身份则为某项操 ## 决策 -运行时接口在拥有身份的位置携带 Agent 身份。`AgentSetup` 接收 `(agentCtx, agent)`;创建与恢复 Agent 的 options 通过 `parentAgent` 标识运行时子级;作用域事件在 payload 中携带 Agent;Remote 转发校验 `request.agent` 就是 carrier key;Host Typert Context 解析则把协议身份映射到存活 Agent Context,不执行反向扫描。`agent.ctx` 继续拥有注册和生命周期,不暴露反向 Agent 属性。 +运行时接口在拥有身份的位置携带 Agent 身份。`AgentSetup` 接收 `(agentCtx, agent)`;每个 subagent Activation 保留其确切运行时树根;作用域事件在 payload 中携带 Agent;Remote 转发校验 `request.agent` 就是 carrier key;Host Typert Context 解析则把协议身份映射到存活 Agent Context,不执行反向扫描。`agent.ctx` 继续拥有注册和生命周期,不暴露反向 Agent 属性。 -感知作用域的注册表继续仅使用不透明作用域键判断注册成员关系。tool-subagent 不会分类该键,也不会从 Context 解析 Agent。直接 `AgentSetup` 显式传入尚未发布的 Session,并在发布前通过所给 Context 完成安装。对于由设置控制的常驻 preset,事件 payload 提供 Agent,其 Session 提供策略目标,其 Context 拥有注册项。 +感知作用域的注册表继续仅使用不透明作用域键判断注册成员关系。tool-subagent 不会分类该键,也不会从 Context 解析 Agent。直接 `AgentSetup` 显式接收 Agent,并在 Agent 发布前通过所给 Context 完成安装。对于由设置控制的常驻 preset,事件 payload 提供 Agent,其 Session 提供策略目标,其 Context 拥有注册项。 -`SubagentManager` 会把确切父级放进全新创建与冷恢复的 options。因此,存活的可续跑子级不会出现在 `AgentRegistry.roots()` 中,并且满足 `isOwnedBy(child.id, parent)`。持久化 `parentSession` 元数据不能代替这项关系:没有存活 Agent 拥有 fork 或已恢复会话时,它仍可成为 runtime root。 +`SubagentManager.rootOf(agent)` 从已有 Activation 读取运行时成员关系;子级和树根都必须匹配注册表中的存活对象。普通 Session 返回自身,非托管的 subagent header 不授予成员身份。持久化 `parentSession` 描述创建关系;中间创建者离线时,Activation 保留确切树根,同 id 替代实例不能继承它。仅限根级的消费方依据显式 subagent 来源分类。 [作用域参考](../../../../packages/core/scope/README.zh.md)与 [Agent loop 参考](../../../../packages/core/agent-loop/README.zh.md)说明注册和生命周期行为。[发起方作用域决策](2026-07-15-agent-initiator-scope.zh.md)负责私有调用链理由;显式运行时归属不改变因果发起关系或注册生命周期。 ## 验证 -Agent 创建测试锁定显式的根级与子级归属。continuation 集成测试让一个真实子级保持存活,直到断言其既不属于 `roots()`、又满足 `isOwnedBy()`。现有 Schedule 测试验证仅限根级的注册项不会出现在显式归属的子级中。 +托管子级测试验证中间创建者释放,以及子级或树根替换后的确切实例检查。SDK 审批测试验证直接创建者退出后的轮次内路由。Schedule 与用户问题测试拒绝委派 Session,历史普通 fork 则保持独立。 -Remote 事件测试会在转发作用域 waterfall 前拒绝缺失或不匹配的 Agent。tool-subagent 测试验证 direct setup 会在 Session 发布前完成安装;常驻 preset 测试验证逐 Session 的策略读取与继承。 +Remote 事件测试会在转发作用域 waterfall 前拒绝缺失或不匹配的 Agent。tool-subagent 测试验证 direct setup 会在 Agent 发布前完成安装;常驻 preset 测试验证逐 Session 的策略读取与继承。 ## 考虑过的替代方案 **保留 `Context.agent`。** 反向 accessor 会让注册所有权看起来等同于操作身份,还要求每个 Context 派生、适配器和测试替身保留一项与 Cordis 服务选择或 effect 清理无关的关联。 -**从调用方 Context 推断运行时归属。** 私有管理器 Context、Agent Context 和常驻 preset Context 都能调用同一个工厂。因此,Context 祖先关系无法说明由哪个存活 Agent 拥有结果;创建方必须把它已知的父级放进请求 options。 +**从调用方 Context 推断运行时归属。** 私有管理器 Context、Agent Context 和常驻 preset Context 都能调用同一个工厂。因此,Context 祖先关系无法说明由哪个存活 Agent 拥有结果;subagent Activation 保留准入时传入的确切树根。 **分类 Agent 作用域键。** 不透明作用域键表达路由成员关系,而不是领域身份。分类该键会让 Agent 成为组合中心,也仍会把插件的 effect 所有者与策略所需的 Session 耦合起来。 **使用发起 Agent 作为创建归属。** 发起方作用域记录异步执行的因果关系,而非生命周期归属。父级可能发起有意创建根级 Agent 的工作,而 setup 仍位于子级驱动边界之外。 -**使用持久化会话谱系。** `parentSession` 跨进程生命周期记录对话祖先关系。运行时归属控制存活根级和 teardown,因此把二者等同会阻止合法恢复的 fork 成为顶层 Agent。 +**使用持久化会话谱系。** `parentSession` 跨进程生命周期记录创建祖先关系。中间创建者可以离线,而后代仍由存活树根管理;持久 id 也无法区分替换后的 Agent 实例。历史普通 fork 可能保留父级元数据,但并不属于委派。 ## 后果 生命周期 options、事件、服务请求和传输请求会携带显式 Agent 身份,因此每项操作都会声明自身使用的身份,TypeScript 也会检查两侧。Context 可以继续复用于依赖访问与 effect 所有权,而不会成为另一种领域对象定位器。 -可续跑子级与一次性进程内子级使用同一种运行时父级关系。仅限根级的消费方会排除这些子级,父级 teardown 可以依据唯一的存活归属图推理,而持久化谱系仍可描述历史,不必承担进程内生命周期语义。 +可续跑子级拥有独立于创建者驻留状态的唯一运行时树根。subagent 管理器拥有整树 teardown 和本地成员关系;核心工厂与注册表仅保留实例创建、发布和释放。第三方调用方通过 subagent 服务创建托管子级,而非给任意工厂创建的 Agent 指定归属。 diff --git a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.i18n.yaml index a59c5e9371..58293afaff 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.i18n.yaml @@ -3,17 +3,17 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md /agent-note-host-owned-scheduled-messages: - en: 11854b220af809ea - zh: 0f0575de37107ed8 + en: b3b0dde47f58ca48 + zh: d4ba3a6cf1228578 /agent-note-host-owned-scheduled-messages/problem: en: 2c774d05ae75784f zh: 619ba7f281b13233 /agent-note-host-owned-scheduled-messages/decision: - en: 1210b3975fd26bb3 - zh: 3322e6d0aa63fdb0 + en: 20dcfc8e9c44cde7 + zh: d9609e41eb4e9bd9 /agent-note-host-owned-scheduled-messages/alternatives-considered: en: 21d7ec9a9ff3cbf2 zh: 93d03b8b3012aa7e /agent-note-host-owned-scheduled-messages/consequences: - en: 3ae0cd93ed95431e - zh: 25a0a2bc25863651 + en: ce4ef02663cd485c + zh: ad8ae567c3bab8e0 diff --git a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md index cd295da249..770d1f9291 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md +++ b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md @@ -4,36 +4,20 @@ Status: implemented English | [中文](2026-09-16-host-schedule-storage.zh.md) +This note remains current for Host authority, whole-unit durability, and saved inbox receipts. [Typed rule storage](2026-10-21-schedule-rule-storage.md) and [Session targets](2026-09-17-standalone-schedules.md) replace its original management and target contracts. + ## Problem Scheduled messages must remain discoverable after restart without loading every Session. A timer attached to a live Agent cannot dispatch a task whose Session remains cold. Users also need to inspect pending and delivered tasks without activating their conversation; removing a task after delivery loses that management record. ## Decision -The existing Schedule package owns one Host storage domain containing each task's original Session id, reminder record, `active` or `inactive` status, latest delivery receipt, and saved delivery history. The domain is authoritative for retained tasks. The Host scheduler restores timers only for active tasks; a due task uses the Session controller's existing resolution operation and queues an ordinary follow-up in the original Session. Querying and deleting tasks do not resolve an Agent. Stored records lacking status normalize to `active` without scanning or recreating historical Sessions. +The original `schedule` domain and whole-unit layout remain authoritative; v2 accepts v1. [Typed rule storage](2026-10-21-schedule-rule-storage.md) supersedes the original Session-owned management API, top-level binding writes, and two-state lifecycle; [Session targets](2026-09-17-standalone-schedules.md) owns Host-wide management and delivery targets. The seven normal timing kinds preserve committed targets. An explicit target wins; absent targets read the old Session binding or reserve a stable new-once identity. No startup migration runs. The task domain declares the whole-unit layout. Tasks are authoritative, so the JSON backend rejects an unreadable file, malformed document, unsupported version, or invalid task as a complete load failure instead of interpreting it as deletion. Failed recovery leaves `schedule.json` unchanged, while an initially absent file opens as an empty domain; repairing the file preserves task identity. `Service.init` waits for both storage validation and runtime setup, management methods wait for the same initialization result, and an unloading owner releases late-acquired storage without starting dispatch. Dispatch admission is separate from initialization: an ancestor can close Agent admission after a task mutation commits but before runtime cleanup starts. That refusal is logged without automatic retry and does not turn the persisted mutation into a failed management result. Invalid storage and failed cleanup registration still reject startup. -This replaces the earlier Session-log authority, live-only activation, and read-only catalog decisions. The [Schedule reference](../../../../packages/schedule/schedule/README.md) owns explicit absolute-time validation, fixed-rate arithmetic, and the distinction between queue admission and model completion. Historical `schedule/change` creation and fold types remain restricted to After, At, and Every through `LegacyScheduleRecord`; a separate Host decoder accepts the current `ScheduleRecord`, including Daily, Weekly, and Cron. The Host record decoder requires a stored `title` that is non-empty after trimming, already trimmed, and at most 120 characters, and the strict task schema rejects the whole domain open instead of dropping such a task. The historical change decoder tolerates an absent `title` so an already-written Session log stays readable, and it applies the same three checks when the member is present. The storage domain remains version 1. Historical events do not populate that domain, and existing `at` tasks are not converted into daily or weekly rules. Loading a Session with active legacy reminders warns that they must be recreated. - -A plugin-sourced `followup()` synchronously appends the message to the Session inbox. Successful Session flush acknowledges durable delivery. One task-record put stores `lastDelivery`, appends a delivery record with the occurrence target, acknowledgment time, actual message id, and instruction snapshot, and updates the one-shot's `inactive` status or the recurring task's next target and status. Task state and its saved history therefore share one commit. Inactive tasks remain stored and never schedule another delivery; explicit deletion stops future delivery and removes the row together with its saved records. These records acknowledge inbox delivery, not user receipt or model execution completion. - New tasks initialize an empty `deliveryHistory`. A task without that optional field exposes its existing latest receipt, if any, and marks earlier records unavailable. Reading never rewrites the old task or invents the lost history or instruction snapshot. Its next acknowledged delivery preserves that available receipt and appends the new one. Strict decoding rejects duplicate message ids and disagreement between the latest receipt and the last history entry. History follows append order, not wall-clock sorting, so clock rollback does not reverse acknowledged deliveries. -A recurring task contributes its latest due occurrence once, including after Host restart. Every remains creation-aligned until an interval edit establishes a new anchor; Daily retains a local time and explicit IANA zone, and Weekly adds a non-empty ISO weekday set stored as unique ascending numbers. Every, Daily, Weekly, and Cron use `renderRecurringReminderBatchFraming` and share one follow-up message and its real message id when due for the same Session. The fixed text both renderers emit is the [delivered-reminder origin line](2026-09-24-scheduled-message-framing.md) decision. A recurring task with no representable next target remains inactive with its last receipt. A stopped Host does not send messages. - -Daily is a fourth mutually exclusive creation selector, Weekly a fifth, and Cron a sixth, none a conversion of `every_seconds` or `at`. Weekly selects every local date whose ISO weekday belongs to its stored set; the decoder rejects an unnormalized stored set, and the selector rejects an empty, repeated, out-of-range, or non-integer one. Their first targets are strictly future. Missing local times and dates are skipped; overlaps select the earlier instant once per date. The next target is after the delivery decision and on a local date later than the selected occurrence's date. Only UTC targets are restricted to years 0001–9999; local dates may cross into year 0 or 10000 at the edges. After Session restoration, the runtime rechecks due members against the current clock so a rollback does not admit future tasks. - -The maintained `@js-temporal/polyfill` 0.5.1 resolves local dates and overlap/gap behavior using the Host's IANA data; Schedule does not own offset-sampling logic or add another package layer. Each daily or weekly record stores normalized `HH:mm:ss.SSS` time, its zone, its weekday set where applicable, and a committed next UTC instant. Decoding and restart do not recompute that instant. Valid zone aliases remain readable across canonical-name changes, while subsequent targets use current Host time-zone data. - -Model `schedule_list`, Remote `list`, and the Session header's right-aligned reminder clock show only active tasks. The independent Automation tasks page opens from the sidebar and reads active and inactive Host tasks through the read-only Remote `catalog` method, without activating Sessions or reading their history. That clock is absent while the Session has no active reminder, opens a single task's detail directly when exactly one remains, and otherwise lists them so one can be chosen; both paths open one right-Sidebar task tab that renders the same detail component the Automation tasks page uses, so neither path selects the main panel. The tab names its task and original Session through its navigation parameters and carries that binding into every mutation, so opening or deleting from it never activates a Session. The page has one All, Enabled, and Inactive status filter row, retained inactive details, latest delivery metadata, and an original-Session control that sits in the detail tab strip beside the task actions. Its header's New action starts a new Session, where the reminder is created by asking the model; the page offers no creation form. Navigation waits for Session and archive metadata, explains unavailable targets, and never restores an archived Session implicitly. Task retention remains independent of original-Session availability. Every, Daily, Weekly, and Cron are recurring rules; the page groups tasks only by status. Daily and Weekly rule labels retain the saved local time, exact rule zone, and stored weekday set rather than substituting the browser zone used for next-target display. Explicit confirmed deletion reuses `delete` with the entry's original Session binding, requiring that the supplied binding match the stored task. This argument check is not independent caller authorization: model tools capture the current Agent's Session, while the global user interface selects the task's original binding. Cross-Session model modification policy remains a product decision, not a consequence of the storage layout. A payload-free change notification invalidates queries, and reconnect queries recover missed notifications. Deletion prevents subsequent dispatch but does not retract a queued message. - -The second detail level separates Rules from Delivery records. Opening records requests `history` with the task's original Session binding and an explicit page limit of 1–100. An exclusive message-id cursor reads older receipts without changing position when new deliveries append. Catalogs retain only latest-receipt metadata rather than duplicating full histories in every task-list response. Missing tasks and unknown cursors are distinct failures, not empty successful history. The records view loads lazily, rejects stale responses, and keeps original-Session navigation separate from inspection. - -Name, instruction, and timing updates share the dispatch and deletion FIFO. Comparing the complete observed record inside that queue prevents a stale draft from overwriting a saved rule or a target advanced by delivery. This avoids adding a persisted revision counter, at the cost of rejecting drafts after normal delivery changes the target. One task put replaces the rule, name, or instruction, preserving identity, original Session binding, status, latest receipt, and saved history. A request may omit the timing change, the name, or the instruction; an omitted field keeps its stored value, and a name or instruction change alone leaves the committed target untouched. Normalized no-ops leave the committed target and stored bytes unchanged. Changed one-shots retain their identity as At records; changed fixed intervals use a new accepted-save anchor; changed wall-clock rules re-resolve their first future target from the same accepted-save sample, and an equivalent normalized rule stays a no-op. A timing change may select a different recurrence kind, and the new rule computes its target exactly as creation would from that accepted-save sample. Deletion removes the row together with its saved records ([consequences of that reversal](2026-09-22-schedule-hard-delete-and-bounded-history.md)), so the runtime never schedules the task again and `history` no longer resolves for its original binding. Inactive tasks are not reopened. - -The page uses the existing Host task domain and scheduler, not a mock engine or a Session projection. The name, the instruction, and the run-time rows edit one local draft for the shown task, and one Save commits that draft as a single update carrying the complete expected record; Cancel restores the stored values, a failed save retains the draft, an unsaved draft survives an authoritative refresh, and a committed save and a failed catalog refresh remain separate outcomes. Pause and execution-history operations remain unsupported. Lifecycle status and latest delivery acknowledgment do not describe model results. - The client presentation derives from existing persisted data instead of widening a persisted format. The `schedule_create` transcript card reads the created task out of the call's model-visible result JSON, which already serializes the canonical task value, rather than declaring `presentationMeta`: a persisted metadata channel would add a durable field for a card that Session-log replay reconstructs from the result alone, and previously recorded Sessions render the card without a format change. The Sidebar Session-row clock mark occupies the root-scoped `sidebar.session.row.leading` seat rather than requesting a per-Session provider, because a Session-scoped seat would bind every listed Session and thereby activate and retain it; the same root-scoped owner share feeds `sidebar.session.row.hover`, and both read the shared Host catalog snapshot `schedule/catalog()` without reading a Session log. Session inbox persistence and the task put occur in separate persistence systems. Inbox persistence precedes the task put to avoid marking delivery before its message exists. A crash or task-write failure after inbox persistence can repeat a message; storing status, target, and receipt together does not make the two stores atomic. Dispatch failures retain the task and produce a diagnostic; there is no independent retry timer. This feature does not create or replace a Goal. @@ -56,10 +40,4 @@ Session inbox persistence and the task put occur in separate persistence systems ## Consequences -**Keep the mock's hourly choice out of the stored vocabulary.** The approved mock lists 每小时整点 beside the daily, weekly and one-shot choices. Hourly and fixed-rate intervals are the same elapsed-time rule, so the card maps that menu slot onto the existing interval kind instead of adding a persisted kind. A dedicated hourly kind would need a new durable variant, its decoder, its target resolution, and its tool schema, all to express what an interval already expresses. - -Task discovery and timers do not depend on loaded Sessions. The after, absolute-time, and fixed-rate selectors retain their semantics alongside Daily, Weekly, and Cron; reading existing saved tasks does not rewrite them. The Host must have its ordinary Session persistence and recovery services available, and the shipped Web composition mounts the Schedule service for the whole deployment. Explicit deletion stops future delivery and removes the task from `list` and `catalog` without deleting conversation messages; the removed row takes its saved receipts with it. History is pruned to the configured window and record cap when an acknowledgment is appended, loaded into Host memory, and rewritten with the task on each acknowledgment. Pagination limits the returned record count; the plugin configuration (`deliveryHistoryDays`, default 30, and `deliveryHistoryRecords`, default 200) limits storage growth. Earlier overwritten receipts and deliveries whose task write failed cannot be reconstructed. Pause and execution-history operations remain unsupported. - -Required coverage includes startup from stored tasks, missing-status normalization, cold Session restoration, latest-only catch-up, inactive-task retention without repeat dispatch, real message receipts, deletion across restart, removal of a deleted task's saved deliveries, queue/persistence failures, and disposal. Wall-clock obligations include gaps and skipped dates, earlier-only overlaps, fractional seconds, UTC-range edges, committed-target and alias preservation, and post-restoration clock rollback. Weekly adds weekday normalization and validation, next-target selection across a gap and an overlap, and stored set preservation. Historical decoders must reject Daily, Weekly, and Cron while Host storage accepts them. Client coverage includes every recurring kind, exact rule time, zone, and weekday set, All/Enabled/Inactive status filters, retained inactive details and original-Session navigation, authoritative refresh after confirmed deletion and notification, empty lists, reconnect, and late responses. Presentation coverage includes the page's New action starting a Session, the transcript card's narrowing of persisted result JSON including an incomplete or replayed result, the header clock's direct open for exactly one task and its count label, the idle-only row mark with the hover-card two-task limit and omission line. History coverage includes legacy byte preservation, append and restart, immutable sent instructions, strict latest-receipt consistency, stable cursor pagination, binding checks, failed persistence, and late page replies during refresh or task changes. Cross-store crash duplication remains an explicit limitation rather than a completion claim. - -Name, instruction, and timing coverage includes all supported rule kinds, complete-record conflicts, delivery/save ordering, cancellation, normalized no-ops, unchanged-history persistence, pending controls, draft retention, and collision-free task identity. The [built CLI process test](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) drives public Remote requests and reloads actual task-file bytes in a fresh Host. Its task and receipt seeds establish retained-data inputs, not real creation, delivery, or recorded-model evidence; those require ordinary Session operations and captured model requests. +Task discovery and timers do not require loaded Sessions. History remains in the same task row and shares its acknowledgment commit; reads never invent missing prompts, timestamps, or earlier deliveries. Historical Session-log After, At, and Every remain frozen and do not populate this domain. The [Schedule reference](../../../../docs/subsystems/schedule.md) owns timing, management, UI projection, and retention contracts. The [built CLI test](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) checks raw old rows, edit-time normalization, conflicts, and cold restart through public Remote requests; seeded receipts are retained-data evidence rather than delivery evidence. diff --git a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.zh.md b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.zh.md index c5ee3ac455..d88c535087 100644 --- a/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.zh.md @@ -4,36 +4,20 @@ Status: implemented [English](2026-09-16-host-schedule-storage.md) | 中文 +本 note 仍拥有宿主权威来源、整单元持久性和已保存收件箱回执。[带类型规则存储](2026-10-21-schedule-rule-storage.zh.md)和 [Session 目标](2026-09-17-standalone-schedules.zh.md)替代原管理与目标契约。 + ## Problem 定时消息必须能在重启后被发现,无须加载每个 Session。挂在 live Agent 上的 timer 无法投递目标 Session 仍为 cold 的任务。用户还需要在不激活对话的情况下查看待投递和已投递任务;投递后删除任务会丢失这条管理记录。 ## Decision -现有 Schedule 包拥有一个 Host storage domain,保存每个任务的原始 Session id、提醒记录、`active` 或 `inactive` 状态,最近一次投递回执,以及已保存的投递历史。该 domain 是保留任务的权威来源。Host scheduler 仅为活动任务恢复 timer;到期任务使用 Session controller 现有的解析操作,在原 Session 中排入普通 follow-up。查询和删除任务不会解析 Agent。已存储但缺少状态的记录规范化为 `active`,不扫描或重建历史 Session。 +原有 `schedule` 领域和整单元布局仍是权威来源;v2 接受 v1。[带类型规则存储](2026-10-21-schedule-rule-storage.zh.md)替代原按 Session 所有的管理 API、顶层绑定写入和两状态生命周期;[Session 目标](2026-09-17-standalone-schedules.zh.md)拥有宿主管理范围与执行目标。七种正常时间类型保留已提交发生时点。显式目标优先;缺少目标时读取旧 Session 绑定或预留稳定的首次新建后复用身份。不运行启动迁移。 任务 domain 声明整 unit 布局。任务是权威数据,因此 JSON 后端会把文件不可读、文档损坏、版本不受支持或任务非法作为整批加载失败,而不是解释为删除。恢复失败不会改写 `schedule.json`,初始不存在的文件则作为空 domain 打开;修复该文件后会保留任务身份。`Service.init` 等待存储校验和运行时初始化,管理方法等待同一初始化结果;拥有方卸载时释放迟到的存储资源,而不开始投递。投递调度准入与初始化分开:任务变更提交后、运行时清理开始前,祖先可能关闭 Agent 准入。此类拒绝会记录日志而不自动重试,不会将已持久化的变更变成失败的管理结果。存储非法和清理注册失败仍拒绝启动。 -本决策替代先前的 Session 日志权威来源、仅 live 时激活和只读目录决策。[Schedule 参考](../../../../packages/schedule/schedule/README.zh.md)负责显式绝对时间校验、固定速率计算,以及区分排队接纳与模型完成。历史 `schedule/change` 的创建与 fold 类型通过 `LegacyScheduleRecord` 保持为 After、At 和 Every;独立的宿主解码器接受包含 Daily、Weekly 与 Cron 的当前 `ScheduleRecord`。宿主记录解码器要求已存储的 `title` 去除首尾空白后非空、本身已去除首尾空白且不超过 120 个字符,严格的 task schema 会拒绝整个 domain 的打开,而不是丢弃这样的任务。历史变更解码器容忍缺失的 `title`,以便已写入的 Session 日志仍可读取;该成员存在时,同样按这三项检查校验。storage domain 保持版本 1。历史事件不会填充该 domain,已有 `at` 任务也不会转换为每日或每周规则。加载含有活动旧提醒的 Session 时,会警告需要重新创建提醒。 - -插件来源的 `followup()` 同步将消息追加到 Session 收件箱。Session flush 成功后确认持久投递。一次任务记录 put 存储 `lastDelivery`,追加包含发生目标、确认时间、真实消息 id 和指令快照的发送记录,并更新一次性任务的 `inactive` 状态或重复任务的下一目标和状态。因此,任务状态与其保存的历史共用一次提交。未运行任务仍保留在存储中,且不会再次安排投递;显式删除会阻止后续投递,并把该行连同其已保存记录一并移除。这些记录确认收件箱投递,不表示用户收到消息或模型执行完成。 - 新任务初始化空的 `deliveryHistory`。缺少该可选字段的任务会展示已有的最近一次回执(如果存在),并标明更早记录不可用。读取不会重写旧任务,也不会虚构已丢失的历史或指令快照。下一次确认投递时,保留已有回执并追加新记录。严格解码拒绝重复消息 id,以及最近一次回执与历史末项不一致的情况。历史按追加顺序排列,不按墙钟排序,因此时钟回拨不会颠倒已确认投递的顺序。 -重复任务只投递一次最新到期发生时点,Host 重启后也一样。Every 保持与创建时间对齐,直到修改间隔后建立新的起算时点;Daily 保留本地时间与显式 IANA 时区,Weekly 另存非空 ISO 星期集合(唯一且升序)。Every、Daily、Weekly 与 Cron 均使用 `renderRecurringReminderBatchFraming`,同一 Session 的到期任务共用一条 follow-up 消息及其真实消息 id。两个渲染器输出的固定文本见[投递提醒的来源行](2026-09-24-scheduled-message-framing.zh.md)决策。没有可表示的下一目标时,重复任务保留未运行状态及最近一次回执。停止的 Host 不会发送消息。 - -Daily 是互斥的第四个创建选择器,Weekly 是第五个,Cron 是第六个,三者都不是对 `every_seconds` 或 `at` 的转换。Weekly 选择本地日期 ISO 星期属于其所存集合的每个日期;解码器拒绝未规范化的已存集合,选择器拒绝空、重复、超出范围或非整数的集合。它们的首个目标严格晚于当前时间。缺失的本地时间或日期被跳过;重叠时间选择较早时点,每个日期一次。下一目标晚于投递判断时刻,且其本地日期晚于所选发生时点的日期。仅 UTC 目标限制在 0001–9999 年;边缘处的本地日期可以进入第 0 年或第 10000 年。Session 恢复后,运行时依据当前时钟重新核对到期成员,避免时钟回拨时接纳未来任务。 - -受维护的 `@js-temporal/polyfill` 0.5.1 使用宿主 IANA 数据解析本地日期及重叠或缺口;Schedule 不拥有偏移量采样逻辑,也不增加包层级。每日或每周记录保存规范化后的 `HH:mm:ss.SSS` 时间、时区、适用的星期集合及已提交的下一 UTC 时点。解码和重启不会重新计算该时点。规范名称变化后,有效时区别名仍可读取;后续目标使用宿主当前的时区数据。 - -模型 `schedule_list`、Remote `list` 和 Session 顶部右侧的提醒时钟仅显示活动任务。独立的自动化任务页面从侧边栏打开,通过只读 Remote `catalog` 方法读取活动和未运行 Host 任务,不激活 Session 或读取其历史。该时钟在该 Session 没有活动提醒时不显示;恰好有一个时直接打开该任务详情,否则列出提醒供选择。两条路径都打开同一个右侧边栏任务页签,该页签渲染自动化任务页面所用的同一详情组件,因此都不会切换主面板。页签通过导航参数指明任务及其原 Session,并把该绑定带入每个修改操作,因此从页签打开或删除都不会激活 Session。页面提供一行“全部/已开启/未运行”状态筛选,保留未运行任务详情、最近一次投递元数据和固定在位于详情页签条内、与任务操作并排的原 Session 入口。页头的“新建”操作会打开一个新会话,提醒由模型在该会话中创建;页面不提供创建表单。导航等待 Session 与归档元数据,解释不可用目标,且不会隐式恢复已归档 Session。任务保留与原 Session 可用性相互独立。Every、Daily、Weekly 和 Cron 均为重复规则;页面只按状态分组。Daily 与 Weekly 规则标签保留保存的本地时间、精确规则时区和所存星期集合,不替换为下一目标显示所用的浏览器时区。显式确认删除复用 `delete`,传入条目的原始 Session 绑定,要求传入绑定与已存任务一致。这项参数校验不是独立的调用者鉴权:模型工具捕获当前 Agent 的 Session,全局用户界面则选择任务的原始绑定。跨会话模型修改政策仍是产品决策,不由存储布局直接决定。无载荷的变更通知使查询失效,重新连接时重新查询以恢复漏掉的通知。删除阻止后续投递,但不撤回已排队消息。 - -第二层详情将“规则”与“发送记录”分开。打开发送记录时,`history` 请求携带任务的原始 Session 绑定,以及 1–100 的显式分页数量。排他的消息 id 游标用于读取更早回执,新投递追加后不会改变其定位。目录仅保留最近一次回执元数据,不在每次任务列表响应中复制完整历史。任务不存在和游标未知属于独立失败,不是查询成功的空历史。记录视图按需加载,拒绝晚到的过期响应,并将原 Session 导航与查看记录分开。 - -名称、指令和时间更新与投递、删除共用 FIFO。在该队列内比较完整的已观察记录,可防止旧草稿覆盖已保存规则或投递已推进的目标。这样无须增加持久版本计数器,代价是正常投递改变目标后也会拒绝旧草稿。一次任务 put 替换规则、名称或指令,保留身份、原始 Session 绑定、状态、最近一次回执和已保存历史。请求可以省略时间变更、名称或指令;省略的字段保留已存储值,仅修改名称或指令不会改变已提交目标。归一化后等价的修改保留已提交目标与存储字节。修改后的一次性任务以 At 记录保留身份;固定间隔改变后以接纳保存时刻重新起算;钟表规则改变后以同一接纳保存时刻重新解析首个未来目标,而归一化后等价的规则不产生变更。时间变更可以选择不同的重复类型,新规则按创建时相同的方式、以同一接纳保存时刻计算目标。删除会移除该行及其已保存记录([该反转的后果](2026-09-22-schedule-hard-delete-and-bounded-history.zh.md)),因此运行时不会再调度该任务,`history` 也不再按其原始绑定解析。未运行任务不会被重新启用。 - -页面使用现有 Host 任务 domain 和调度器,不使用 mock 引擎或 Session projection。名称、指令和运行时间行编辑当前任务的同一份本地草稿,一次保存把该草稿作为携带完整预期记录的单个更新提交;取消恢复已存储值,保存失败保留草稿,未保存的草稿会保留到权威刷新之后,保存已提交与目录刷新失败仍是不同结果。暂停和执行历史操作仍不受支持。生命周期状态与最近一次投递确认不描述模型结果。 - 客户端的呈现从已有持久化数据派生,而不扩展持久化格式。`schedule_create` transcript(文本记录)卡片从该调用对模型可见的结果 JSON 中读出创建的任务——该 JSON 已经序列化规范任务值——而不是声明 `presentationMeta`:持久化 metadata 通道会为一张仅凭结果即可在 Session 日志回放中重建的卡片增加持久字段,而早于该卡片录制的 Session 无需格式变更即可渲染它。侧栏 Session 行的时钟标记占用 root 作用域的 `sidebar.session.row.leading` slot,而不是请求逐 Session provider,因为 Session 作用域的 slot 会绑定列表中每个 Session,从而激活并保留它;同一个 root 作用域属主约定也供给 `sidebar.session.row.hover`,两者都读取共享的 Host 目录快照 `schedule/catalog()`,不读取 Session 日志。 Session 收件箱持久化和任务 put 发生在两个持久化系统中。收件箱持久化先于任务 put,以免消息尚不存在时就标记已投递。收件箱持久化后崩溃或任务写入失败可能重复发送消息;状态、目标和回执一起存储,并不使两个存储具有原子性。投递失败保留任务并输出诊断;没有独立的重试 timer。此功能不创建或替换 Goal。 @@ -56,10 +40,4 @@ Session 收件箱持久化和任务 put 发生在两个持久化系统中。收 ## Consequences -**不把 mock 的「每小时整点」引入持久词表。** 设计稿把它与每天、每周、仅一次并列。每小时整点与固定间隔在语义上是同一种按经过时间计量的规则,因此详情里的该项直接映射到既有的间隔类型,而不是新增一个持久种类。若真要新增,需要新的持久变体、解码器、目标解析与工具 schema,而它表达的能力现有间隔已经覆盖。 - -任务发现和 timer 不依赖已加载的 Session。延迟、绝对时间和固定速率选择器在与 Daily、Weekly、Cron 并存时保留自身语义;读取已有任务不会重写它们。Host 必须提供普通 Session 持久化和恢复服务,而随发行版交付的 Web 组合为整个部署挂载 Schedule 服务。显式删除会阻止后续投递,并将任务从 `list` 和 `catalog` 中移除,不删除对话消息;被移除的行会带走其已保存回执。历史在追加确认时按配置的窗口与条数上限裁剪,随后加载到 Host 内存,并在每次确认时随任务一起重写。分页限制返回记录数量,不限制存储增长或指令字节数。此前被覆盖的回执,以及任务写入失败的投递记录,无法重建。暂停和执行历史操作仍不受支持。 - -必要覆盖范围包括从已存储任务启动、缺失状态规范化、冷 Session 恢复、仅补发最新发生时点、保留未运行任务且不重复投递、真实消息回执、重启后的删除结果、删除会移除已保存发送记录、排队或持久化失败,以及销毁。钟表规则的验证要求包括缺口和跳过的日期、仅选择较早时点的重叠、小数秒、UTC 范围边缘、已提交目标和别名保留,以及恢复后的时钟回拨。Weekly 另需覆盖星期集合的规范化与校验、跨缺口与重叠的下一目标选择,以及已存集合的保留。历史解码器必须拒绝 Daily、Weekly 与 Cron,而宿主存储接受它们。客户端覆盖范围包括每种重复规则、精确规则时间、时区和星期集合、全部/已开启/未运行状态筛选、保留未运行任务详情和原 Session 导航、确认删除和通知后的权威刷新、空列表、重新连接和晚到响应。呈现覆盖范围包括页面“新建”操作打开新会话、transcript 卡片从不完整或回放的结果 JSON 中收窄任务、页头时钟在恰好一个任务时直接打开并给出数量标签、仅空闲行标记及其悬浮卡片两个任务上限与遗漏行。历史覆盖范围包括旧文件字节保留、追加与重启、不可变的发送指令、最近回执一致性严格校验、稳定游标分页、绑定校验、持久化失败,以及刷新或切换任务期间晚到的分页响应。跨存储崩溃导致的重复投递仍是明确限制,不能被表述为完成保证。 - -名称、指令和时间编辑覆盖范围包括所有支持的规则类型、完整记录冲突、投递与保存的顺序、取消、规范化后的无变更、历史持久化不变、等待期间的控件、草稿保留,以及无碰撞的任务标识。[已构建 CLI 进程测试](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) 驱动公开 Remote 请求,并在新 Host 中重新加载实际任务文件字节。任务和回执种子只是已保留数据的输入,不是真实创建、投递或模型录制证据;这些证据需要普通 Session 操作与捕获的模型请求。 +任务发现和定时器无需已加载 Session。历史保留在同一任务行中,与确认一同提交;读取不虚构缺失指令、时间戳或更早投递。历史 Session 日志 After、At、Every 保持冻结,不填充此领域。[Schedule 参考](../../../../docs/subsystems/schedule.zh.md)拥有时间、管理、UI 投影和保留契约。[构建后 CLI 测试](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts)通过公开 Remote 请求检查旧原始行、编辑时规范化、冲突和冷重启;种入回执是保留数据证据,不是投递证据。 diff --git a/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.i18n.yaml new file mode 100644 index 0000000000..eca5b805b7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-09-17-standalone-schedules.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-standalone-schedules.md +/agent-note-standalone-schedules-and-session-targets: + en: ce8ed282ec843da0 + zh: a5ca78422ea009ec +/agent-note-standalone-schedules-and-session-targets/problem: + en: 2a6769cd378455bb + zh: 84cfb0f2e1fde8e1 +/agent-note-standalone-schedules-and-session-targets/decision: + en: 73ed15d2219f2898 + zh: db8ea6ae79a95241 +/agent-note-standalone-schedules-and-session-targets/alternatives-considered: + en: 1def5c19511fc59e + zh: 84f0f5d568272c39 +/agent-note-standalone-schedules-and-session-targets/consequences: + en: bda079e488b5374b + zh: d5ffe96b33e8e65d diff --git a/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.md b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.md new file mode 100644 index 0000000000..e22bbc4628 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.md @@ -0,0 +1,35 @@ +# Agent Note: Standalone schedules and Session targets + +Status: implemented + +English | [中文](2026-09-17-standalone-schedules.zh.md) + +## Problem + +Host tasks need global management and explicit delivery targets while remaining recognizable in their Workspace. + +## Decision + +The storage domain, importer, placeholder RRULE, and parallel API decisions are superseded by [typed rule storage and shared recurrence](2026-10-21-schedule-rule-storage.md). Keep the existing `schedule` domain and one management API; the target, execution, and notice decisions below remain current. + +Targets are `session`, `new_once`, or `new`. `session` stores one existing Session id; create and edit check, without activating that Session, that it exists and does not belong to a delegated child. `new_once` reserves a Session id when the task is created or retargeted, creates that exact Session at first delivery, and then becomes `session`. `new` saves a reserved Session id in `pendingDelivery` before each create attempt, so a retry after a failed delivery uses the same Session. A created Session uses the target's working directory and Agent preset, or the Host defaults. When the target names a working directory, the Session joins the Workspace registered there, if any. While the Session has no title, it takes the task title; a `new` target adds the Session's creation minute in the timing rule's zone, for example `Weekday digest · 2026-10-12 09:00`, so the Sessions of successive deliveries stay distinguishable. A failed join or rename is logged and does not block delivery. `involvedSessionIds` lists the creating and editing Agent Sessions and each existing or reserved target Session in first-involvement order; Sessions that a `new` target creates are not listed. + +The runtime keeps latest-only catch-up. It delivers the latest occurrence at or before the delivery decision and advances to the next future occurrence; an exhausted rule stays stored with `ended` status, and a paused task has no timer. Each delivery of one task, timed or manual, comes at least 60 seconds after the occurrence of the previous delivery, and the occurrence of a manual run is its run time; for a `new` target, whose every delivery creates a Session, a deployment can raise that interval through `newSessionIntervalSeconds`, which defaults to 60. The floor counts from the previous occurrence when the next stored occurrence keeps the interval, and from the previous acknowledgment otherwise, so acknowledgment latency does not accumulate and a late delivery does not shift later occurrences; the next on-time occurrence can then follow the late delivery by less than one interval. A task delivered to a reused Session, `session` or `new_once`, holds its execution slot until the target Agent is idle, and occurrences that become due meanwhile coalesce into one later delivery, so that Session has at most one pending delivery of the task; a `new` target holds no slot, and its launches run beside one another with only the delivery interval between them. Due tasks with a `session` target share one message per target Session, except After and At tasks. Manual run shares target resolution, the delivery interval, Session inbox persistence, the receipt, and the involvement update with timed delivery, but keeps the next occurrence and status. Both refuse an archived destination Session, including a reserved retry, because the archived-Session gate would block the turn that the message wakes. Session inbox persistence precedes the task receipt write, so a crash between the two stores can repeat a message. The implementation adds no scheduler, run, or ownership service. + +After a committed create, update, or delete, Schedule queues a change notice on its own chain, so Session I/O never holds the mutation and delivery queue. Each involved Session other than the actor whose Agent is loaded receives a `schedule`-sourced message for its next model step that does not start a model turn, so notices queued while the Session is idle reach the model with its next input instead of each running as a model turn; the message names the change and carries the task id and title as JSON strings. A Session without a loaded Agent receives nothing and reads the current task when it next lists tasks. A notice failure is logged and does not roll back the committed change. Shutdown drains queued notices before storage closes. + +## Alternatives considered + +**Require a caller-supplied schedule id.** A user-facing title and canonical identity serve different purposes, but accepting ids would expose collision and validation policy. The Host generates identity and returns it for later operations. + +**Keep creator Session ownership.** Ownership would keep list and mutation APIs scoped and would conflict with global management, retargeting, and Session creation policies. Historical involvement is metadata and notification routing, not authorization. + +**Check spacing by sampling upcoming occurrences.** Each occurrence query enumerates from `DTSTART`, so a high-frequency rule with an early start blocked the Host thread before a sampled check could refuse it, and a sample cannot bound the complete sequence. Static rule checks before enumeration and the per-task delivery interval enforce the spacing instead. + +**Add scheduler, run, and notification services.** The existing Schedule service, storage domain, runtime, and Session controller already own these responsibilities at the required scale. New layers would add indirection without changing durability. + +**Leave created Sessions untitled and outside Workspaces.** Such a Session appears as one more untitled Session outside the Workspace that owns its directory, so the user cannot tell which task created it or, for a `new` target, which delivery it received. Joining the Workspace at the target directory and naming the Session after the task, with the creation minute for `new`, needs no stored field. A failure is only logged because delivery has priority over presentation. + +## Consequences + +Tasks outlive Agents and are managed by id. Archive admission reports active Session targets; explicit stop deletes tasks. Host availability, cross-store at-least-once delivery, best-effort notices, and unbounded per-delivery concurrency remain limitations. The [Schedule reference](../../../../docs/subsystems/schedule.md) owns the exact current contracts and the [management upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md) covers changed callers. diff --git a/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.zh.md b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.zh.md new file mode 100644 index 0000000000..8ce6ff8cae --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-09-17-standalone-schedules.zh.md @@ -0,0 +1,35 @@ +# Agent Note: 独立计划任务与 Session 目标 + +Status: implemented + +[English](2026-09-17-standalone-schedules.md) | 中文 + +## Problem + +宿主任务需要全局管理和显式执行目标,并在工作区中可辨认。 + +## Decision + +存储领域、导入器、占位 RRULE 和并行 API 决策由[带类型规则存储与共享重复计算](2026-10-21-schedule-rule-storage.zh.md)替代。保留现有 `schedule` 领域和统一管理 API;下述目标、执行和通知决策保持有效。 + +目标分为 `session`、`new_once` 和 `new`。`session` 存储一个现有 Session id;创建和编辑会在不激活该 Session 的情况下检查它存在且不属于被委派的子 Agent。`new_once` 在创建任务或重新指定目标时预留 Session id,在首次投递时创建该精确 Session,然后转换为 `session`。`new` 在每次创建尝试前把预留的 Session id 保存在 `pendingDelivery` 中,因此投递失败后的重试使用同一 Session。新建 Session 使用目标中的工作目录和 Agent preset,未提供时使用 Host 默认值。目标指定工作目录时,该 Session 加入在该目录注册的 Workspace(若存在)。该 Session 尚无标题时以任务标题命名;`new` 目标再加上该 Session 的创建时间(精确到分钟,按规则 `DTSTART` 的时区),例如 `Weekday digest · 2026-10-12 09:00`,以便区分各次投递创建的 Session。加入或命名失败只记录日志,不阻止投递。`involvedSessionIds` 按首次参与顺序列出创建和编辑任务的 Agent Session,以及每个现有或预留的目标 Session;`new` 目标创建的 Session 不列入其中。 + +运行时保留仅补发最新发生时点的行为。它投递不晚于投递判断时刻的最新发生时点,并推进到下一个未来发生时点;耗尽的规则以 `ended` 状态保留在存储中,暂停的任务没有计时器。同一任务的每次投递,无论定时还是立即执行,都在上一次投递的发生时点之后至少 60 秒,立即执行的发生时点是其运行时间;`new` 目标的每次投递都会创建 Session,部署可通过 `newSessionIntervalSeconds` 加大该间隔,默认 60。下一个已存储发生时点满足该间隔时,最小投递间隔从上一次发生时点起算,否则从上一次确认时间起算,因此确认延迟不会累积,延迟的投递也不会推移之后的发生时点;下一个准时的发生时点随后可能在延迟投递之后不足一个间隔到来。投递到复用 Session(`session` 或 `new_once`)的任务在目标 Agent 空闲之前一直占用其执行槽位,期间到期的发生时点合并为之后的一次投递,因此该 Session 最多有该任务的一次待处理投递;`new` 目标不占用槽位,各次启动并行运行,彼此之间只隔投递间隔。目标为 `session` 的到期任务按目标 Session 共享一条消息,After 和 At 任务除外。立即执行与定时投递共用目标解析、投递间隔、Session 收件箱持久化、回执与相关 Session 更新,但保留下一发生时点和状态。二者都拒绝已归档的目的 Session,包括重试时复用的预留 Session,因为已归档会话门禁会阻止该消息唤醒的轮次。Session 收件箱持久化先于任务回执写入,因此两个存储之间崩溃可能重复消息。实现不增加 scheduler、run 或 ownership service。 + +create、update 或 delete 提交后,Schedule 在独立的链上排队一条变更通知,因此 Session I/O 不会占用变更与投递队列。除操作者之外、Agent 已加载的每个相关 Session 都会收到一条供下一个模型步骤读取的 `schedule` 来源消息,该消息不会启动模型轮次,因此 Session 空闲期间排队的通知会随其下一条输入到达模型,而不会各自作为一个模型轮次运行;消息说明变更类型,并以 JSON 字符串携带任务 id 和标题。没有已加载 Agent 的 Session 不会收到消息,会在下次列出任务时读取当前任务。通知失败会记录日志,但不会回滚已提交的变更。关闭时先排空已排队的通知,再关闭存储。 + +## Alternatives considered + +**要求调用方提供计划任务 id。** 用户可见标题与规范身份用途不同,但接受 id 会暴露冲突与校验策略。Host 生成身份并返回,供后续操作使用。 + +**保留创建者 Session 所有权。** 所有权会让 list 与 mutation API 保持作用域限制,并与全局管理、重新指定目标和 Session 创建策略冲突。历史参与关系是元数据和通知路由,不是授权。 + +**通过抽样即将到来的发生时点检查间隔。** 每次发生时点查询都从 `DTSTART` 开始枚举,因此起始时间较早的高频规则会在抽样检查拒绝它之前阻塞 Host 线程,而且抽样无法约束完整序列。改为在枚举之前做静态规则检查,并用每个任务的投递间隔约束间隔。 + +**增加 scheduler、run 和 notification service。** 现有 Schedule service、存储领域、runtime 和 Session 控制器已按所需规模承担这些职责。新层级只会增加间接性,不改变持久性。 + +**让新建 Session 保持无标题且不属于任何 Workspace。** 这样的 Session 会作为又一个无标题 Session 出现在拥有其目录的 Workspace 之外,用户无法分辨是哪个任务创建了它,也无法分辨对于 `new` 目标它接收了哪一次投递。加入目标目录处的 Workspace,并以任务标题命名 Session(`new` 再加创建分钟),不需要存储字段。失败只记录日志,因为投递优先于呈现。 + +## Consequences + +任务寿命长于 Agent,并按 id 管理。归档准入报告活动 Session 目标;显式停止删除任务。宿主可用性、跨存储至少一次投递、尽力通知和每次新建目标的无界并发仍是限制。[Schedule 参考](../../../../docs/subsystems/schedule.zh.md)拥有精确的当前契约,[管理升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.zh.md)说明调用方变更。 diff --git a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.i18n.yaml index 575b3ca146..cf62bcbb22 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.i18n.yaml @@ -6,14 +6,14 @@ en: 17a73230ad22ec0b zh: 5bcf27d7c0e86764 /agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/problem: - en: 98e82a0add324882 - zh: c10e85a3f2a522f8 + en: c49b11c393e59f35 + zh: 03cab3ae79a6c878 /agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/decision: - en: 56328745115714b5 - zh: f30d39f59aa06a13 + en: 48272c9bbe2a0040 + zh: 668799310bcd20ba /agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/alternatives-considered: - en: 0c4eb01054be1141 - zh: 95980f8097fa36fd + en: 7663bb52e1034eeb + zh: 2ef8f146c5642837 /agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/consequences: - en: 05121f4b77b8ee12 - zh: 1751c9b1a752ce6b + en: f911ddff2a9b81da + zh: 38ee18e3f6b10c26 diff --git a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.md b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.md index 90127d6887..691e9e6318 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.md +++ b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.md @@ -6,15 +6,15 @@ English | [中文](2026-09-22-schedule-hard-delete-and-bounded-history.zh.md) ## Problem -The Schedule domain is one whole-unit JSON document that the backend rewrites on every mutation, so every retained byte in a task row grows every write. Saved delivery records were unbounded: each acknowledgment appended to the array, and a deleted task kept its row and records so the open detail could still read them. The document's size therefore followed a task's delivery count, and deletion added a state every reader had to skip. +The Schedule domain stores each task as one JSON document that the backend rewrites whole on every change of that task, so every retained byte in a task row grows every write of that task. Saved delivery records were unbounded: each acknowledgment appended to the array, and a deleted task kept its row and records so the open detail could still read them. The document's size therefore followed a task's delivery count, and deletion added a state every reader had to skip. ## Decision -Deletion is hard deletion. `ScheduleService.delete` removes the storage row through `tasks.delete`, so the task stops scheduling, leaves `list` and `catalog`, and `history` answers `schedule_not_found` for the same `(sessionId, id)`; the row's saved delivery records are removed with it. The task schema has no `deleted` field, and no client surface offers a recycle bin or a read of an already deleted task's records. +Deletion is hard deletion. The `delete` action of `ScheduleService.edit` removes the storage row through `tasks.delete`, so the task stops scheduling, leaves `list` and `catalog`, and `history` answers `schedule_not_found` for its id; the row's saved delivery records are removed with it. `deleteInactive` removes only ended tasks in one `tasks.deleteMany` batch and preserves active and paused tasks. The task schema has no `deleted` field, and no client surface offers a recycle bin or a read of an already deleted task's records. Delivery history is bounded by plugin `Config`: `deliveryHistoryDays` (default 30, 1–3650) and `deliveryHistoryRecords` (default 200, 1–10000). `appendDelivery` applies both bounds on the only write path. It keeps the records whose `deliveredAt` is at or after the appended receipt's `deliveredAt` minus the configured day window, keeps the newest `deliveryHistoryRecords` of those, and always retains the appended latest receipt; a pruned window sets `earlierRecordsUnavailable` and `earlierRecordsPruned`, which later appends preserve. The latter flag is optional in stored rows and confirms actual removal; legacy unavailability alone does not imply pruning. The history response includes the current retention limits, and the Client shows the cleanup notice only for confirmed pruning after loading the final nonempty page. -The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision: one authoritative version-1 task domain, timer restoration for active tasks only, cold-Session delivery through the Session controller, the catalog and detail surfaces, and the historical-versus-Host decoder split. Its status vocabulary is `active` or `inactive`; `inactive` is the sole non-active name, and the client filter row reads All, Enabled, and Inactive. That note stays active: this supersession is partial, so it is neither archived nor frozen, and it remains the owner of everything above while the deletion and retention decisions it recorded are replaced here. +The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision: timer restoration for active tasks only, cold-Session delivery through the Session controller, the catalog and detail surfaces, and the historical-versus-Host decoder split. That note stays active: this supersession is partial, so it is neither archived nor frozen, and it remains the owner of everything above while the deletion and retention decisions it recorded are replaced here. [Standalone schedules and Session targets](2026-09-17-standalone-schedules.md) owns the authoritative task domain and its `active`, `paused`, or `ended` status. Native and Remote catalogs report these same three statuses across the Host. The Automation tasks page's status filter row reads All, Enabled, Paused, and Ended. ## Alternatives considered @@ -24,10 +24,10 @@ The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note ke **Measure the window from the task instead of from each receipt.** Anchoring the window to the task's creation or committed target would discard a newly written receipt of an old task. Measuring back from the appended receipt's `deliveredAt` keeps the window anchored to the data being kept. -**Keep history unbounded and let operators clean up.** The domain publishes one whole-unit document per write, so unbounded history makes the storage document's size a function of delivery counts. Retention is a bound the storage layout requires, not a retention preference. +**Keep history unbounded and let operators clean up.** The backend rewrites each task document whole on every write of that task, so unbounded history makes the task document's size a function of delivery counts. Retention is a bound the storage layout requires, not a retention preference. ## Consequences Deletion now offers no recovery: a deleted task's saved deliveries cannot be read back, and a task that still needs its full history must be read before deletion. Configured retention also discards receipts the task once had; the retained flag records that a window was pruned rather than pretending the history is complete. -In exchange, the persisted task set has one deletion semantics, the storage document's size is bounded by configuration instead of by delivery counts, and `inactive` is the only non-active lifecycle name. The plugin `Config` is the place to raise the bounds when a deployment needs longer delivery history. +In exchange, the persisted task set has one deletion semantics, the size of each task document is bounded by configuration instead of by delivery counts, and deletion adds no lifecycle state. The plugin `Config` is the place to raise the bounds when a deployment needs longer delivery history. diff --git a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.zh.md b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.zh.md index dfc8ab4ff3..67552c5a41 100644 --- a/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-22-schedule-hard-delete-and-bounded-history.zh.md @@ -6,15 +6,15 @@ Status: implemented ## Problem -Schedule domain 是后端每次变更都会重写的单个整 unit JSON 文档,因此任务行中保留的每个字节都会随每次写入增长。已保存的发送记录没有上限:每次确认都会向数组追加,而被删除的任务会保留其行与记录,以便已打开的详情仍能读取。于是文档大小随任务的投递次数变化,删除还引入了一个所有读取方都必须跳过的状态。 +Schedule domain 把每个任务存储为一个 JSON 文档,后端在该任务每次变更时整体重写它,因此任务行中保留的每个字节都会随该任务的每次写入增长。已保存的发送记录没有上限:每次确认都会向数组追加,而被删除的任务会保留其行与记录,以便已打开的详情仍能读取。于是文档大小随任务的投递次数变化,删除还引入了一个所有读取方都必须跳过的状态。 ## Decision -删除是硬删除。`ScheduleService.delete` 通过 `tasks.delete` 移除存储行,因此任务停止调度、离开 `list` 与 `catalog`,`history` 对相同的 `(sessionId, id)` 返回 `schedule_not_found`;该行已保存的投递记录随行一并移除。任务 schema 没有 `deleted` 字段,也没有任何界面提供回收站或读取已删除任务记录的能力。 +删除是硬删除。`ScheduleService.edit` 的 `delete` 操作通过 `tasks.delete` 移除存储行,因此任务停止调度、离开 `list` 与 `catalog`,`history` 对其 id 返回 `schedule_not_found`;该行已保存的投递记录随行一并移除。`deleteInactive` 通过一次 `tasks.deleteMany` 批量写入仅删除已结束任务,保留活动和暂停任务。任务 schema 没有 `deleted` 字段,也没有任何界面提供回收站或读取已删除任务记录的能力。 投递历史受插件 `Config` 限制:`deliveryHistoryDays`(默认 30,1–3650)与 `deliveryHistoryRecords`(默认 200,1–10000)。`appendDelivery` 在唯一的写入路径上同时应用这两个上限。它保留 `deliveredAt` 不早于「本次追加回执的 `deliveredAt` 减去配置的天数窗口」的记录,在其中保留最新的 `deliveryHistoryRecords` 条,并始终保留本次追加的最近一次回执;发生裁剪时设置 `earlierRecordsUnavailable` 和 `earlierRecordsPruned`,后续追加会保留这两个标志。后者在存储行中可选,用于确认实际删除;仅有旧格式的不可用标志不表示发生过裁剪。历史响应携带当前保留上限,客户端仅在加载完最后一页且历史非空、确认裁剪时显示清理提示。 -[Host-owned scheduled messages](2026-09-16-host-schedule-storage.zh.md) 笔记保留其余决策:唯一的权威版本 1 任务 domain、只为活动任务恢复定时器、通过 Session controller 投递到冷会话、目录与详情界面,以及历史解码器与宿主解码器的划分。其状态词汇为 `active` 或 `inactive`;`inactive` 是唯一的非活动名称,客户端筛选行为全部、活动和未运行。该笔记保持活动状态:这是一次部分取代,因此它既未归档也未冻结,仍是上述内容的归属笔记,而它记录的删除与保留决策由本笔记取代。 +[Host-owned scheduled messages](2026-09-16-host-schedule-storage.zh.md) 笔记保留其余决策:只为活动任务恢复定时器、通过 Session controller 投递到冷会话、目录与详情界面,以及历史解码器与宿主解码器的划分。该笔记保持活动状态:这是一次部分取代,因此它既未归档也未冻结,仍是上述内容的归属笔记,而它记录的删除与保留决策由本笔记取代。[独立计划任务与 Session 目标](2026-09-17-standalone-schedules.zh.md) 拥有权威任务 domain 及其 `active`、`paused` 或 `ended` 状态。原生和 Remote 目录在宿主范围内报告相同的三种状态。自动化任务页面的状态筛选行为全部、已开启、已暂停和已结束。 ## Alternatives considered @@ -24,10 +24,10 @@ Schedule domain 是后端每次变更都会重写的单个整 unit JSON 文档 **以任务而非每条回执为窗口起点。** 把窗口锚定在任务的创建时间或已提交目标上,会丢弃旧任务刚写入的回执。从本次追加回执的 `deliveredAt` 向前计算,使窗口锚定在所要保留的数据上。 -**保留无上限的历史,由运维清理。** 该 domain 每次写入都发布整个 unit 文档,因此无上限的历史会让存储文档的大小随投递次数增长。保留上限是存储布局所要求的约束,而不是保留策略偏好。 +**保留无上限的历史,由运维清理。** 后端在该任务每次写入时整体重写其任务文档,因此无上限的历史会让任务文档的大小随投递次数增长。保留上限是存储布局所要求的约束,而不是保留策略偏好。 ## Consequences 删除不再提供恢复能力:已删除任务的已保存投递无法再读回,仍需要完整历史的必须在删除前读取。配置的保留策略也会丢弃任务曾经拥有的回执;保留的标志记录窗口发生过裁剪,而不是假装历史完整。 -换取的是:持久任务集合只有一种删除语义,存储文档大小由配置而非投递次数决定,且 `inactive` 是唯一的非活动生命周期名称。当某个部署需要更长的投递历史时,应提高插件 `Config` 中的上限。 +换取的是:持久任务集合只有一种删除语义,每个任务文档的大小由配置而非投递次数决定,且删除不增加生命周期状态。当某个部署需要更长的投递历史时,应提高插件 `Config` 中的上限。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml index 01a5ad7732..9a557c0044 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.i18n.yaml @@ -9,14 +9,14 @@ en: 27b4d1d25cd1c178 zh: 3ddc4d9a09b6182d /agent-note-preset-scoped-schedule-tools/decision: - en: 3c4708981d34217d - zh: cd0c07dc0888f3db + en: 652fb37ad4e5a826 + zh: f5c3cc1e9a79b4ca /agent-note-preset-scoped-schedule-tools/alternatives-considered: en: 5cfe619038339caa zh: c2d2651d304d867c /agent-note-preset-scoped-schedule-tools/consequences: - en: d7c7e6b8e6268559 - zh: 801e5be70e00cc90 + en: aceed1aa98ed9bec + zh: b9d99a25a8b25417 /agent-note-preset-scoped-schedule-tools/testing: - en: d42cb866907a96b5 - zh: 6e66f8babe744bcb + en: 05080859ac790524 + zh: 4b220c10da961608 diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md index 169f3bea52..7bedb1ef0e 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md @@ -10,9 +10,9 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md) ## Decision -`@deepseek-ai/dsh-tool-schedule` (`packages/schedule/tool-schedule`) contributes the four tools as a preset-level Consumer. It declares `inject = ['tools']` and registers the definitions on `ctx.tools` from inside `ctx.inject(['schedule'], …)`, so the mounting scope is the one that owns them and the registration waits for the Host Schedule service in that same scope. The shipped Web profile mounts the row in its `standard`, `cordis`, and `ptc` presets and omits it from `minimal`. Cordis effect ownership disposes the definitions with the mount, and a composition that never resolves `schedule` registers none of them. The [Web bundle](../../../../packages/bundle/web-app/README.md) owns the `schedule` and `ui-schedule` rows the shipped composition mounts; this record owns the reminder tools' preset placement. +`@deepseek-ai/dsh-tool-schedule` (`packages/schedule/tool-schedule`) contributes `schedule_create`, `schedule_list`, `schedule_view`, and `schedule_edit` as a preset-level Consumer. It declares `inject = ['tools', 'systemPrompt']` and registers the definitions and shared authorization instruction from inside `ctx.inject(['schedule'], …)`, so the mounting scope owns them and registration waits for the Host Schedule service in that same scope. The shipped Web profile mounts the row in its `standard`, `cordis`, and `ptc` presets and omits it from `minimal`. Cordis effect ownership disposes the definitions with the mount, and a composition that never resolves `schedule` registers none of them. The [Web bundle](../../../../packages/bundle/web-app/README.md) owns the `schedule` and `ui-schedule` rows the shipped composition mounts; this record owns the reminder tools' preset placement. -`@deepseek-ai/dsh-schedule` keeps the version-1 storage domain, the Host timer and serialized queue, Host delivery through the Session controller, the Automation page's backing reads, and the `ctx.schedule` interface. `dsh-tool-schedule` is the model-facing consumer of that interface: it checks selector and identity constraints before the service call, reads `exec.agent` for the Session binding, and maps failures that are not `ScheduleInputError` to `internal_error` so storage details never reach the model. +`@deepseek-ai/dsh-schedule` keeps the `schedule` storage domain, now writing v2 and reading v1, the Host timer and serialized queue, Host delivery, the Automation tasks page's backing reads, and the `ctx.schedule` interface. `dsh-tool-schedule` is the model-facing consumer of that interface: it maps RRULE and target inputs to service requests, reads `exec.agent` for the actor and `this_session` destination, and maps undeclared failures to `internal_error` so storage details never reach the model. Management addresses every Host task by id; the target alone selects the receiving Session. ## Alternatives considered @@ -26,9 +26,9 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md) - Each preset that mounts the row pays the four schemas' fixed token cost, and tool availability is read from the composition instead of inferred from the Host service's presence. - A deployment can mount `dsh-schedule` for storage and delivery without granting its agents model-driven reminder management. - `dsh-schedule` injects no `ctx.tools` and registers no model-facing tool. -- A delegated child inherits the preset's four reminder schemas. `subagentCallerRefusal` in `dsh-tool-schedule` returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }` from each tool when the caller's delegation depth is above zero. The [preset composition decision](../simplification/2026-10-09-preset-owned-subagent-composition.md) removes the redundant child filter; visibility does not authorize execution. -- A Session a delegated child owns can never receive a delivered reminder, so `ScheduleService.create` and `ScheduleService.update` refuse it with `subagent_session`. The refusal reads the delegation depth — the accounting the delegation cap itself enforces, carried by the persisted session header across a cold resume. The rule sits in the service, so other consumers reach it too — the Automation surface included. +- A delegated child inherits the preset's four reminder schemas. `runForCaller` in `dsh-tool-schedule` returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' }` from each tool when the caller's delegation depth is above zero. The [preset composition decision](../simplification/2026-10-09-preset-owned-subagent-composition.md) removes the redundant child filter; visibility does not authorize execution. +- A Session a delegated child owns can never receive a delivered reminder, so `ScheduleService.create` and target changes or arming through `ScheduleService.edit` refuse it with `subagent_session`. The refusal reads the delegation depth — the accounting the delegation cap itself enforces, carried by the persisted session header across a cold resume. The rule sits in the service, so other consumers reach it too — the Automation surface included. ## Testing -`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every tool for a delegated child caller`. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins. +`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every call from a registered delegated child whose scope mounts the tools`, and `packages/subagent/subagent/tests/schedule-tools.spec.ts` runs a delegated child through the tool executor and pins that refusal without a stored task. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins. diff --git a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md index 75b41d8b9e..408eff9a8d 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md @@ -10,9 +10,9 @@ Status: implemented ## Decision -`@deepseek-ai/dsh-tool-schedule`(`packages/schedule/tool-schedule`)以 preset 级 Consumer 的身份贡献这四个工具。它声明 `inject = ['tools']`,并在 `ctx.inject(['schedule'], …)` 内通过 `ctx.tools` 注册这些定义,因此拥有它们的是挂载它的作用域,而注册会等待同一作用域中的宿主 Schedule 服务。发布版 Web profile 在其 `standard`、`cordis` 和 `ptc` preset 中挂载该行,`minimal` 不挂载。Cordis 的 effect 所有权随挂载卸载而释放这些定义,而始终未解析出 `schedule` 的组合不会注册其中任何一个。[Web bundle](../../../../packages/bundle/web-app/README.zh.md)负责随发行版交付的组合挂载的 `schedule` 与 `ui-schedule` 两行;本记录负责提醒工具的 preset 归属。 +`@deepseek-ai/dsh-tool-schedule`(`packages/schedule/tool-schedule`)以 preset 级 Consumer 的身份贡献 `schedule_create`、`schedule_list`、`schedule_view` 和 `schedule_edit`。它声明 `inject = ['tools', 'systemPrompt']`,并在 `ctx.inject(['schedule'], …)` 内注册这些定义和共用授权指令,因此挂载作用域拥有它们,注册会等待同一作用域中的宿主 Schedule 服务。发布版 Web profile 在其 `standard`、`cordis` 和 `ptc` preset 中挂载该行,`minimal` 不挂载。Cordis 的 effect 所有权随挂载卸载而释放这些定义,而始终未解析出 `schedule` 的组合不会注册其中任何一个。[Web bundle](../../../../packages/bundle/web-app/README.zh.md)负责随发行版交付的组合挂载的 `schedule` 与 `ui-schedule` 两行;本记录负责提醒工具的 preset 归属。 -`@deepseek-ai/dsh-schedule` 保留版本 1 storage domain、宿主定时器与串行队列、经由 Session controller 的宿主投递、自动化任务页面的读取来源,以及 `ctx.schedule` 接口。`dsh-tool-schedule` 是该接口面向模型的消费者:它在调用服务前校验选择器与身份约束,从 `exec.agent` 读取 Session 绑定,并把非 `ScheduleInputError` 的失败映射为 `internal_error`,使存储细节不会到达模型。 +`@deepseek-ai/dsh-schedule` 保留 `schedule` 存储域,现写入 v2 并读取 v1,同时保留宿主定时器与串行队列、宿主投递、自动化任务页面的读取来源,以及 `ctx.schedule` 接口。`dsh-tool-schedule` 是该接口面向模型的消费者:它将 RRULE 与目标输入映射为服务请求,从 `exec.agent` 读取操作者与 `this_session` 目的地,并把未声明的失败映射为 `internal_error`,使存储细节不会到达模型。管理按 id 寻址宿主全部任务;仅目标选择接收 Session。 ## Alternatives considered @@ -26,9 +26,9 @@ Status: implemented - 挂载该行的每个 preset 承担四个 schema 的固定 token 成本,工具可用性取自组合,而不是由宿主服务是否存在推断。 - 部署可以只为存储与投递挂载 `dsh-schedule`,而不授予其 Agent 由模型驱动的提醒管理能力。 - `dsh-schedule` 不注入 `ctx.tools`,也不注册任何面向模型的工具。 -- 被委派的子 agent 继承 preset 的四个提醒 schema。调用方委派深度大于零时,`dsh-tool-schedule` 中的 `subagentCallerRefusal` 从每个工具返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }`。[preset 组装决策](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md)移除了重复的子级过滤;可见性不授予执行权限。 -- 被委派子 agent 拥有的 Session 永远收不到投递的提醒,因此 `ScheduleService.create` 与 `ScheduleService.update` 会以 `subagent_session` 拒绝它。该拒绝读取委派深度——委派封顶本身执行的记账,由持久化 session header 承载并跨冷恢复保留。这条规则在服务层,因此其它消费方(包括自动化任务页面)也会命中。 +- 被委派的子 agent 继承 preset 的四个提醒 schema。调用方委派深度大于零时,`dsh-tool-schedule` 中的 `runForCaller` 从每个工具返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' }`。[preset 组装决策](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md)移除了重复的子级过滤;可见性不授予执行权限。 +- 被委派子 agent 拥有的 Session 永远收不到投递的提醒,因此 `ScheduleService.create` 以及通过 `ScheduleService.edit` 改变目标或启用任务时会以 `subagent_session` 拒绝它。该拒绝读取委派深度——委派封顶本身执行的记账,由持久化 session header 承载并跨冷恢复保留。这条规则在服务层,因此其它消费方(包括自动化任务页面)也会命中。 ## Testing -`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every tool for a delegated child caller`。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。 +`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every call from a registered delegated child whose scope mounts the tools`;`packages/subagent/subagent/tests/schedule-tools.spec.ts` 通过工具执行器运行一个被委派的子 agent,并在没有已存任务时固定该拒绝。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.i18n.yaml index 8dcfb5a6a2..2a25da27a7 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.i18n.yaml @@ -6,14 +6,14 @@ en: f524c3b0ee74c586 zh: ec4e85f0fd853532 /agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/problem: - en: c4156e2a8a3ad379 - zh: 992b76509f83d61f + en: 57f2fb0a35f6a420 + zh: 7174afde673c62d6 /agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/decision: - en: b9b203da394f58e5 - zh: ac511458d60dab49 + en: 136514e302d80f4c + zh: b34e140f41547d06 /agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/alternatives-considered: - en: 8074a2b9b9f5d782 - zh: 1604b7ee5d34375e + en: 49cc4e396052fc09 + zh: adb8b01f29ce76fb /agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/consequences: - en: 85e03b541bfce57c - zh: 77decbb804f6a0b9 + en: 55c346fbd5feb417 + zh: 29631345d447f643 diff --git a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.md b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.md index 906edabec9..27a4837b83 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.md +++ b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.md @@ -6,17 +6,17 @@ English | [中文](2026-09-24-scheduled-message-framing.zh.md) ## Problem -Due reminders reach their original Session as user-role messages with producer kind `schedule`. Before this decision, both renderers opened that message with an instruction about how to treat its payload: one-shot delivery asked the model to present `reminder_prompt_json` as untrusted reminder content and not as new user instructions, and recurring batch delivery asked the same for every `reminder_prompt` in `reminders_json`. The message therefore asserted that its own content was untrusted instead of naming where it came from. +Due reminders reach their target Session as user-role messages with producer kind `schedule`. Before this decision, both renderers opened that message with an instruction about how to treat its payload: one-shot delivery asked the model to present `reminder_prompt_json` as untrusted reminder content and not as new user instructions, and recurring batch delivery asked the same for every `reminder_prompt` in `reminders_json`. The message therefore asserted that its own content was untrusted instead of naming where it came from. ## Decision `renderReminderFraming` and `renderRecurringReminderBatchFraming` in [`packages/schedule/schedule/src/domain.ts`](../../../../packages/schedule/schedule/src/domain.ts) both emit one shared fixed line, `SCHEDULED_MESSAGE_FRAMING`: `This is a scheduled message from the user`. It is the block's second line, after the bracketed marker (`[SCHEDULE REMINDER]`, `[SCHEDULE REMINDER BATCH]`), and the dynamic field lines are unchanged: a one-shot message still appends `schedule_id_json`, `occurrence_at`, and `reminder_prompt_json`, and a recurring batch still appends `reminders_json`. -The fixed line states the origin of the message: a schedule bound to that Session. A model reading a user-role message whose fixed block carries it reads the following reminder payload (`reminder_prompt_json` in a one-shot message, `reminders_json` in a batch) as content the user scheduled, and the Host cannot attest that the user typed it: `schedule_create` and `schedule_update` let the model write the prompt, and a model-written prompt can carry text the model read from the web, files, or command output. The previous line marked that payload untrusted, and this decision drops that instruction, so the change accepts the residual risk that model-authored text arrives under a user-origin line. Reintroduction condition: a demonstrated injection through a model-written prompt restores a clause that scopes the payload as reminder text rather than a new instruction, and the five pinned framing assertions in the package specs plus `expectReminderFraming` in the Web e2e are the check that such a change is deliberate. Framing-line forgery is closed by encoding: the schedule id and prompt are JSON strings, the occurrence instant is a validated canonical RFC 3339 value, and each occupies one line, so a prompt carrying embedded newlines or an `occurrence_at:`-style line cannot add framing lines to the block. The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision, including delivery through the Session controller and the saved delivery records. +The fixed line states the origin of the message: a schedule that delivers to that Session. A model reading a user-role message whose fixed block carries it reads the following reminder payload (`reminder_prompt_json` in a one-shot message, `reminders_json` in a batch) as content the user scheduled, and the Host cannot attest that the user typed it: `schedule_create` and `schedule_edit` let the model write the prompt, and a model-written prompt can carry text the model read from the web, files, or command output. The previous line marked that payload untrusted, and this decision drops that instruction, so the change accepts the residual risk that model-authored text arrives under a user-origin line. Reintroduction condition: a demonstrated injection through a model-written prompt restores a clause that scopes the payload as reminder text rather than a new instruction, and the five pinned framing assertions in the package specs plus `expectReminderFraming` in the Web e2e are the check that such a change is deliberate. Framing-line forgery is closed by encoding: the schedule id and prompt are JSON strings, the occurrence instant is a validated canonical RFC 3339 value, and each occupies one line, so a prompt carrying embedded newlines or an `occurrence_at:`-style line cannot add framing lines to the block. The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision, including delivery through the Session controller and the saved delivery records. ## Alternatives considered -**Keep the untrusted-content instruction.** It asserted that the prompt was untrusted input, which the delivered message does not need: the prompt is written in the Session the schedule is bound to — by the model through `schedule_create` and `schedule_update`, or by the user in the Web task detail — and the delivery is an ordinary user-role message there. +**Keep the untrusted-content instruction.** It asserted that the prompt was untrusted input, which the delivered message does not need: the model writes the prompt through `schedule_create` and `schedule_edit`, a human caller writes it through the Web task detail or Remote `create` and `edit`, and the delivery is an ordinary user-role message in its target Session. **Change only the recurring batch line.** One-shot and recurring delivery would then disagree about the origin of the same kind of message, and each later wording change would need both renderers edited separately. Both paths now read one constant. @@ -24,6 +24,6 @@ The fixed line states the origin of the message: a schedule bound to that Sessio Model-visible reminder text changes for both delivery paths, so a Session log recorded before this decision reconstructs the previous framing, and the Web notice that renders a delivered message shows the new line when expanded. Nothing else moves: no session event, storage field, client code, protocol, or durable format changes, and the delivered text remains reconstructable from the log. -The prompt text carries no authorship guarantee. It is written in the Session the schedule is bound to, by the model through `schedule_create` and `schedule_update` or by the user in the Web task detail, and a model-written reminder can quote text the model read from the web, files, or command output. The task's Session binding scopes which Session's model reaches the task; it is not caller authorization and says nothing about where the prompt content came from. The Decision holds the accepted risk and its reintroduction condition. +The prompt text carries no authorship guarantee. The model writes it through `schedule_create` and `schedule_edit`, a human caller writes it through the Web task detail or Remote `create` and `edit`, and a model-written reminder can quote text the model read from the web, files, or command output. Those tools reach every Host task by id from any Session whose preset mounts them, so the task's target Session is not caller authorization and says nothing about where the prompt content came from. The Decision holds the accepted risk and its reintroduction condition. No recorded-session snapshot covers a delivered reminder, and this change adds none: no committed fixture contains a `schedule` message, and `snapshots/web/schedule-catalog` records catalog queries only. Two harness capabilities are missing for such a fixture: no scenario patch controls the wall clock that `packages/schedule/schedule/src/runtime.ts` reads for delivery, and the snapshot harness seeds Sessions rather than the schedule storage domain that holds Host tasks, so those rows exist only where a Web test writes them by hand. This change records the missing harness support instead of a fixture. The delivered text is pinned by the five full-string assertions in `packages/schedule/schedule/tests/{domain,daily,weekly,cron}.spec.ts` and by `expectReminderFraming` in `apps/web/tests/schedule-after.e2e.ts`, which asserts the line in the assembled request for the one-shot and recurring paths. diff --git a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.zh.md b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.zh.md index 7aed47c1d0..b2060b019c 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-scheduled-message-framing.zh.md @@ -6,17 +6,17 @@ Status: implemented ## Problem -到期的提醒以生产者 kind 为 `schedule` 的 user-role 消息进入其原 Session。在本决策之前,两个渲染器都用一句关于如何处理其载荷的固定指令开篇:单次投递要求模型把 `reminder_prompt_json` 作为不可信的提醒内容呈现、而不是新的用户指令;周期批次投递对 `reminders_json` 中的每个 `reminder_prompt` 提出同样的要求。于是这条消息断言自身内容不可信,而没有说明它来自哪里。 +到期的提醒以生产者 kind 为 `schedule` 的 user-role 消息进入其目标 Session。在本决策之前,两个渲染器都用一句关于如何处理其载荷的固定指令开篇:单次投递要求模型把 `reminder_prompt_json` 作为不可信的提醒内容呈现、而不是新的用户指令;周期批次投递对 `reminders_json` 中的每个 `reminder_prompt` 提出同样的要求。于是这条消息断言自身内容不可信,而没有说明它来自哪里。 ## Decision [`packages/schedule/schedule/src/domain.ts`](../../../../packages/schedule/schedule/src/domain.ts) 中的 `renderReminderFraming` 与 `renderRecurringReminderBatchFraming` 都输出同一条固定行,即模块常量 `SCHEDULED_MESSAGE_FRAMING`:`This is a scheduled message from the user`;它是该块的第二行,位于方括号标记(`[SCHEDULE REMINDER]`、`[SCHEDULE REMINDER BATCH]`)之后。动态字段行不变:单次消息仍追加 `schedule_id_json`、`occurrence_at`、`reminder_prompt_json`,周期批次仍追加 `reminders_json`。 -这条固定行说明消息的来源:绑定到该 Session 的一条定时任务。模型读到固定块中带有它的 user-role 消息时,会把随后的提醒载荷(单次消息的 `reminder_prompt_json`、批次的 `reminders_json`)当作用户安排的内容,而 Host 无法证明该文本由用户键入:`schedule_create` 与 `schedule_update` 允许模型写入提示词,模型写入的提示词可以带上模型从网页、文件或命令输出中读到的文本。旧固定行把该载荷标记为不可信,本决策有意去掉这一指令,因此接受「模型生成的文本以用户来源行投递」这一残留风险。再引入条件:一旦出现经由模型写入提示词完成注入的实例,就恢复一句把载荷限定为提醒文本、而非新指令的说明;包内五处固定断言与 Web e2e 的 `expectReminderFraming` 是「此类改动必须是有意为之」的检查。固定行无法被动态字段伪造,这由编码保证:schedule id 与提示词是 JSON 字符串,发生时点是经校验的规范 RFC 3339 值,且各自只占一行,因此带有换行或形如 `occurrence_at:` 的提示词无法向该块增加固定行。[Host 拥有的定时消息](2026-09-16-host-schedule-storage.zh.md) 记下的其余决策不变,包括通过 Session controller 投递以及保存的投递记录。 +这条固定行说明消息的来源:投递到该 Session 的一条定时任务。模型读到固定块中带有它的 user-role 消息时,会把随后的提醒载荷(单次消息的 `reminder_prompt_json`、批次的 `reminders_json`)当作用户安排的内容,而 Host 无法证明该文本由用户键入:`schedule_create` 与 `schedule_edit` 允许模型写入提示词,模型写入的提示词可以带上模型从网页、文件或命令输出中读到的文本。旧固定行把该载荷标记为不可信,本决策有意去掉这一指令,因此接受「模型生成的文本以用户来源行投递」这一残留风险。再引入条件:一旦出现经由模型写入提示词完成注入的实例,就恢复一句把载荷限定为提醒文本、而非新指令的说明;包内五处固定断言与 Web e2e 的 `expectReminderFraming` 是「此类改动必须是有意为之」的检查。固定行无法被动态字段伪造,这由编码保证:schedule id 与提示词是 JSON 字符串,发生时点是经校验的规范 RFC 3339 值,且各自只占一行,因此带有换行或形如 `occurrence_at:` 的提示词无法向该块增加固定行。[Host 拥有的定时消息](2026-09-16-host-schedule-storage.zh.md) 记下的其余决策不变,包括通过 Session controller 投递以及保存的投递记录。 ## Alternatives considered -**保留「不可信内容」指令。** 它断言提示词是不可信输入,而投递的消息并不需要这一断言:提示词写在绑定该定时任务的 Session 内——由模型通过 `schedule_create` 与 `schedule_update` 写入,或由用户在 Web 任务详情中写入——投递本身就是该 Session 中的普通 user-role 消息。 +**保留「不可信内容」指令。** 它断言提示词是不可信输入,而投递的消息并不需要这一断言:模型通过 `schedule_create` 与 `schedule_edit` 写入提示词,人工调用方通过 Web 任务详情或 Remote `create` 与 `edit` 写入它,投递本身就是目标 Session 中的普通 user-role 消息。 **只改周期批次那一行。** 单次与周期投递会对同类消息的来源给出不同说法,此后每次改措辞都要分别改两个渲染器。现在两条路径读同一个常量。 @@ -24,6 +24,6 @@ Status: implemented 两个投递路径的模型可见提醒文本都改变,因此在该决策之前记录的 Session 日志重建出的是旧的固定文本;Web 中渲染该投递消息的通知在展开时显示新的一行。其余不动:没有 session 事件、存储字段、客户端代码、协议或持久化格式变化,投递文本仍可从日志重建。 -提示词文本不携带作者保证。它写在绑定该定时任务的 Session 内——由模型通过 `schedule_create` 与 `schedule_update` 写入,或由用户在 Web 任务详情中写入——模型创建的提醒可以把模型从网页、文件或命令输出中读到的文本原样写入。任务的 Session 绑定限定的是哪个 Session 的模型能访问该任务;它不是调用方鉴权,也不说明提示词内容的来源。本决策中记下该残留风险与再引入条件。 +提示词文本不携带作者保证。模型通过 `schedule_create` 与 `schedule_edit` 写入它,人工调用方通过 Web 任务详情或 Remote `create` 与 `edit` 写入它;模型创建的提醒可以把模型从网页、文件或命令输出中读到的文本原样写入。这些工具可以从任何挂载它们的 preset 所属的 Session 按 id 访问 Host 的每个任务,因此任务的目标 Session 不是调用方鉴权,也不说明提示词内容的来源。本决策中记下该残留风险与再引入条件。 没有录制会话快照覆盖提醒投递,本次也没有新增:已提交夹具中没有 `schedule` 消息,`snapshots/web/schedule-catalog` 只记录任务查询。构成该夹具还缺两项 harness 能力:没有场景补丁能控制 `packages/schedule/schedule/src/runtime.ts` 读取的墙上时钟;快照 harness 播种的是 Session,而不是承载 Host 任务的 schedule storage domain,那些任务行只在 Web 测试里手工写入。因此本次记录缺失的 harness 支持,而不新增夹具。投递文本改由 `packages/schedule/schedule/tests/{domain,daily,weekly,cron}.spec.ts` 中五处整串断言,以及 `apps/web/tests/schedule-after.e2e.ts` 中在装配后请求上断言该行、覆盖单次与周期两条路径的 `expectReminderFraming` 固定。 diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml index 8b028995ae..5207fd6764 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.i18n.yaml @@ -9,11 +9,11 @@ en: abd0263d14861926 zh: e1736cd08e87f795 /agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision: - en: fdd39b7e8fa89d70 - zh: 4a0dfc81509e5485 + en: f1c2b98bf56cdba3 + zh: 7e9444f8e73a4834 /agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered: - en: 1737484c099fab52 - zh: 303b144c52d167bd + en: 3964f7d653747b55 + zh: b50636faea4917ef /agent-note-shared-time-vocabulary-for-wall-clock-selectors/consequences: - en: 79d8d66071453d1f - zh: f940f0b6d74148d6 + en: 9fdaa9da9c9952eb + zh: b941f68c9c1bb994 diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md index 2cc2c8be43..9592d362f0 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.md @@ -10,11 +10,11 @@ English | [中文](2026-09-24-shared-time-vocabulary.zh.md) ## Decision -`dsh-util-time` owns the time vocabulary that boundaries accept. `packages/util/time/src/instant.ts` holds the parsers, `src/duration.ts` holds the span type, and `src/index.ts` re-exports both and keeps `canonicalClientTimeZone` as the `string | undefined` wrapper the existing wire boundaries consume. +`dsh-util-time` owns the time vocabulary that boundaries accept. `packages/util/time/src/instant.ts` holds strict instant and zone parsers, `src/duration.ts` holds the span type, and `src/cron.ts` / `src/rrule.ts` hold bounded recurrence values. `src/index.ts` exports them and keeps `canonicalClientTimeZone` as the `string | undefined` wrapper the existing wire boundaries consume. The library answers discriminated results and carries no failure vocabulary. `parseOffsetInstant`, `fourDigitYearEpoch`, `parseLocalCalendar`, and `canonicalizeTimeZone` answer an `accepted` arm or a `rejected` arm naming a stable reason (`not_rfc3339`, `out_of_range`, `not_a_calendar_date`, `invalid_numeric_offset`, `malformed`, `blank`, `padded`, `not_area_location`, `unsupported`, `not_canonical_shape`). Each caller maps a reason onto its own code and diagnostic, so the library never writes model-facing text. `formatFourDigitYearInstant` returns the canonical instant text or `undefined` outside the bound, `isFourDigitYearInstant` answers whether an epoch is representable at all, and `resolveLocalInstant` answers epoch milliseconds or `undefined` for a wall-clock value inside a forward transition's gap. The reason vocabulary is parallel between the two strict parsers: the same condition is `out_of_range` in both, so year 0 is refused by `parseOffsetInstant` and `parseLocalCalendar` alike, while `resolveLocalInstant` accepts any year a real `Temporal` date carries because its callers derive local dates at the UTC edges. `LocalCalendarTime.year` records that split. -Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they now call the shared parser and map its reason. Schedule still owns the durable record shapes, the fold and transition authority, the injection-resistant framing, and all recurrence arithmetic: the cron engine, the daily and weekly date walks, the latest-due search, and the schedule-specific accepted-decision bound. +Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they call the shared parser and map its reason. Pure Cron/RRULE parsing and bounded occurrence searches belong to the library, take explicit reference times, and validate committed targets with `fourDigitYearEpoch`. Schedule owns durable records, the fold and transition authority, injection-resistant framing, daily and weekly date walks, delivery limits, and domain errors. The shared values own no task state, wall clock, or timers. `dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each user-rpc zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers. @@ -22,7 +22,7 @@ Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `d The last copy of the canonical instant profile moves too. `packages/session/session-format-v0-to-v1/src/payload-validation.ts` validated a stored schedule instant with its own regular expression and round trip; the shared `fourDigitYearEpoch` owns that same profile, so the migration now asks it and keeps its own error type and message. Because that migration reads released logs, its accepted set is a compatibility promise: `packages/session/session-format-v0-to-v1/tests/validation.spec.ts` accepts the four-digit-year bounds and refuses each spelling a regular expression alone would admit (`0000`, `2026-02-30`, a four-digit fraction, a numeric offset, surrounding whitespace). -The maintained `@js-temporal/polyfill` 0.5.1 becomes a runtime dependency of `dsh-util-time` as well as of `dsh-schedule`. Local resolution continues to use it, so the Host's IANA data still decides gaps and overlaps and no caller owns offset sampling. `util/time`'s own description and README drop the `zero-dependency` phrase as ambiguous: the group's charter forbids harness dependencies so any group may depend on util, and does not ban external packages, which is why `packages/README.md` and the `util/` line in `AGENTS.md` keep the phrase while `packages/util/README.md` and this package's own description name what it loads. +The maintained `@js-temporal/polyfill` 0.5.1 is a runtime dependency of `dsh-util-time` as well as of `dsh-schedule`; `rrule` supplies RRULE enumeration behind the library's strict syntax and cost checks. Local resolution uses Temporal, so the Host's IANA data decides gaps and overlaps and no caller owns offset sampling. The util group's charter forbids harness dependencies so any group may depend on util; it permits external packages, which this package's own description and README identify. Observable behavior does not change. Every accepted input resolves to the same epoch, every refused input raises the same `ScheduleInputError` or `ScheduleLogError` code and the same message, and the stored `scheduledAt` profile is unchanged, so no durable record and no recorded snapshot is re-recorded. Schedule's suites assert error codes and a few unrelated message substrings, so the assertion this change adds to `packages/schedule/schedule/tests/domain.spec.ts` is the only place that pins the three local-calendar message strings. `packages/util/time/tests/instant.spec.ts` covers the new entries directly, per-file 100% included. @@ -38,13 +38,13 @@ Observable behavior does not change. Every accepted input resolves to the same e **Hold the span in nanoseconds.** `Temporal` carries nanoseconds internally as a `bigint`, so a nanosecond span is representable. It was rejected for the same reason the boundaries stay in milliseconds: the count would have to be a `bigint`, which no `number` arithmetic, no `Date`, and no `JSON.stringify` accepts, so every consumer and every durable record would need a string or binary hop to move it. A nanosecond span as a `number` would instead be quantized to roughly 256 ns at the current epoch, which is a different value wearing the same name. -**Add formatting and DST arithmetic for other consumers too.** No current consumer needs model-facing formatting or offset arithmetic from this library: `dsh-time-context` owns its own formatter and zone policy text. Adding them now would give the library a public operation set with no consumer evidence, against the package rule that ties each abstraction to a current owner and need. +**Share model-facing formatting too.** `dsh-time-context` owns its formatter and zone policy text. Moving that presentation into the library would add consumer policy to the shared arithmetic, against the package rule that ties each abstraction to a current owner and need. ## Consequences The time profile now has one home. A change to the accepted instant profile or the zone profile is made once and covered once, and a new boundary imports it instead of copying it. Schedule's `domain.ts` loses the five regular expressions that spelled the instant, calendar-date, local-time, and zone profiles, the `Intl` canonicalization, and the hand-rolled calendar conversion. It still imports the library's two bound constants for its date arithmetic at the UTC edges and delegates every representability guard to `isFourDigitYearInstant`, so the range itself has one owner. -The cost is a wider published surface and a heavier dependency graph: `dsh-util-time` gains a runtime dependency on `@js-temporal/polyfill`, so a consumer that imports only `canonicalClientTimeZone` now loads that module too. The library is also no longer a pure "validation and canonicalization only" package, which its README and package description had to state and which its Known Limitations section now records. Schedule keeps a thin mapping layer at each entry. The local-calendar and instant mappers switch over the library's closed reason unions with a `never` default, so a newly added reason fails the build there instead of silently taking a catch-all. The zone mapper instead branches only on `not_canonical_shape` — a reason the current IANA data never produces, so it is guarded by a `v8 ignore` rather than a `never` default — and folds `blank`, `padded`, `not_area_location`, and `unsupported` into one diagnostic. A reason added to `TimeZoneRejection` later would therefore compile there and silently take that generic message. +The cost is a wider published surface and a heavier dependency graph: the root entry resolves `@js-temporal/polyfill` and `rrule` even for consumers that only need a zone or span. The README records that cost and the bounded recurrence profiles. Schedule keeps a thin mapping layer at each entry. The local-calendar and instant mappers switch over the library's closed reason unions with a `never` default, so a newly added reason fails the build there instead of silently taking a catch-all. The zone mapper instead branches only on `not_canonical_shape` — a reason the current IANA data never produces, so it is guarded by a `v8 ignore` rather than a `never` default — and folds `blank`, `padded`, `not_area_location`, and `unsupported` into one diagnostic. A reason added to `TimeZoneRejection` later would therefore compile there and silently take that generic message. A value type publishes what its consumers call, so the span exposes the constructor and the split that `dsh-time-context` uses and nothing else. A conversion, an arithmetic operation, or a `zero` identity lands with the caller that needs it; the seconds-valued fields at `dsh-schedule` and the DeepSeek file store are the spans that will ask for a second-unit conversion, and the bound and the freeze the class already carries are what make that addition a small one. The package README records the un-migrated boundaries as a known limitation. diff --git a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md index 72d4e6b12b..619cd29751 100644 --- a/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-24-shared-time-vocabulary.zh.md @@ -10,11 +10,11 @@ Status: implemented ## Decision -`dsh-util-time` 拥有各边界所接收的时间词汇。解析器位于 `packages/util/time/src/instant.ts`,时间段类型位于 `src/duration.ts`,`src/index.ts` 转出两者,并保留 `canonicalClientTimeZone` 作为既有协议边界消费的 `string | undefined` 包装。 +`dsh-util-time` 拥有各边界所接收的时间词汇。严格时刻与时区解析器位于 `packages/util/time/src/instant.ts`,时间段类型位于 `src/duration.ts`,有界重复规则值位于 `src/cron.ts` / `src/rrule.ts`。`src/index.ts` 导出这些入口,并保留 `canonicalClientTimeZone` 作为既有协议边界消费的 `string | undefined` 包装。 本库回答带判别值的结果,不持有失败词汇。`parseOffsetInstant`、`fourDigitYearEpoch`、`parseLocalCalendar` 与 `canonicalizeTimeZone` 回答 `accepted` 分支,或回答携带稳定原因的 `rejected` 分支(`not_rfc3339`、`out_of_range`、`not_a_calendar_date`、`invalid_numeric_offset`、`malformed`、`blank`、`padded`、`not_area_location`、`unsupported`、`not_canonical_shape`)。每个调用方把原因映射成自己的错误码与诊断文案,因此本库从不撰写面向模型的文本。`formatFourDigitYearInstant` 返回规范时刻文本,越界时返回 `undefined`;`isFourDigitYearInstant` 回答某个纪元是否可表示;`resolveLocalInstant` 回答纪元毫秒,对落在前向跳变缺口内的墙钟值回答 `undefined`。两个严格解析器的原因词汇彼此对称:同一条件在两者中都叫 `out_of_range`,所以年份 0 被 `parseOffsetInstant` 与 `parseLocalCalendar` 同样拒绝;而 `resolveLocalInstant` 接受真实 `Temporal` 日期携带的任何年份,因为它的调用方需要在 UTC 边界推导本地日期。`LocalCalendarTime.year` 记录了这一分工。 -Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们现在调用共享解析器并映射其原因。Schedule 仍拥有持久记录结构、折叠与状态转移权威、抗注入的框架文本,以及全部重复规则运算:cron 引擎、每日与每周日期遍历、最近到期搜索,以及 Schedule 特有的决策时刻边界。 +Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们调用共享解析器并映射其原因。纯 Cron/RRULE 解析与有界发生时点搜索归本库所有,接收显式参考时间,并通过 `fourDigitYearEpoch` 校验已提交时点。Schedule 拥有持久记录、折叠与状态转移权威、抗注入的框架文本、每日与每周日期遍历、投递限制及领域错误。共享值不拥有任务状态、墙钟或定时器。 `dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条 user-rpc 时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。 @@ -22,7 +22,7 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec 最后一份规范时刻剖面副本也一并迁移。`packages/session/session-format-v0-to-v1/src/payload-validation.ts` 原本用自己的一段正则与往返比对校验持久记录里的调度时刻;共享的 `fourDigitYearEpoch` 拥有同一剖面,因此该迁移改为询问它,并保留自己的错误类型与文案。由于这个迁移要读取已发布的日志,其接受集是兼容性承诺:`packages/session/session-format-v0-to-v1/tests/validation.spec.ts` 接受四位年份两端,并拒绝只靠正则会放进来的每种拼写(`0000`、`2026-02-30`、四位小数、数字偏移、首尾空白)。 -受维护的 `@js-temporal/polyfill` 0.5.1 在成为 `dsh-schedule` 运行时依赖之外,也成为 `dsh-util-time` 的运行时依赖。本地解析继续使用它,因此缺口与重叠仍由宿主 IANA 数据决定,也没有调用方需要自己实现偏移采样。`util/time` 自身的描述与 README 去掉了 `zero-dependency` 这一说法,因为它容易被误读:该组的约定禁止的是 harness 依赖(以便任何组都能依赖 util),并不禁止外部包;因此 `packages/README.md` 与 `AGENTS.md` 里的 `util/` 一行保留该说法,而 `packages/util/README.md` 与本包自己的描述写明它加载了什么。 +受维护的 `@js-temporal/polyfill` 0.5.1 是 `dsh-util-time` 与 `dsh-schedule` 的运行时依赖;`rrule` 在本库的严格语法与成本检查之后提供 RRULE 枚举。本地解析使用 Temporal,因此缺口与重叠由宿主 IANA 数据决定,也没有调用方需要自己实现偏移采样。util 组的约定禁止 harness 依赖,以便任何组都能依赖 util;它允许外部包,本包自己的描述与 README 写明了这些依赖。 可观察行为不变。每个被接受的输入解析出相同的纪元值,每个被拒绝的输入抛出相同的 `ScheduleInputError` 或 `ScheduleLogError` 错误码与相同的消息,存储的 `scheduledAt` 剖面不变,因此没有持久记录或录制快照需要重录。Schedule 的测试断言错误码以及少量无关的消息子串,因此本次在 `packages/schedule/schedule/tests/domain.spec.ts` 新增的断言是唯一固定这三条本地日历消息的地方。`packages/util/time/tests/instant.spec.ts` 直接覆盖新增入口,包含逐文件 100% 覆盖。 @@ -38,13 +38,13 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec **用纳秒保存时间段。** `Temporal` 内部以 `bigint` 携带纳秒,所以纳秒时间段是可表示的。之所以否决,理由与边界保持毫秒相同:计数必须变成 `bigint`,而 `number` 算术、`Date` 与 `JSON.stringify` 都不接受它,于是每个消费方与每条持久记录都要多一次字符串或二进制转换。若改用 `number` 表示纳秒,在当前离线纪元量级上它会被量化到约 256 ns,那是同一个名字下的另一个值。 -**同时为其他消费方加入格式化与 DST 运算。** 目前没有消费方需要本库提供面向模型的格式化或偏移运算:`dsh-time-context` 自己拥有格式化器与时区策略文本。现在加入只会给本库一个没有消费方证据的公开操作集合,违背"每项抽象都绑定当前所有者与需求"的包规则。 +**同时共享面向模型的格式化。** `dsh-time-context` 拥有自己的格式化器与时区策略文本。把这些呈现迁入本库会向共享算术加入消费方策略,违背“每项抽象都绑定当前所有者与需求”的包规则。 ## Consequences 时间剖面现在只有一个归宿。时刻剖面或时区剖面的变更只做一次、只覆盖一次,新边界导入它而不是复制它。Schedule 的 `domain.ts` 去掉了为时刻、日历日期、本地时间与时区剖面命名的五段正则、`Intl` 规范化与手写日历换算。它仍然导入本库的两个边界常量用于其 UTC 边界日期运算,并把每处可表示性守卫委托给 `isFourDigitYearInstant`,因此范围本身只有一个所有者。 -代价是更宽的已发布接口与更重的依赖图:`dsh-util-time` 增加了对 `@js-temporal/polyfill` 的运行时依赖,因此只导入 `canonicalClientTimeZone` 的消费方也会加载该模块。本库也不再是纯"只做校验与规范化"的包——其 README 与包描述必须说明这一点,其"已知限制"一节现在也记录了它。Schedule 在每个入口保留一层薄映射。本地日历与时刻映射函数以 `never` 默认分支穷尽 switch 本库的封闭原因联合,因此新增原因会让这两个调用点构建失败,而不是静默走兜底分支。时区映射函数则只对 `not_canonical_shape` 分支——当前 IANA 数据不会产生该原因,因此它由 `v8 ignore` 守护而不是 `never` 默认分支——并把 `blank`、`padded`、`not_area_location` 与 `unsupported` 合并成一条诊断。因此日后给 `TimeZoneRejection` 新增原因时会通过编译并静默套用那条通用文案。 +代价是更宽的已发布接口与更重的依赖图:根入口会解析 `@js-temporal/polyfill` 和 `rrule`,只需要时区或跨度的消费方也一样。README 记录了这些成本与有界重复规则子集。Schedule 在每个入口保留一层薄映射。本地日历与时刻映射函数以 `never` 默认分支穷尽 switch 本库的封闭原因联合,因此新增原因会让这两个调用点构建失败,而不是静默走兜底分支。时区映射函数则只对 `not_canonical_shape` 分支——当前 IANA 数据不会产生该原因,因此它由 `v8 ignore` 守护而不是 `never` 默认分支——并把 `blank`、`padded`、`not_area_location` 与 `unsupported` 合并成一条诊断。因此日后给 `TimeZoneRejection` 新增原因时会通过编译并静默套用那条通用文案。 值类型只发布消费方会调用的部分,因此这个时间段只暴露 `dsh-time-context` 用到的构造入口与拆解,其余不发布。某个换算、某个算术运算或 `zero` 恒等元都随第一个需要它的调用方落地;`dsh-schedule` 与 DeepSeek 文件存储里以秒为单位的字段就是将来会要求第二个单位换算的那些跨度,而类已经携带的范围约束与冻结正是让这次添加保持很小的原因。包 README 把这些尚未迁移的边界记为已知限制。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml index 65205260c3..f1c602359c 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.i18n.yaml @@ -2,18 +2,18 @@ # section, a hash of its English and Chinese blocks outside code blocks and generated regions. # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md -/agent-note-team-identity-in-required-runtime-context: - en: 8c88759320ae8481 - zh: 4068b18723907eb9 -/agent-note-team-identity-in-required-runtime-context/problem: - en: c9a81cb731ddf7b2 - zh: 428c0e6f8937d7c5 -/agent-note-team-identity-in-required-runtime-context/decision: - en: 6c73479973c1e378 - zh: 98677c77f77f8d81 -/agent-note-team-identity-in-required-runtime-context/alternatives-considered: +/agent-note-subagent-identity-in-required-runtime-context: + en: ce8f378b6e7b57fa + zh: 26bd0415b4dba94a +/agent-note-subagent-identity-in-required-runtime-context/problem: + en: f944254565541454 + zh: 27fa9f67c671dec7 +/agent-note-subagent-identity-in-required-runtime-context/decision: + en: 85100936f97a139c + zh: 614081943944e28b +/agent-note-subagent-identity-in-required-runtime-context/alternatives-considered: en: 774566ffbf9e9db8 zh: ea761d876af462f2 -/agent-note-team-identity-in-required-runtime-context/consequences: - en: 18d1aa67936f1227 - zh: 7e06c1f51553ecdd +/agent-note-subagent-identity-in-required-runtime-context/consequences: + en: 2c01a24cd8cc4556 + zh: 37b5d1ca1173318a diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md index 39794f02d3..fb8e92e811 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.md @@ -1,4 +1,4 @@ -# Agent Note: Team identity in required runtime context +# Agent Note: Subagent identity in required runtime context Status: implemented @@ -6,15 +6,15 @@ English | [中文](2026-10-13-team-identity-runtime-context.zh.md) ## Problem -A teammate identity embedded in its initial task depends on ordinary history retention. Compaction can remove it, and an ordinary fork from that teammate can retain the old role even though the fork is an independent Lead. Identity must reflect current membership while keeping shared system instructions uniform. +A teammate identity embedded in its initial task depends on ordinary history retention. Compaction can remove it, and an ordinary fork from that teammate can retain the old role even though the fork is an independent Lead. Identity must reflect the current subagent tree while keeping shared system instructions uniform. ## Decision -`tool-agent-team` contributes `team:identity` through the Agent-scoped `systemPrompt.context()` registry with `required: true`. Its provider reads the existing Team membership and renders the member's role, name, and addressing instructions. Optional-context suppression cannot remove it. Fixed collaboration policy stays in the system prompt; roster and task state remain tool queries. Initial tasks contain only their supplied content. +`tool-subagent-control` contributes required `subagent:identity` through `systemPrompt.context()` in ordinary subagent and Team compositions. It derives identity from `ctx.subagents.rootOf(agent)`: the root sees its own Session id, and descendants see their own, direct parent, and root ids. An unavailable root is reported explicitly. Optional-context suppression and Team mode do not remove identity. Agents receive messaging and discovery guidance only while the root is available and each corresponding standard tool is admitted. Team task policy stays in the shared system prompt; task state remains a tool query. The loop owns logging, retained-snapshot comparison, and re-admission after compaction. A changed role appends the current full runtime-context snapshot after inherited history; unchanged retained context adds no message. No Team-specific retention state, event type, or log migration is introduced. Existing recorded reminders remain historical messages. -This supersedes only the initial-task identity decision in [Agent Teams](../feature/2026-08-05-agent-teams.md#team-identity); its roster, mailbox, and task decisions remain active. +This supersedes only the initial-task identity decision in [Agent Teams](../feature/2026-08-05-agent-teams.md#team-identity). [Task-board wait coordination](2026-10-19-team-task-board-inbox.md) keeps ordinary inbox waiting independent of Team-only model guidance. ## Alternatives considered @@ -28,4 +28,4 @@ This supersedes only the initial-task identity decision in [Agent Teams](../feat Members pay for identity within the full runtime-context snapshot. Other context changes repeat it, while stable retained context adds no new message. Forks preserve inherited history and append current identity; actual provider cache hits remain best-effort. Existing Team authorization remains in tool execution. -Verification covers fresh and fork teammates, an independent fork from a teammate, optional-context suppression, compaction restoration, cold resume, and registration disposal. The recorded `team-targets` scenario pins Lead context; the keyless headless Team workflow pins teammate context through the shipped profile. +Verification covers fresh and fork children, an independent Session fork, optional-context suppression, compaction restoration, unavailable roots, cold resume, and registration disposal. Recorded ordinary subagent and Team workflows pin identity through their shipped compositions; delegated tasks retain final-result return guidance. diff --git a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md index d0e333a71e..f3ebb3e6b3 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-team-identity-runtime-context.zh.md @@ -1,4 +1,4 @@ -# Agent Note: 必需 runtime context 中的 Team 身份 +# Agent Note: 必需 runtime context 中的 subagent 身份 Status: implemented @@ -6,15 +6,15 @@ Status: implemented ## Problem -嵌入初始任务的 teammate 身份依赖普通历史保留。压缩可能移除它;从 teammate 创建的普通 fork 即使已成为独立 Lead,也可能保留旧角色。身份必须反映当前 membership,同时保持共享系统指令一致。 +嵌入初始任务的 teammate 身份依赖普通历史保留。压缩可能移除它;从 teammate 创建的普通 fork 即使已成为独立 Lead,也可能保留旧角色。身份必须反映当前 subagent 树,同时保持共享系统指令一致。 ## Decision -`tool-agent-team` 通过 Agent 作用域的 `systemPrompt.context()` 注册 `team:identity`,并设置 `required: true`。提供方读取现有 Team membership,渲染成员角色、名字与寻址说明。关闭可选 context 不能移除它。固定协作策略保留在 system prompt;roster 和 task 状态仍通过工具查询。初始任务只包含传入的正文。 +`tool-subagent-control` 在普通 subagent 和 Team 组合中通过 `systemPrompt.context()` 提供必需的 `subagent:identity`。它从 `ctx.subagents.rootOf(agent)` 派生身份:根看到自身 Session id,后代看到自身、直接父级和根 id。根不可用时会明确报告。可选上下文抑制和 Team 模式都不会移除身份。只有根可用时,agent 才会分别根据对应标准工具的获准情况收到通信与发现指导。Team 任务策略保留在共享系统提示中;任务状态仍通过工具查询。 Loop 负责日志记录、保留快照比较和压缩后的重新接纳。角色变化会在继承历史之后追加当前完整 runtime-context 快照;保留的 context 未变化时不追加消息。不引入 Team 专属的保留状态、事件类型或日志迁移。已有身份提醒仍作为历史消息保留。 -本决策仅取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md#team-identity) 中的初始任务身份决策;其 roster、mailbox 和 task 决策仍然有效。 +这仅取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md#team-identity) 中将身份放入初始任务的决策。[任务板等待协调](2026-10-19-team-task-board-inbox.zh.md)使普通收件箱等待独立于 Team 专用模型指导。 ## Alternatives considered @@ -28,4 +28,4 @@ Loop 负责日志记录、保留快照比较和压缩后的重新接纳。角色 成员承担完整 runtime-context 快照中的身份 token 成本。其他 context 变化会重复身份,保留的 context 稳定时则不追加消息。Fork 保留继承历史并追加当前身份;提供方实际缓存命中仍为尽力而为。现有 Team 授权仍在工具执行时落实。 -验证覆盖 fresh 和 fork teammate、从 teammate 创建的独立 fork、关闭可选 context、压缩后恢复、冷恢复和注册释放。录制的 `team-targets` 场景固定 Lead context;无密钥 headless Team 工作流通过内置 profile 固定 teammate context。 +验证覆盖新建和 fork 子级、独立 Session fork、可选上下文抑制、压缩恢复、不可用根、冷恢复和注册释放。录制的普通 subagent 和 Team 工作流通过各自的分发组合固定身份行为;委派任务保留最终结果返回指导。 diff --git a/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.i18n.yaml new file mode 100644 index 0000000000..282acab92a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-15-agent-teams-as-subagents.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.md +/agent-note-agent-teams-teammates-are-subagents: + en: 51e2fc51a6e1622a + zh: 7e09ea6292e5921d +/agent-note-agent-teams-teammates-are-subagents/problem: + en: ca2848e3bbc3a009 + zh: 0551e32ff6d187d0 +/agent-note-agent-teams-teammates-are-subagents/decision: + en: 2c29c42cc02a9a05 + zh: bc542e3a27cfd03d +/agent-note-agent-teams-teammates-are-subagents/alternatives-considered: + en: ef0cf648ff54784f + zh: 2a0b3745a54e7072 +/agent-note-agent-teams-teammates-are-subagents/consequences: + en: 3ff718671be076fa + zh: 38a367077ce95d52 +/agent-note-agent-teams-teammates-are-subagents/testing: + en: a0ec8546a783bfd9 + zh: 8920b46970e3a2de diff --git a/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.md b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.md new file mode 100644 index 0000000000..8cab7023e0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.md @@ -0,0 +1,41 @@ +# Agent Note: Agent Teams teammates are subagents + +Status: implemented + +English | [中文](2026-10-15-agent-teams-as-subagents.zh.md) + +The adjacency and parent-lifetime restrictions are superseded by [tree-wide communication](2026-10-16-tree-wide-agent-communication.md). [Task-board inbox coordination](2026-10-19-team-task-board-inbox.md) supersedes the separate roster and Team-owned wait; the single subagent identity decision remains active. + +## Problem + +Teammates already use the subagent runtime for creation, Session identity, catalog membership, capacity, cold resume, settlement, and interruption. A separate Team roster duplicates identity, provisioning recovery, and teardown. Team-scoped messaging and control tools shadow the standard subagent tools, forcing profiles to disable ordinary delegation and making fork tool schemas diverge from their parent. + +## Decision + +Use one subagent identity: the Session id. The existing `description` tool argument supplies the catalog label and display text; descriptions may repeat and never address an agent. Creation accepts no member name, reserves no names, and adds no catalog payload version. + +[Tree-wide communication](2026-10-16-tree-wide-agent-communication.md) authorizes an exact live sender within one root tree and preserves the actual sender’s id. Interruption retains ancestor authority and id addressing. + +Every root Agent and its descendants form the Team identified by the root Session id. Team creates no agents and contributes task tools and task policy. Ordinary subagent controls supply required identity, discovery, messaging, interruption, and inbox waiting. Parent and fork children receive identical tool schemas and shared policies. + +Task ownership uses `ownerId`; root reassignment accepts itself or any reachable continuable descendant. Historical roster records remain decode-only. Team persists task changes without ending inbox waits or starting idle turns; [inbox-only waiting](../simplification/2026-10-29-inbox-only-agent-wait.md) owns wake behavior. Historical `team/message/*` records remain readable but are never delivered or acknowledged. + +This supersedes the roster, provisioning, recovery, and messaging decisions in [Agent Teams](../feature/2026-08-05-agent-teams.md) and the [Team direct inbox decision](../../archived/simplification/2026-09-26-team-direct-inbox.md). The task-board and shared-checkout decisions remain active. [Adjacent Agent messaging](2026-08-27-adjacent-agent-steer-messaging.md) includes sibling routing, while [required runtime-context identity](2026-10-13-team-identity-runtime-context.md) owns the role statement. The [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.md) lists removed tools, methods, and configuration. + +## Alternatives considered + +**Separate Team authority and tools.** This retains a second roster and recovery lifecycle for Agents already owned by the subagent runtime, plus same-name tools and a private delivery adapter. The shared parent relation supplies the required authority. + +**Unique names as sibling-routing opt-in.** Names add validation, reservation, persistence, and ambiguous resolution beside existing Session ids. Descriptions already explain responsibilities; stable ids distinguish repeated descriptions without another identity system. + +**Pluggable address books.** A registry would support groups spanning unrelated parents but add another authorization input. No current consumer needs this; revisit when collaboration must cross parent trees. + +## Consequences + +Tree members discover and message one another through ordinary controls. Team retains task ownership, dependencies, and task policy. Subagent capacity and lifecycle apply; failed starts create no Team roster row. Existing durable task generations remain unchanged. + +Descendants at any depth share the board and can be task owners. Historical members grant no authority. Separate working directories remain explicit caller choices; cross-process task coordination is unsupported. + +## Testing + +Verification covers tree delivery and cold resume with actual sender attribution, task CAS and owner discovery, historical decoding, inbox wait isolation, and registration disposal. Recorded sessions cover Team policy and identity, plus ordinary subagent return guidance. diff --git a/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.zh.md b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.zh.md new file mode 100644 index 0000000000..8c113d288a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-15-agent-teams-as-subagents.zh.md @@ -0,0 +1,41 @@ +# Agent Note: Agent Teams 队友是子代理 + +Status: implemented + +[English](2026-10-15-agent-teams-as-subagents.md) | 中文 + +邻接和父级生命周期限制由[整树通信](2026-10-16-tree-wide-agent-communication.zh.md)取代。[任务板收件箱协调](2026-10-19-team-task-board-inbox.zh.md)取代独立名册和 Team 所有的等待;单一 subagent 身份决策仍有效。 + +## Problem + +队友已经使用子代理运行时完成创建、Session 身份、目录成员关系、容量、冷恢复、结算和中断。独立 Team 成员列表重复了身份、创建恢复和释放职责。Team 作用域内的消息及控制工具覆盖标准子代理工具,迫使 profile 禁用普通委派,并使分叉工具模式偏离父级。 + +## Decision + +统一使用子代理的 Session id 作为身份。现有 `description` 工具参数提供目录标签和展示文本;描述可以重复,不用于寻址代理。创建不接收成员名称、不预留名称,也不增加目录载荷版本。 + +[整树通信](2026-10-16-tree-wide-agent-communication.zh.md)在同一根树内授权当前在线发送方,并保留实际发送方 id。中断保留祖先权限和 id 寻址。 + +每个根 Agent 及其后代组成以根 Session id 标识的 Team。Team 不创建 agent,提供任务工具和任务策略。普通 subagent 控制工具提供必需身份、发现、通信、中断和收件箱等待。父级和 fork 子级接收相同工具 schema 和共享策略。 + +任务归属使用 `ownerId`;根重新分配可指定自身或任意可达的可继续执行后代。历史名册记录仅供解码。Team 持久化任务变更,不结束收件箱等待,也不启动空闲轮次;[仅等待收件箱](../simplification/2026-10-29-inbox-only-agent-wait.zh.md)负责唤醒行为。历史 `team/message/*` 记录仍可读取,但绝不再投递或确认。 + +本决策取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md) 的成员列表、创建、恢复和消息决策,以及 [Team 直接收件箱决策](../../archived/simplification/2026-09-26-team-direct-inbox.md)。任务板和共享工作树决策仍有效。[相邻 Agent 消息](2026-08-27-adjacent-agent-steer-messaging.zh.md)纳入同级路由,[必需运行时身份](2026-10-13-team-identity-runtime-context.zh.md)负责角色声明。[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.zh.md)列出移除的工具、方法和配置。 + +## Alternatives considered + +**独立 Team 权限和工具。** 这会为子代理运行时已拥有的 Agent 保留第二套成员列表与恢复生命周期,以及同名工具和私有投递适配器。共同父级关系已经提供所需权限。 + +**以唯一名称选择性启用同级路由。** 名称会在现有 Session id 之外增加校验、预留、持久化和歧义解析。描述已能说明职责;稳定 id 可以区分重复描述,无需另一套身份系统。 + +**可插拔地址簿。** 注册表可支持跨不同父级的组,但会增加另一种授权输入。当前没有消费者需要此能力;协作必须跨父级树时再考虑。 + +## Consequences + +树内成员通过普通控制工具发现和联系彼此。Team 保留任务归属、依赖和任务策略。容量和生命周期遵循 subagent 规则;启动失败不会创建 Team 名册行。现有持久化任务代次保持不变。 + +任意深度后代共享任务板,均可成为任务所有者。历史成员不授予权限。独立工作目录仍由调用者显式选择;不支持跨进程任务协调。 + +## Testing + +验证覆盖具有实际发送方归属的整树投递和冷恢复、任务 CAS 与所有者发现、历史解码、收件箱等待隔离和注册释放。录制会话覆盖 Team 策略和身份,以及普通 subagent 返回指导。 diff --git a/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.i18n.yaml new file mode 100644 index 0000000000..ee52c30615 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-16-tree-wide-agent-communication.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.md +/agent-note-communication-follows-the-subagent-tree: + en: 849d806b901e9f04 + zh: 649b2984f844d510 +/agent-note-communication-follows-the-subagent-tree/problem: + en: c583c3cdb894e417 + zh: 6edc0354b79f4f26 +/agent-note-communication-follows-the-subagent-tree/decision: + en: da35a75e069fa1e4 + zh: 7edf62ad66ab04ec +/agent-note-communication-follows-the-subagent-tree/alternatives-considered: + en: 470f9cf8c3e32af9 + zh: 73bbe29767c5d02a +/agent-note-communication-follows-the-subagent-tree/consequences: + en: 6d409833d762d473 + zh: 000cd93577ec6b34 diff --git a/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.md b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.md new file mode 100644 index 0000000000..30dee6781a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.md @@ -0,0 +1,29 @@ +# Agent Note: Communication follows the subagent tree + +Status: implemented + +English | [中文](2026-10-16-tree-wide-agent-communication.zh.md) + +## Problem + +A Team shares one task board across the root's entire subagent tree. Restricting discovery and messages to adjacent relatives forces deeper members to relay work through parents despite sharing tasks. + +## Decision + +`list_agents` starts at the caller's live root and lists that root and all reachable continuable descendants, including the caller. Parent ids and depth remain relative to the root. The existing parent catalogs remain authoritative; no Team directory is stored separately. + +`send_message` accepts another root or continuable member of the same tree. The sender must be the exact live root or a resident continuable subagent. Cross-branch delivery verifies the target descriptor and creation catalogs, then restores only the target under the Team root. Final inbox admission rechecks the sender and root. Cancellation or rejection before acceptance releases the new target instance; accepted input follows normal Agent persistence. + +The existing Agent registry records runtime ownership by the Team root. Creation parent ids and catalogs preserve ancestry for discovery and interrupt authority. A member finishing or being released affects only its own instance; Team-root shutdown joins all startup and cleanup. This removes ancestor restoration, parent retention, and recursive disposal without adding a Team runtime registry. Saved target presets and permission events supply restoration configuration. + +This supersedes the adjacency, discovery, and parent-lifetime restrictions in [adjacent messaging](2026-08-27-adjacent-agent-steer-messaging.md) and [subagent teammates](2026-10-15-agent-teams-as-subagents.md). Their shared inbox, scheduling, attribution, and Team reuse decisions remain active. Members use Session ids for addressing; ordinary Session forks lead independent Teams. + +## Alternatives considered + +**Relay through parents.** This preserves the narrower routing implementation but makes the creation hierarchy determine who can collaborate. Shared work requires direct communication across branches. + +**Separate Team directory and delivery.** A second member list and message path would duplicate the existing catalogs, inbox, and restoration lifecycle. Tree membership supplies the required communication scope without another registry. + +## Consequences + +Discovery output grows with the whole tree. Cold delivery requires one capacity slot and readable creation history. Intermediate creators may be offline. Completion notices reach only online creators, so work that requires descendant results must explicitly wait. Listing is a snapshot and does not promise that a later send succeeds. External and one-shot executions cannot receive follow-ups. diff --git a/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.zh.md b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.zh.md new file mode 100644 index 0000000000..58d075e9a6 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-16-tree-wide-agent-communication.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 通信范围由子代理树决定 + +Status: implemented + +[English](2026-10-16-tree-wide-agent-communication.md) | 中文 + +## Problem + +一个 Team 在根的整棵子代理树中共享任务板。把发现和消息限定在相邻成员之间,会迫使深层成员在共享任务的同时,仍通过父级转发工作。 + +## Decision + +`list_agents` 从调用方的在线根开始,列出该根与所有可达的可继续后代,包括调用方。父级 id 和深度始终相对根计算。现有父级目录仍是权威来源;不单独存储 Team 目录。 + +`send_message` 接受同一棵树中的其他根或可继续成员。发送者必须是确切在线根或驻留的可继续子代理。跨分支投递验证目标描述符和创建目录后,仅在 Team 根下恢复目标。最终收件箱准入重新检查发送者与根。接受前的取消或拒绝释放新建目标实例;已接受输入遵循普通 Agent 持久化。 + +现有 Agent 注册表记录 Team 根对运行时实例的所有权。创建父级 id 和目录保留用于发现及中断授权的祖先关系。成员完成或释放只影响自身实例;关闭 Team 根会等待全部启动和清理。这删除了祖先恢复、父级保留和递归释放,无需增加 Team 运行时注册表。目标保存的 preset 和权限事件提供恢复配置。 + +本决策替代[相邻消息](2026-08-27-adjacent-agent-steer-messaging.zh.md)与[子代理队友](2026-10-15-agent-teams-as-subagents.zh.md)中的邻接、发现及父子生命周期限制。它们的共享收件箱、调度、发送者归属和 Team 复用决策仍有效。成员使用 Session id 寻址;普通 Session 分叉领导独立 Team。 + +## Alternatives considered + +**通过父级转发。** 这保留了更窄的路由实现,却让创建层级决定谁能协作。共享工作需要跨分支直接通信。 + +**单独的 Team 目录与投递。** 第二份成员列表和消息路径会重复现有目录、收件箱与恢复生命周期。树成员身份已经提供所需通信范围,无需另一个注册表。 + +## Consequences + +发现输出随整棵树增长。冷投递需要一个容量名额和可读的创建历史。中间创建者可以离线。完成通知仅投递给在线创建者,因此依赖后代结果的工作必须显式等待。列表是快照,不保证后续发送成功。外部执行和一次性执行不能接收后续消息。 diff --git a/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.i18n.yaml new file mode 100644 index 0000000000..aa751903bf --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-19-team-task-board-inbox.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.md +/agent-note-team-task-boards-share-ordinary-subagent-waits: + en: 7f19734715f5d50f + zh: 95af09c9d855d1af +/agent-note-team-task-boards-share-ordinary-subagent-waits/problem: + en: 6fdc766a348d8659 + zh: 8a84748e147deed5 +/agent-note-team-task-boards-share-ordinary-subagent-waits/decision: + en: 154da8a8a5146c89 + zh: 76a7c921153d238d +/agent-note-team-task-boards-share-ordinary-subagent-waits/alternatives-considered: + en: eed6f6d4fa0ccd7b + zh: 61271057d6e5d019 +/agent-note-team-task-boards-share-ordinary-subagent-waits/consequences: + en: cc250eb21dbb45a1 + zh: 9d03d1eb53075fb6 diff --git a/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.md b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.md new file mode 100644 index 0000000000..818298684c --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.md @@ -0,0 +1,31 @@ +# Agent Note: Team task boards share ordinary subagent waits + +Status: implemented + +English | [中文](2026-10-19-team-task-board-inbox.zh.md) + +## Problem + +The subagent tree already supplies identity, discovery, routing, and lifecycle. A second Team roster can grant assignment authority from stale history and duplicates member navigation. Team-wide status waits observe unrelated activity and miss input already pending for the caller. Persisting task-board wakeups as messages adds unread state and message schemas even though the task journal already owns the state to inspect. + +## Decision + +The subagent tree is the Team. Ordinary controls own required identity, communication, discovery, interruption, and `wait_agent`, independently of the optional task board. Team tools own task policy, without adding it to ordinary subagent compositions. Team owns task storage, dependencies, and compare-and-set commands. Assignment accepts the root or any discovered continuable descendant. Historical roster records grant no authority; the Team panel shows tasks and ordinary navigation owns members. + +The wait-signal decision is superseded by [inbox-only Agent waits](../simplification/2026-10-29-inbox-only-agent-wait.md). Tree ownership, task durability, and historical non-authority remain unchanged. + +Task state remains in the existing journal. Ordinary tool results record what the waiting model observes. Historical roster, mailbox, and task generations remain readable and unchanged. This partially supersedes the roster and wait decisions in [Agent Teams](../feature/2026-08-05-agent-teams.md) and [subagent teammates](2026-10-15-agent-teams-as-subagents.md). Their task durability and single-identity rationale remain active; [required runtime identity](2026-10-13-team-identity-runtime-context.md) owns retention. + +## Alternatives considered + +**Keep Team membership and a separate wait tool.** This duplicates tree authority and wait lifecycle, allowing stale roster rows or unrelated activity to affect current work. + +**Persist task-board notices in every inbox.** The task journal already preserves every revision. Durable notices add message types, unread state, coalescing, and delivery-failure recovery solely to interrupt a current wait. + +**Poll Agent status or start every idle task owner.** Activity does not identify useful input, and task readiness does not authorize a new turn. Explicit messages continue idle work when needed. + +## Consequences + +Task completion, inbox availability, current waiting, and Agent lifetime remain separate. Task updates do not end waits; callers inspect current tasks when deciding what to do. The task journal retains committed revisions without storing redundant notifications in recipient Sessions. + +Verification distinguishes pending inbox input from task commits, isolates callers, excludes next-turn input and status changes, and covers wait cleanup and task persistence. Assignment coverage retains arbitrary depth and historical non-authority. diff --git a/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.zh.md b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.zh.md new file mode 100644 index 0000000000..3a88ce8d19 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.zh.md @@ -0,0 +1,31 @@ +# Agent Note: Team 任务板复用普通 subagent 等待 + +Status: implemented + +[English](2026-10-19-team-task-board-inbox.md) | 中文 + +## 问题 + +subagent 树已经提供身份、发现、路由和生命周期。第二份 Team 名册可能根据过期历史授予分配权限,并重复成员导航。Team 范围状态等待会观察无关活动,却漏掉调用者已有的待处理输入。任务日志已经拥有待查询状态,将任务板唤醒持久化为消息仍会增加未读状态和消息 schema。 + +## 决策 + +subagent 树就是 Team。普通控制工具独立于可选任务板,负责必需身份、通信、发现、中断和 `wait_agent`。Team 工具负责任务策略,不向普通 subagent 组合添加该策略。Team 负责任务存储、依赖和比较并交换命令。分配接受根或任意已发现的可继续执行后代。历史名册不授予权限;Team 面板显示任务,普通导航负责成员。 + +等待信号决策已由[仅等待收件箱的 Agent 等待](../simplification/2026-10-29-inbox-only-agent-wait.zh.md)取代。树归属、任务持久性和历史记录不授予权限的决策保持不变。 + +任务状态保留在现有日志中。普通工具结果记录等待中的模型所观察到的结果。历史名册、邮箱和任务代次保持可读且不变。这部分取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md) 和 [subagent 队友](2026-10-15-agent-teams-as-subagents.zh.md) 中的名册与等待决策。其任务持久性和单一身份理由继续生效;[必需运行时身份](2026-10-13-team-identity-runtime-context.zh.md)负责保留规则。 + +## 考虑过的替代方案 + +**保留 Team 成员关系与独立等待工具。** 这会重复树权限和等待生命周期,让过期名册行或无关活动影响当前工作。 + +**将任务板通知持久化到每个收件箱。** 任务日志已保留每个修订。持久通知仅为打断当前等待,就增加消息类型、未读状态、合并和投递失败恢复。 + +**轮询 Agent 状态或启动每个空闲任务所有者。** 活动状态不能标识有用输入,任务就绪也不授权新轮次。需要时通过显式消息继续空闲成员的工作。 + +## 后果 + +任务完成、收件箱可用性、当前等待和 Agent 生命周期保持独立。任务更新不会结束等待;调用者在决定下一步工作时查询当前任务。任务日志保留已提交修订,不在接收者 Session 中存储重复通知。 + +验证区分已有收件箱输入和任务提交,隔离调用者,排除下一轮输入及状态变化,并覆盖等待清理和任务持久性。分配验证保留任意深度和历史记录无权限场景。 diff --git a/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.i18n.yaml new file mode 100644 index 0000000000..afbff73943 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-20-session-team-mode.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-20-session-team-mode.md +/agent-note-team-availability-is-selected-per-session: + en: 5f36d81bd414ea67 + zh: 71883b0fe2afd1b6 +/agent-note-team-availability-is-selected-per-session/problem: + en: db7a81ab452fdd0f + zh: a14fdcdb8ff4cd47 +/agent-note-team-availability-is-selected-per-session/decision: + en: f4e4ba7be0eda796 + zh: 410649e86ff5ca72 +/agent-note-team-availability-is-selected-per-session/alternatives-considered: + en: cd3cc1f3fab84f80 + zh: 6d7792742d62f9fe +/agent-note-team-availability-is-selected-per-session/consequences: + en: b56a6a1c8ad1aa7a + zh: 43bdd8a5bccce8bf diff --git a/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.md b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.md new file mode 100644 index 0000000000..2449e1e4d0 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.md @@ -0,0 +1,29 @@ +# Agent Note: Team availability is selected per Session + +Status: implemented + +English | [中文](2026-10-20-session-team-mode.zh.md) + +## Problem + +A plugin-level Team switch requires users to change the shared profile before choosing collaboration for one conversation. It can disable another Session’s capability and leaves a second control beside the Session selection. Ordinary tasks still need their existing tool catalog, and disabling collaboration must not discard task history or children. + +## Decision + +The base bundle loads the Team service and task tools, and the Web bundle loads the Team UI. The packages belong to the subagent and client product groups. A saved root-Session selection gates task tools and Team guidance throughout the tree, and the shared board in the root conversation; new Sessions default off. Ordinary subagent creation, communication, and navigation remain available. + +The model and reasoning menu owns the user’s selection. The root conversation’s Subagent panel displays members above shared tasks. Disabling Team keeps the journal and children; re-enabling restores the board. Historical task boards without a saved selection stay enabled. Profile loading removes the retired optional bundle selection, retaining row overrides. + +This supersedes the explicit-composition choice in [Agent Teams](../feature/2026-08-05-agent-teams.md). Its durability, ownership, and lifecycle decisions remain active. [Optional bundles](../process/2026-09-15-shipped-optional-bundles.md) still governs other experimental features. + +## Alternatives considered + +**Keep both switches.** Capability installation remains a prerequisite that the conversation control cannot explain or resolve; users must manage shared profile state for a Session decision. + +**Hide the plugin card without loading Team.** New profiles would have no way to obtain the capability. Loading experimental packages in the default profile would violate product isolation; moving them to their owning product groups makes the delivered support explicit. + +## Consequences + +Default profiles carry the Team implementation while exposing no task tools until enabled. The removed package names require custom compositions to migrate; durable event names and task data remain unchanged. [The upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md) owns those steps. + +Verification covers default startup, new-Session opt-in, independent roots, persisted selections, retained tasks, old profile migration, and absence of the plugin switch. Product-isolation checks retain an unrelated experimental plugin as their negative control. diff --git a/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.zh.md b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.zh.md new file mode 100644 index 0000000000..5b8baec113 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-20-session-team-mode.zh.md @@ -0,0 +1,29 @@ +# Agent Note: 按 Session 选择 Team 能力 + +Status: implemented + +[English](2026-10-20-session-team-mode.md) | 中文 + +## Problem + +插件级 Team 开关要求用户先修改共享 profile,才能为一个会话选择协作。它可能关闭另一个 Session 的能力,并在会话选项之外留下第二个控件。普通任务仍需要原有工具目录,关闭协作也不能丢弃任务历史或子智能体。 + +## Decision + +基础 bundle 加载 Team 服务与任务工具,Web bundle 加载 Team UI。相关包归属 subagent 与 client 产品组。根 Session 保存的选择控制整棵树的任务工具与 Team 指引,以及根会话中的共享任务板;新 Session 默认关闭。普通 subagent 创建、通信与导航继续可用。 + +模型与推理等级菜单承载用户选择。根会话的 Subagent 面板在成员下方显示共享任务。关闭 Team 保留日志与子智能体;重新开启恢复任务板。没有保存选择的历史任务板保持开启。profile 加载时移除已停用的可选 bundle 选择,保留配置行覆盖。 + +本决策替代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md) 中显式选择组合的部分;其持久性、归属与生命周期决策继续有效。[可选 bundle](../process/2026-09-15-shipped-optional-bundles.zh.md)仍约束其他实验性功能。 + +## Alternatives considered + +**保留两个开关。** 安装能力仍是会话控件无法解释或解决的前置条件;用户必须为 Session 决策管理共享 profile 状态。 + +**隐藏插件卡片但不加载 Team。** 新 profile 将无法获得该能力。默认 profile 加载实验性包会违反产品隔离;将相关包移入所属产品组可明确随产品提供的支持。 + +## Consequences + +默认 profile 包含 Team 实现,但开启前不暴露任务工具。自定义组合必须迁移已移除的包名;持久事件名称与任务数据保持不变。[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md)负责具体步骤。 + +验证覆盖默认启动、新 Session 手动开启、独立根、选择持久化、任务保留、旧 profile 迁移和插件开关移除。产品隔离检查使用另一个无关实验性插件作为负对照。 diff --git a/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.i18n.yaml new file mode 100644 index 0000000000..23586315cb --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-21-schedule-rule-storage.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.md +/agent-note-schedule-rule-storage-and-shared-recurrence: + en: 34817514a06a4351 + zh: a9e33a1c4d5845d1 +/agent-note-schedule-rule-storage-and-shared-recurrence/problem: + en: 22eed4a004cbb1c5 + zh: dc7b6f8ed9c074cf +/agent-note-schedule-rule-storage-and-shared-recurrence/decision: + en: 50bfa3e81af7c2b0 + zh: e9bd5fae6e611030 +/agent-note-schedule-rule-storage-and-shared-recurrence/alternatives-considered: + en: fbfcd35c35fb637a + zh: df9dd646e6d18e3c +/agent-note-schedule-rule-storage-and-shared-recurrence/consequences: + en: 61213641597c18bb + zh: 393a79013e311311 diff --git a/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.md b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.md new file mode 100644 index 0000000000..2c62fcf258 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.md @@ -0,0 +1,25 @@ +# Agent Note: Schedule rule storage and shared recurrence + +Status: implemented + +English | [中文](2026-10-21-schedule-rule-storage.zh.md) + +## Problem + +Host tasks already use the versioned `schedule` domain. A second domain, importer, and placeholder RRULE duplicate timing and storage authority. Cron and RRULE should be supported timing types rather than separate generations of the task API. + +## Decision + +Use `schedule` version 2 with `compatibleVersions: [1]`, retaining its backend routing, envelope, and whole-unit layout. Extend the existing accepted-version policy to authoritative JSON and SQLite units; reads leave storage unchanged, and the next write commits the current stamp with its data. Add `rrule` to the six existing record kinds and evaluate every kind normally. Remove the standalone store importer, import marker, placeholder RRULE, and parallel Session-bound management API. Move reusable Cron and RRULE parsing and bounded occurrence arithmetic into `dsh-util-time`; Schedule owns records, targets, delivery admission, history, and errors. + +An explicit target wins. Without one, read an existing `sessionId` as a Session target; otherwise reserve a stable `new_once` target. Optional new metadata receives read defaults without rewriting storage. Every successful edit writes the current row format without `sessionId`. Custom timing accepts either RRULE or a five-field Cron expression with an explicit zone; UI labels name neither syntax. Model guidance continues to teach RRULE. + +This partially supersedes [standalone schedules](2026-09-17-standalone-schedules.md): its target, execution, notification, and Host-wide management decisions remain. It restores the domain and layout in [Host schedule storage](2026-09-16-host-schedule-storage.md), while replacing that note's Session-bound management API. Both notes remain active and link to this decision. + +## Alternatives considered + +Changing the domain or layout would require routing and copy logic without changing the feature. Converting Cron into RRULE can change day-of-month/day-of-week and time-zone semantics. A generic value migration engine is deferred until an incompatible storage version requires one; the existing domain envelope already identifies the version. + +## Consequences + +Missing creation metadata cannot recover historical timestamps. A default target must retain its reserved Session identity across reads and retries. Old receipts need their original destination retained before retargeting. A current unit stamp can contain older untouched rows, so future compatible readers must retain those defaults until a complete rewrite allows removal. Old binaries reject a newer stamp. Session inbox persistence and task acknowledgment remain separate commits, so delivery remains at least once. diff --git a/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.zh.md b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.zh.md new file mode 100644 index 0000000000..a9d68c3e56 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.zh.md @@ -0,0 +1,25 @@ +# Agent Note: 调度规则存储与共享重复时间计算 + +Status: implemented + +[English](2026-10-21-schedule-rule-storage.md) | 中文 + +## 问题 + +Host 任务已经使用带版本的 `schedule` 域。第二个域、导入器和占位 RRULE 会重复定义时间与存储的权威来源。Cron 和 RRULE 应当是并列的时间规则类型,而非两代任务 API。 + +## 决策 + +使用 `schedule` 版本 2 和 `compatibleVersions: [1]`,保留后端路由、封套和整单元布局。将现有接受版本策略扩展到权威 JSON 和 SQLite 单元;读取保持存储不变,下一次写入将当前版本戳与数据一同提交。在现有六种记录类型旁添加 `rrule`,所有类型均正常求值。移除独立存储的导入器、导入标记、占位 RRULE 和并行的 Session 绑定管理 API。将可复用的 Cron、RRULE 解析及有界时间计算移至 `dsh-util-time`;Schedule 负责记录、目标、投递准入、历史和领域错误。 + +显式目标优先。缺少目标时,将已有 `sessionId` 读取为 Session 目标;否则保留稳定的 `new_once` 目标。新增可选元数据使用读取默认值,不重写存储。每次成功编辑都写入不含 `sessionId` 的当前行格式。自定义时间同时接受 RRULE 和带显式时区的五字段 Cron 表达式;界面标签不提示任何语法名称。模型指引继续推荐 RRULE。 + +本决策部分替代[独立定时任务](2026-09-17-standalone-schedules.zh.md),保留其目标、执行、通知和宿主级管理决策。它恢复[宿主任务存储](2026-09-16-host-schedule-storage.zh.md)的领域与布局,并替代按 Session 绑定的管理 API。两个 note 保持活动并链接到本决策。 + +## 考虑过的替代方案 + +更换域或布局需要增加路由和复制逻辑,却不改变功能。将 Cron 转换为 RRULE 可能改变月内日期、星期和时区语义。通用值迁移引擎留待不兼容存储版本确有需要时再引入;现有域封套已经标识版本。 + +## 影响 + +缺失的创建元数据无法恢复历史时间戳。默认目标必须在读取和重试间保持预留 Session 标识。重新指定目标前,旧回执需要保留原始投递目标。当前单元版本戳可包含未改动的旧行,因此未来兼容读取器必须保留这些默认规则,直至完整重写后才能移除。旧程序拒绝更新的版本戳。Session 收件箱持久化与任务确认仍是两次独立提交,因此投递仍然至少一次。 diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml index 9ae0452069..575a8026c7 100644 --- a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.i18n.yaml @@ -12,8 +12,8 @@ en: 45c63df5dac389eb zh: d72a5bcb94de22f1 /agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/reads-and-subscriptions: - en: 38df4f3c4fba2cc9 - zh: a34f3376faf26f0c + en: a2439f02cb9654f9 + zh: 9de786792cba6a1d /agent-note-session-snapshots-passive-subscriptions-and-web-aggregation/decision/follow-ordering-and-ownership: en: 352ff87a3e9cd110 zh: 4ac6366cecfc08a3 diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md index b5e1112a18..98d632eda8 100644 --- a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.md @@ -18,7 +18,7 @@ History reads return chronological records, `hasMore`, and an inclusive cursor. `usingObservation({ sessionId, projection }, signal, callback?)` acquires the existing disposable SessionObservation. A callback borrows it until the callback settles; without a callback the caller owns disposal. Ordinary history, state, and Wait output reads do not request projections. Follow, exact projection reads, and subagent history descriptor validation request them. No read activates an Agent implicitly. -`observeEvent` and `observeProjections` install listeners without acquiring an Observation. Their initial `ready` confirms subscription, not a snapshot cursor, existence, parent-child validity, or Agent readiness. History establishes continuity from its first received event; projection updates replace individual keys and may share a sequence number. `observeState` instead begins with a complete state read and coalesces later Session and Agent invalidations. +`observeEvent` and `observeProjections` install listeners without acquiring an Observation. Their initial `ready` confirms subscription, not a snapshot cursor, existence, parent-child validity, or Agent readiness. History establishes continuity from its first received event; each projection change frame covers one committed event and replaces only the keys it lists. `observeState` instead begins with a complete state read and coalesces later Session and Agent invalidations. History, history observation, and Follow accept Address requests; projection and state operations accept Session IDs. All internal readers and listeners use Session IDs. History and Follow validate Address against their opening Observation at the Controller layer, including the existing subagent descriptor rules. Pure history observation does not acquire a read for entity validation. Gateway resource authorization remains independent: the registered Session resolver extracts the target ID from the request before access is decided. diff --git a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md index 773ab039b3..fa9d53c2d8 100644 --- a/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-21-session-history-stream-and-snapshot.zh.md @@ -18,7 +18,7 @@ Status: implemented `usingObservation({ sessionId, projection }, signal, callback?)` 获取已有的可释放 SessionObservation。有回调时租约借给回调直到其结束;无回调时由调用方释放。普通历史、状态及 Wait 输出读取不请求投影。Follow、精确投影读取和子会话历史 descriptor 校验请求投影。读取不会隐式激活 Agent。 -`observeEvent` 和 `observeProjections` 安装监听而不获取 Observation。首个 `ready` 确认订阅生效,不代表快照游标、实体存在、父子关系有效或 Agent 就绪。历史从首个收到的事件建立连续性;投影更新替换单个键,多个更新可以共享序号。`observeState` 则从完整状态读取开始,并合并后续 Session 和 Agent 失效通知。 +`observeEvent` 和 `observeProjections` 安装监听而不获取 Observation。首个 `ready` 确认订阅生效,不代表快照游标、实体存在、父子关系有效或 Agent 就绪。历史从首个收到的事件建立连续性;每个投影变更帧对应一个已提交事件,只替换帧内列出的键。`observeState` 则从完整状态读取开始,并合并后续 Session 和 Agent 失效通知。 历史、历史观察和 Follow 接收 Address 请求;投影和状态操作接收 Session ID。所有内部读取器和监听器都使用 Session ID。History 和 Follow 在 Controller 层以开场 Observation 校验 Address,包括已有的子会话 descriptor 规则。纯历史观察不为实体校验获取读取。Gateway 资源授权与之独立:注册的 Session 解析器在访问判定前从请求提取目标 ID。 diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.i18n.yaml new file mode 100644 index 0000000000..82eae5a35d --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-22-subagent-target-user-controls.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.md +/agent-note-user-controls-address-the-target-subagent: + en: d7dcf54ddb311881 + zh: 5f388447737c5414 +/agent-note-user-controls-address-the-target-subagent/problem: + en: 962c75771235903c + zh: 203b651c0830310e +/agent-note-user-controls-address-the-target-subagent/decision: + en: 13a2617e28445744 + zh: 75d193ef7d8c7804 +/agent-note-user-controls-address-the-target-subagent/alternatives-considered: + en: 447adb24280bf2bb + zh: 08d95a93b14aa5c7 +/agent-note-user-controls-address-the-target-subagent/consequences: + en: 98e784f55775247d + zh: 1c62d2ebc71b658f diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.md b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.md new file mode 100644 index 0000000000..064dbb1e17 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.md @@ -0,0 +1,33 @@ +# Agent Note: User controls address the target subagent + +Status: implemented + +English | [中文](2026-10-22-subagent-target-user-controls.zh.md) + +## Problem + +A browser knows the subagent it is displaying, but requiring its direct creator and a continuable marker makes every control caller repeat history metadata. A caller-supplied parent id checks address consistency without establishing the caller's identity or permission. Calls that resolve only the global access resource also cannot express a grant on one target Session. + +## Decision + +Browser prompts and `interruptByUser` address only the target child Session. Each Remote method explicitly declares that Session as its access resource; the Gateway checks the invocation's principal before attachment admission, restoration, or cancellation. A global or parent Session grant does not imply a child Session grant. Policies decide whether to grant both actions, either action, or inherited access. Same-process user interruption trusts its caller and does not accept a wire-supplied principal. + +Prompt delivery derives the live root from the resident Activation or verified persisted creation edges. Only the cold target resumes; its creator can remain offline. Shared delivery retains exact live root checks, shutdown admission, cancellation, capacity, and final inbox acceptance. A root Session is not a target of the browser subagent prompt endpoint. User interruption addresses a resident Activation without persistence reads or restoration; an absent target remains a no-op, and interruption preserves parked input. + +Model messages retain the exact live sender and same-tree rule from [tree-wide communication](2026-10-16-tree-wide-agent-communication.md). Model interruption retains its stricter ancestor rule. Creation parents still determine catalog edges, history-address consistency, ancestry, and completion recipients; they are not browser control credentials. + +This supersedes the direct-parent addressing requirement for human continuation in [continuable subagents](../feature/2026-07-28-continuable-subagent-conversations.md). That record retains its inbox and durable continuation rationale; tree-wide communication owns its superseded model adjacency and runtime ownership restrictions. No Session format changes. + +## Alternatives considered + +**Keep the parent check as authorization.** The client supplies the parent id and can obtain it from history. Matching that id does not authorize the principal, and requiring it couples controls to discovery metadata. + +**Require a root id from the browser.** The server already derives the runtime owner from the target. Another supplied id adds a consistency check without granting permission; Agent senders still need an independently resolved root to enforce same-tree messaging. + +**Unify user and Agent interruption permissions.** A user with a target grant can stop that target, while an Agent may stop only its descendants. Same-tree collaboration does not grant members control over each other's execution. + +## Consequences + +Remote callers update their prompt fields, interrupt endpoint, and non-owner policy actions and resources; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md) owns the migration. History URLs retain parent ids for consistency checks. Cold host prompts may read creation ancestry twice, once to find the live root and again during restoration; no verified-ancestry cache is retained across asynchronous work. + +Gateway tests cover target grants, global-only and parent-only refusal, separate send and interrupt actions, owner access, and refusal before side effects. Continuation tests cover nested and cold targets with online or offline creators, unavailable roots, and rejection of a root as a subagent target. The Web interrupt scenario exercises the renamed endpoint and parked-input behavior through the shipped composition. diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.zh.md b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.zh.md new file mode 100644 index 0000000000..455a511778 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-target-user-controls.zh.md @@ -0,0 +1,33 @@ +# Agent Note: 用户控制按目标子代理寻址 + +Status: implemented + +[English](2026-10-22-subagent-target-user-controls.md) | 中文 + +## 问题 + +浏览器知道当前展示的子代理,但要求提供直接创建者和 continuable 标记,使每个控制调用方都要重复历史元数据。调用方提供的父级 id 只能检查地址一致性,不能确定调用者身份或权限。仅解析出 global 访问资源的调用也无法表达对单个目标 Session 的授权。 + +## 决策 + +浏览器提示词和 `interruptByUser` 仅按目标子 Session 寻址。每个 Remote 方法显式声明该 Session 为访问资源;Gateway 在附件接纳、恢复或取消之前检查调用的 principal。global 或父 Session 授权不意味着子 Session 授权。策略决定授予两个操作、其中一个操作,或继承访问权。同进程用户中断信任其调用方,不接受从线上传入的 principal。 + +提示词投递从驻留 Activation 或经过验证的持久化创建关系中解析在线根。仅恢复冷目标,创建者可以保持离线。共享投递保留精确在线根检查、关闭准入、取消、容量和最终 inbox 接纳。根 Session 不是浏览器子代理提示词端点的目标。用户中断直接寻址驻留 Activation,不读取持久化数据,也不恢复目标;目标缺席仍为无操作,中断保留停放的输入。 + +模型消息保留[整树通信](2026-10-16-tree-wide-agent-communication.zh.md)中的精确在线发送者和同树规则。模型中断保留更严格的祖先规则。创建父级仍决定目录关系、历史地址一致性、祖先关系和完成通知接收者;它们不是浏览器控制凭证。 + +本决策取代[可继续的 subagent](../feature/2026-07-28-continuable-subagent-conversations.zh.md)对人工继续执行要求直接父级地址的部分。旧记录保留 inbox 和持久化继续执行的理由;整树通信决策拥有其中已取代的模型相邻关系和运行时所有权限制。Session 格式不变。 + +## 考虑过的替代方案 + +**保留父级检查作为授权。** 客户端提供父级 id,也能从历史中取得它。匹配该 id 不能授权 principal,还使控制依赖于发现元数据。 + +**要求浏览器提供根 id。** 服务端已经能从目标解析运行时所有者。再提供一个 id 只会增加一致性检查,不会授予权限;Agent 发送者仍需要独立解析的根来约束同树消息。 + +**统一用户和 Agent 的中断权限。** 用户获得目标授权后可以停止该目标,而 Agent 只能停止自己的后代。同树协作不赋予成员控制彼此执行的权限。 + +## 影响 + +Remote 调用方需要更新提示词字段、中断端点,以及非 owner 策略的操作和资源;迁移步骤由[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.zh.md)拥有。历史 URL 保留父级 id 用于一致性检查。冷目标的宿主提示词可能读取两次创建祖先:先查找在线根,再在恢复期间验证;不跨异步操作保留已验证祖先缓存。 + +Gateway 测试覆盖目标授权、仅 global 和仅父级授权的拒绝、独立的发送和中断操作、owner 访问,以及副作用前拒绝。继续执行测试覆盖创建者在线或离线时的嵌套和冷目标、根不可用,以及拒绝把根当作子代理目标。Web 中断场景通过交付组合验证重命名后的端点和输入停放行为。 diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.i18n.yaml new file mode 100644 index 0000000000..81682a6981 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-22-subagent-tool-owned-communication.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.md +/agent-note-subagent-tools-own-communication-guidance: + en: 0bd031aa81fbc18d + zh: c530e980826698ed +/agent-note-subagent-tools-own-communication-guidance/problem: + en: ac391b569d2bc7e9 + zh: a95f613aa2b330b8 +/agent-note-subagent-tools-own-communication-guidance/decision: + en: 52fb33963bedfe07 + zh: 75fe66d80f47323f +/agent-note-subagent-tools-own-communication-guidance/alternatives-considered: + en: c55d44c6414e0c4c + zh: 9fa2ab31843e259b +/agent-note-subagent-tools-own-communication-guidance/consequences: + en: 52f7234664c515ec + zh: 55ec7b54c044e9af diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.md b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.md new file mode 100644 index 0000000000..2222cd5dd7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.md @@ -0,0 +1,27 @@ +# Agent Note: Subagent tools own communication guidance + +Status: implemented + +English | [中文](2026-10-22-subagent-tool-owned-communication.zh.md) + +## Problem + +The continuation manager inspected a Symbol on the standard messaging tool before adding tool instructions and parent addressing to the initial task. This coupled orchestration to one tool implementation and made result-delivery guidance depend on tool installation. A published internal entry point carried both that marker and a host prompt adapter used only by tests. + +## Decision + +`tool-subagent-control` owns messaging instructions and parent addressing. Its logged runtime context gives delegated children their direct creator’s id from the Session header, explains when to send findings, and states that sending does not finish a turn. The context is emitted only for delegated children when the plugin’s own tool definition is admitted in the current scope and step; roots and ordinary Session forks receive none. Communication guidance follows inherited history without changing the shared system prompt or tool schema. + +The manager owns result delivery. Local activations with `delivery: 'parent'` receive automatic-result guidance even without messaging tools; caller-owned activations receive no parent-delivery promise. Settlement timing, recipients, output, and suppression of closing text after a final message to the parent remain unchanged. Tool visibility grants no messaging authority. + +This supersedes the Symbol identity and initial-task communication-guidance choices in [adjacent messaging](2026-08-27-adjacent-agent-steer-messaging.md). Its message attribution, fixed Steer delivery, and rejection of a separate report operation remain active. The internal entry point and prompt adapter are removed; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md) owns caller migration. + +## Alternatives considered + +**Keep a cross-package marker or add a service hook.** Tool registration already gives its owner the exact definition, and prompt assembly already supplies the current Agent. Another protocol or stored identity has no independent consumer. + +**Move all return guidance into the tool.** Automatic parent notification depends on activation delivery, not on messaging capability. The tool must not promise it to caller-owned activations or withhold it from children without tools. + +## Consequences + +Tests cover visible, hidden and replaced definitions, logged identity, plugin disposal, fork prefix reuse, and parent versus caller result delivery. Recorded-session snapshots cover the assembled prompt and durable runtime context. Tests needing host input use the existing private manager test helper; no production adapter exists solely to expose that helper. diff --git a/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.zh.md b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.zh.md new file mode 100644 index 0000000000..21242507b7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-22-subagent-tool-owned-communication.zh.md @@ -0,0 +1,27 @@ +# Agent Note: Subagent 工具拥有通信指导 + +Status: implemented + +[English](2026-10-22-subagent-tool-owned-communication.md) | 中文 + +## 问题 + +继续执行管理器检查标准通信工具上的 Symbol,随后在初始任务中加入工具说明和父级地址。这让编排依赖一个工具实现,也让结果交付指导取决于是否安装工具。已发布的内部入口同时承载该标记和仅供测试使用的宿主 prompt 适配器。 + +## 决策 + +`tool-subagent-control` 拥有通信说明和父级寻址。持久记录的运行时上下文从 Session header 读取委派子级的直接创建者 id,说明何时发送发现,并指出发送不会结束轮次。仅当本插件的工具定义在当前作用域和 step 中可用时,才向委派子级提供上下文;根代理和普通 Session fork 不接收。通信指导位于继承历史之后,不改变共享系统提示词或工具 schema。 + +管理器拥有结果交付。采用 `delivery: 'parent'` 的本地 activation 即使没有通信工具,也会收到自动结果交付指导;调用方拥有的 activation 不会收到父级交付承诺。结算时序、接收方、输出,以及最后向父级发送消息后省略结束文本的规则保持不变。工具可见性不授予通信权限。 + +本决策取代[相邻代理通信](2026-08-27-adjacent-agent-steer-messaging.zh.md)中的 Symbol 身份和初始任务通信指导选择。该记录的消息来源归属、固定 Steer 投递,以及不另设 report 操作的决策继续有效。内部入口和 prompt 适配器已删除;调用方迁移由[升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.zh.md)说明。 + +## 考虑过的替代方案 + +**保留跨包标记或增加 service hook。** 工具注册已经向所有者提供确切定义,提示词组装也已提供当前 Agent。另一套协议或身份存储没有独立消费者。 + +**把全部返回指导移入工具。** 自动父级通知取决于 activation 的交付方式,而非通信能力。工具不能向调用方拥有的 activation 承诺自动通知,也不能让没有工具的子级缺少交付说明。 + +## 后果 + +测试覆盖可见、隐藏及替换的定义、持久记录的身份、插件释放、fork 前缀复用,以及父级与调用方结果交付。录制会话快照覆盖组装后的提示词和持久运行时上下文。需要宿主输入的测试使用现有的私有 manager 测试帮助函数;生产代码不再仅为暴露该帮助函数而保留适配器。 diff --git a/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.i18n.yaml new file mode 100644 index 0000000000..42e6d43425 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-30-cli-account-host-registry.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.md +/agent-note-host-registry-for-cli-app-accounts: + en: a2c6e955d6277d11 + zh: 3be00f1c59fb5bfa +/agent-note-host-registry-for-cli-app-accounts/problem: + en: 142a32f4631867dc + zh: a5b679997d71be10 +/agent-note-host-registry-for-cli-app-accounts/decision: + en: 512b112f0a4bbdb6 + zh: 57186e4ae712848d +/agent-note-host-registry-for-cli-app-accounts/alternatives-considered: + en: 5a4f9e1a637d8458 + zh: 20feb3570a3b435e +/agent-note-host-registry-for-cli-app-accounts/consequences: + en: 5dd503c56a97139a + zh: 0c5478c7bad8283b diff --git a/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.md b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.md new file mode 100644 index 0000000000..72e2c96a59 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.md @@ -0,0 +1,29 @@ +# Agent Note: Host registry for CLI app accounts + +Status: implemented + +English | [中文](2026-10-30-cli-account-host-registry.zh.md) + +## Problem + +CLI app plugins such as Feishu, WeCom, DingTalk, and Tencent Meeting show the account their vendor CLI keeps on the Plugins page: a section with status and buttons, a title tag, an activation prompt, confirmations, and notices. Each plugin's account runtime already runs on the Host, and every plugin needs the same surfaces. Registering each account in the browser makes each plugin ship a browser package with its own account Remote, stream, presentation, and dictionary, although that package knows nothing the Host does not. + +## Decision + +The Host service `ctx.cliAccounts` in [`@deepseek-ai/dsh-client-ui-cli-account`](../../../../packages/client/ui-cli-account/README.md) holds the accounts. An app plugin's Host row registers its `CliAccountRuntime` as the source, the operations a page button may start with their success text, the copy, and a presenter that maps the account view to a display whose text is `LocalizedText`. It registers inside `ctx.inject(['cliAccounts'], …)`, so a profile without the registry, such as headless, loads the plugin without the page. The Web app composition loads the registry. + +The registry serves every account through one `cliAccounts` Remote: `watch` streams every account's entry, and `start` and `cancel` route by package and accept only registered operations. One browser half renders the surfaces of every account and keeps the state that belongs to one browser: it opens an authorization link only in the browser that started the operation, reports notices only there, and ignores clicks while its own action is pending. The copy every account shares lives in the kit dictionary; every other string comes from the plugin as `LocalizedText`, which the browser resolves in its active language. + +## Alternatives considered + +**Browser registration.** Each plugin's browser half registers with a browser `ctx.cliAccounts` and follows its own account Remote. That needs one browser package and one Remote per plugin, and the browser half only restates what the Host knows. Listing the kit in `PLATFORM_MODULES`, so that those packages can import it at run time, makes a feature package part of the shell baseline. + +**Presentation in the browser.** The Host could stream the raw account view and a browser presenter per plugin could map it. That keeps one browser package per plugin. Producing `LocalizedText` on the Host keeps each plugin's text in its Host row, and the browser still resolves the language without a Host round trip. + +**Per-browser state on the Host.** Publishing links and notices to every browser would open the authorization link in every open window and report one user's action to all of them. Keeping that state in the browser opens a link only where the user asked for it and reports an outcome only to that browser. + +## Consequences + +A CLI app plugin ships no browser code for its account and serves no account Remote; its Host row registers the account and the kit renders it. Each browser opens one stream for all accounts when the Web app loads, and the Host checks each idle account for every new stream. A plugin whose Host row fails to load shows no account section, while the Plugins page still lists the bundle with its load failure. The display vocabulary is fixed at five phases, buttons whose command is `start`, `cancel`, or `open`, notes, and a failure with classified diagnostics; a plugin that needs another control extends the kit. + +Host specs pin registration, the check for each new stream, coalescing, operation routing, and unload. Client specs pin link opening in the starting browser, notices, the pending-action guard, and each account's slot registrations and their removal. diff --git a/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.zh.md b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.zh.md new file mode 100644 index 0000000000..b98948072f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-10-30-cli-account-host-registry.zh.md @@ -0,0 +1,29 @@ +# Agent Note: CLI 应用账号的 Host 注册表 + +Status: implemented + +[English](2026-10-30-cli-account-host-registry.md) | 中文 + +## Problem + +飞书、企业微信、钉钉和腾讯会议等 CLI 应用插件在插件页显示其厂商 CLI 保存的账号:带状态和按钮的区块、标题旁标签、开启引导、确认和提示。每个插件的账号运行时本来就在 Host 上运行,而每个插件需要的界面都一样。如果在浏览器中注册账号,每个插件都要提供一个浏览器包,带着自己的账号 Remote、流、展示推导和字典,尽管这个包知道的内容 Host 全都知道。 + +## Decision + +[`@deepseek-ai/dsh-client-ui-cli-account`](../../../../packages/client/ui-cli-account/README.zh.md) 中的 Host 服务 `ctx.cliAccounts` 保存这些账号。应用插件的 Host 行注册其 `CliAccountRuntime` 作为来源,以及页面按钮可以启动的操作及其成功文本、文案,和把账号视图映射为 display 的展示函数,display 中的文本为 `LocalizedText`。它在 `ctx.inject(['cliAccounts'], …)` 内注册,因此没有注册表的 profile(如 headless)加载插件时不带页面。Web 应用组合加载注册表。 + +注册表通过一个 `cliAccounts` Remote 提供所有账号:`watch` 流式推送每个账号的条目,`start` 和 `cancel` 按包路由,并且只接受已注册的操作。一个浏览器一半渲染所有账号的界面,并保存属于单个浏览器的状态:只在发起操作的浏览器中打开授权链接,只在那里报告提示,并在自己的操作未完成时忽略点击。所有账号共用的文案位于套件字典;其余文案都以 `LocalizedText` 的形式来自插件,由浏览器按当前语言解析。 + +## Alternatives considered + +**在浏览器中注册。** 每个插件的浏览器一半向浏览器中的 `ctx.cliAccounts` 注册,并跟随自己的账号 Remote。这需要每个插件各有一个浏览器包和一个 Remote,而浏览器一半只是重复 Host 已经知道的内容。把套件列入 `PLATFORM_MODULES`,让这些包能在运行时导入它,会使一个功能包成为 shell 基线的一部分。 + +**在浏览器中推导展示。** Host 可以流式推送原始账号视图,由每个插件的浏览器展示函数映射。这仍然需要每个插件一个浏览器包。在 Host 上生成 `LocalizedText` 让每个插件的文本留在其 Host 行中,浏览器仍可在不往返 Host 的情况下解析语言。 + +**把单个浏览器的状态放到 Host 上。** 把链接和提示发布给所有浏览器,会在每个打开的窗口中打开授权链接,并把一个用户的操作报告给所有窗口。把这些状态留在浏览器中,链接只在用户要求的地方打开,结果也只报告给该浏览器。 + +## Consequences + +CLI 应用插件不为账号提供浏览器代码,也不提供账号 Remote;其 Host 行注册账号,由套件渲染。每个浏览器在 Web 应用加载时为所有账号打开一条流,Host 为每条新流检查每个空闲账号。Host 行加载失败的插件不显示账号区块,插件页仍会列出该插件包及其加载失败。显示词汇是固定的:五个阶段、命令为 `start`、`cancel` 或 `open` 的按钮、附加行,以及带分类诊断的失败信息;需要其他控件的插件要扩展套件。 + +Host 测试固定注册、每条新流触发的检查、变化合并、操作路由和卸载。客户端测试固定在发起操作的浏览器中打开链接、提示、未完成操作保护,以及每个账号的插槽注册及其移除。 diff --git a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.i18n.yaml b/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.i18n.yaml deleted file mode 100644 index e17980cb32..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.i18n.yaml +++ /dev/null @@ -1,22 +0,0 @@ -# Bilingual-pair consistency record for 2026-09-17-multiline-display-dollar-math.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.md -/agent-note-multi-line-display-dollar-math: - en: 8f57c77aa43fbd6c - zh: ef5192184e4923d5 -/agent-note-multi-line-display-dollar-math/problem: - en: e4b73644a982844c - zh: 48f86358242d6ccc -/agent-note-multi-line-display-dollar-math/decision: - en: d6b136b1f62285b7 - zh: aba323bfdb800162 -/agent-note-multi-line-display-dollar-math/alternatives-considered: - en: e0833b5674e648e7 - zh: b0472020b07099b9 -/agent-note-multi-line-display-dollar-math/consequences: - en: 70f16597bd640e93 - zh: 0e0c9005f331e514 -/agent-note-multi-line-display-dollar-math/testing: - en: f17a1453df91ce88 - zh: 4f15be0139e8b694 diff --git a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.md b/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.md deleted file mode 100644 index 0362895314..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.md +++ /dev/null @@ -1,66 +0,0 @@ -# Agent Note: Multi-line display-dollar math - -Status: implemented - -English | [中文](2026-09-17-multiline-display-dollar-math.zh.md) - -## Problem - -Authors and models write `$$` display math in three shapes. The settled grammar rendered two of them: `$$math$$` on one line, and an opening `$$` alone on its line closed by `$$` alone on its line. The third shape — math on the opening line, a closing `$$` at the end of the last math line — did not: - -```markdown -$$f(x)=x -\text{continued}$$ -``` - -`micromark-extension-math` treats text after an opening `$$` as fence meta and accepts a closing fence only on a line whose content is exactly `$$` (after optional whitespace). The [markdown compatibility layer](../../archived/feature/2026-07-23-web-assistant-markdown.md) claimed only the same-line shape, and the settled renderer passes `node.value` to KaTeX while ignoring `node.meta`. The block therefore never closed: it consumed the document text that followed, `value` retained the literal `$$`, KaTeX raised `Can't use function '$' in math mode`, and [katex.tsx](../../../../packages/client/ui-primitives/src/markdown/katex.tsx)'s error arm painted the TeX source plus the swallowed prose in red. - -In the session that surfaced this, one chat reply lost lines 22–55 of 55 to a single error span, and six note files lost every line after such a block (up to 500 lines) to one. A second defect shared the mechanism: when a later lone `$$` did close the flow, the opening line had already been assigned to `meta`, so the renderer silently dropped the first line of the formula. - -## Decision - -[mathCompatibility.ts](../../../../packages/client/ui-primitives/src/markdown/mathCompatibility.ts) gains multi-line display-dollar blocks. Its dollar construct keeps the opening line's text in `mathFlowValue` instead of fence meta and closes at a trailing `$$` on any later content line, so `$$a+b` continued by `c+d$$` becomes one math node. - -A `$$` sequence that fails to close ends the candidate: immediately on a later line, and at that line's ending on the opening line (`$$x$$ trailing` fails there). Within the opening line the scan continues, so a later `$$` there still closes (`$$\verb*a$$a$$`). Scanning past either point would consume a later block's closing fence. A solitary `$` is content rather than a failed fence, so a formula that uses one — `$$P = \begin{cases} 1 & \text{if $x>0$} \end{cases}$$` — keeps the block open and closes normally wherever this flow owns the block. A trailing backslash escapes the line ending, not the next line's first character, so the escape run ends at the line ending instead of reaching into the next candidate. An unescaped `%` starts a TeX comment that runs to the line ending, so a `$$` at the end of a later line closes nothing when the comment holds text before it. A `%` whose text before the fence is empty or whitespace (`95%$$`, `95 %$$`) holds no comment text, and a block that opens and closes on one line keeps closing at that line's `$$`, as it did before this flow spanned lines. That state and its gate on the closing check belong to the dollar flow. The characters right after `\verb` or `\verb*` are that command's delimiter rather than a fence, so the delimiter and, when the region is empty, the `$` closing it are content; that tail is cleared at a line ending and after an escaped backslash (`\\verb` is a line break followed by letters), and a comment holds no commands. Otherwise verbatim regions are not parsed, which keeps `\verb`-bearing formulas on the same value path as every other input. - -Its paragraph-interruption check declines instead of consuming the line ending, for the dollar construct only. Consuming it there keeps the paragraph open across the line boundary, so the document layer keeps the container and counts the next line lazy for every construct tried afterwards; that made upstream's `mathFlow`, the construct tried after this one, end empty inside a list item. Declining also leaves the interruption decision to that upstream flow, whose own check short-circuits without consuming and claims only the fences it accepts, so a candidate neither construct accepts (`**before` followed by `$$a\$b`) leaves its paragraph intact. The backslash construct has no competing upstream construct and keeps consuming there. - -[parse.ts](../../../../packages/client/ui-primitives/src/markdown/parse.ts) registers `mathCompatibility()` after `math()`: micromark dispatches the extension registered last first, so the dollar flow above takes precedence over upstream's `mathFlow` while `math()` still owns inline `$…$`. - -## Alternatives considered - -**Keep the compatibility layer at same-line `$$…$$`.** The multi-line shape is what GitHub, KaTeX's auto-render, VS Code, and Typora accept, and the form models emit for multi-case formulas; leaving it unparsed means a red error span in place of the formula plus the rest of the document. - -**Repair the parsed tree afterwards.** The flow consumes the swallowed text into `mathFlowValue`, where it is indistinguishable from math source; `meta` and `value` cannot be reassembled into the intended block, and the following blocks were never parsed at all. - -**Rewrite `$$` fences in the source text before parsing.** The compatibility layer is a grammar extension by design; a text pass would need to locate code spans, fences, and escapes itself, and would change author text rather than parse it. - -**Continue the dollar flow after a failed close.** That is what a plain `multiline` flag produces: `$$x$$ trailing\n\n$$y$$` then scans to the second block's `$$` and renders one math node holding both lines' text, where upstream inline math renders `x`, the prose, and `y` separately. Existing behavior for `$$x$$ trailing` already pinned the fallback, so the flow declines the candidate instead. Declining on any `$` rather than a full `$$` sequence also broke formulas that use a solitary `$` inside `\text{}`. - -**End the attempt as soon as one line resists parsing.** Declining every failed same-line close swallows nothing but turns `$$a$b` lines into a quadratic scan and drops the solitary-`$` formulas above. The condition is the full `$$` sequence, not the character. - -**Claim the paragraph interruption in the check.** Returning success there, as upstream's flow does for the fences it accepts, prevents the lazy bookkeeping that broke the list case, but it also ends the paragraph for candidates that later fail (`**before\n$$a\$b\nafter**` split in two and exposed its `**`). Declining instead lets upstream's own check decide. - -**Apply the interruption guard to the backslash construct too.** The guard exists to protect the construct tried after this one; `\[`/`\(` have no second construct, and an unconditional guard dropped their multi-line blocks (`Prose line` followed by `\[`). - -## Consequences - -The three shapes now produce the same math node, so formulas stop truncating at the opening line and stop swallowing the prose after them. `$$` fence meta is no longer honored: `$$asciimath$$` parses as a formula whose value is `asciimath`, which upstream's flow treats as fence meta and drops. That spelling has no user in this repository, and the renderer never read `meta` anyway. - -Six inputs still reach upstream's flow or stay in the surrounding paragraph, because the compatibility flow declines them. Trailing text after a closing `$$` (`$$x$$ trailing`, or a CJK quote mark closing a line of prose) resolves through upstream inline math, as the existing `markdown.client.spec.tsx` case pins — including when a later `$$` block follows. A `$$` sequence the line does not end after declines the block: immediately on a later line, and at that line's ending on the opening line. A `$$` block left open runs to the next lone `$$` or to EOF exactly as it did before this change, because the upstream flow closes at EOF. - -The fourth is a multi-line block whose opening line carries a solitary `$` and that must interrupt a paragraph, with no blank line before it. Both flows decline the interruption there — this one by design, upstream because its fence meta stops at the `$` — so the block stays inside the paragraph and renders as inline math or not at all. Separating the block from the paragraph with a blank line makes this flow own it and render the display block. - -The fifth follows from the comment gate: a block whose only closing fence sits behind a comment that holds text keeps scanning instead of closing there, so when nothing else closes it the block reaches the upstream flow as the shapes above do. A fence behind a whitespace-only comment closes the block there, which leaves a following lone `$$` as its own empty block where the flow it replaced kept one node. - -The sixth is a multi-line block inside a container whose continuation line falls back to the container's indentation. `- Define:` followed by `$$f(x)=x` at the item's indentation and then a de-indented continuation line gives upstream's flow a fence meta and no value, so the reader sees an empty display block and the continuation as prose — the opening line is gone. Keeping the continuation at the same indentation, or moving the block out of the list, renders it normally. Both flow behaviors match the grammar this replaced; only the multi-line blocks this flow owns are new. - -One further limitation is not a fallback: the flow reads the six characters before a fence and does not parse verbatim regions, so a fence inside an unterminated region (`\verb|$$`) closes the block there, and a region whose text ends in `\verb` (`\verb**\verb*$$`) has its fence read as that text's delimiter. The six characters before either fence are locally identical, so no rule that reads only that tail separates them. - -Repeated unclosed candidates keep linear parser work: an open candidate declines at the next line that starts with a full `$$` it cannot close, rather than scanning each candidate to EOF, which would make 9.6 KB of `$$a$b` lines take ~4 s instead of ~16 ms. KaTeX-level failures in a formula's own source, such as `\arccot`, remain errors by design. - -## Testing - -`packages/client/ui-primitives/tests/markdown.client.spec.tsx` adds the multi-line case — opening-line math closed on a content line, closed by a lone fence, after a paragraph, inside a list item, and at column zero after a list item — and that case fails without the change. The same file also pins a multi-line formula that uses a solitary `$`, which like the case above renders only with this change. Further cases pin one condition each: a trailing-text candidate ahead of a later block (the flow must decline a full `$$` the line does not end after), a solitary `$` inside a single-line display formula (the flow must not decline on a single `$`), an escaped-dollar candidate that leaves its paragraph intact (the interruption check must not claim the paragraph), an unclosed `\[` candidate that leaves its paragraph intact (the guard must not apply to the backslash construct), a candidate ending in an odd backslash (the escape run must end at the line ending), a closing fence inside a TeX comment, a `%` the fence follows immediately or after whitespace, a second `%` inside an open comment, a `%` inside `\verb|…|`, the delimiter right after `\verb` and `\verb*` together with its empty region, an escaped backslash before `verb`, a verb tail that crosses no line ending, a comment ending in `verb`, a later-line trailing fence whose following prose upstream takes, a failed fence inside a comment, and bounded-work cases for repeated candidates with that backslash, without it, and ending in a verb tail. - -The DOM compatibility corpus adds `math-multiline-display` with its `.settled.txt` and `.streaming.txt` fixtures, which also pin that a column-zero `$$` after a list item stays outside the list item. `apps/web/tests/math-rendering.e2e.ts` renders the multi-line shape in the browser lane. diff --git a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.zh.md b/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.zh.md deleted file mode 100644 index ed0ef3f46a..0000000000 --- a/.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.zh.md +++ /dev/null @@ -1,66 +0,0 @@ -# Agent Note: Multi-line display-dollar math - -Status: implemented - -[English](2026-09-17-multiline-display-dollar-math.md) | 中文 - -## Problem - -作者和模型写 `$$` 行间公式时有三种写法。定稿语法只渲染其中两种:一行内开闭的 `$$math$$`,以及 `$$` 独占一行、由独占一行的 `$$` 闭合。第三种——开围栏同一行就带公式内容,闭合 `$$` 落在最后一行公式行行尾——不渲染: - -```markdown -$$f(x)=x -\text{continued}$$ -``` - -`micromark-extension-math` 把开围栏 `$$` 之后的同一行文本当作围栏 meta,并且只接受内容恰为 `$$`(后接可选空白)的行作为闭合围栏。[markdown 兼容层](../../archived/feature/2026-07-23-web-assistant-markdown.md)只认同一行开闭这一种形状,而定稿渲染器把 `node.value` 交给 KaTeX,不读 `node.meta`。于是该块始终不闭合:它吞掉后续正文,`value` 里残留字面 `$$`,KaTeX 抛出 `Can't use function '$' in math mode`,[katex.tsx](../../../../packages/client/ui-primitives/src/markdown/katex.tsx) 的错误分支把 TeX 原文连同被吞掉的正文一起显示为红色。 - -在暴露该问题的会话中,一条聊天回复 55 行里有 34 行(第 22–55 行)变成同一个错误块,六个笔记文件从出错点起的所有行(最多约 500 行)同样变成一个错误块。同一机制还带出第二个缺陷:当更靠后的独占行 `$$` 恰好闭合了这个流时,开围栏那一行已经归给 `meta`,渲染器于是静默丢掉公式的第一行。 - -## Decision - -[mathCompatibility.ts](../../../../packages/client/ui-primitives/src/markdown/mathCompatibility.ts) 现在支持跨行的显示美元块。dollar 构造把开围栏同一行的文本留在 `mathFlowValue` 里而不是当作围栏 meta,并在后续任意内容行行尾的 `$$` 处闭合,于是 `$$a+b` 接 `c+d$$` 成为一个 math 节点。 - -闭合失败的 `$$` 序列会结束该候选:出现在后续行时立即结束;出现在开围栏行时在该行行尾结束(`$$x$$ trailing` 即在此放弃)。在开围栏行内扫描继续,因此同一行更靠后的 `$$` 仍能闭合(`$$\verb*a$$a$$`)。越过这两点继续扫描都会吞掉更靠后一个块的闭合围栏。孤立的一个 `$` 属于公式内容而不是失败的围栏,所以凡是本 flow 拥有该块的场合,用到它的公式——`$$P = \begin{cases} 1 & \text{if $x>0$} \end{cases}$$`——保持块打开并正常闭合。行尾反斜杠转义的是换行本身,不是下一行的第一个字符,因此转义状态在换行处结束,不会延续到下一个候选。未转义的 `%` 会开启延续到行尾的 TeX 注释:当注释在围栏之前还有文本时,块后续行行尾的 `$$` 不闭合任何东西;而围栏之前只有空白或什么都没有的 `%`(`95%$$`、`95 %$$`)不含注释文本,且在一行内开闭的块仍在该行的 `$$` 处闭合,与它跨行之前的行为一致。该状态及其对闭合判定的门控属于 dollar flow。`\verb` 或 `\verb*` 之后的那个字符是该命令的分隔符而不是围栏,因此该分隔符、以及区域为空时紧随其后的那个 `$` 都属于内容;这段尾部状态在换行处、以及在被转义的反斜杠之后清空(`\\verb` 是换行加字母,不是该命令),注释里也不识别命令。除此之外不解析原样文本区域,使含 `\verb` 的公式与其它输入走同一条 value 路径。 - -它的段落打断检查改为「不认领」,且只作用于 dollar 构造。在那里消耗换行会让段落跨行边界保持打开,document 层因此保留容器并把下一行对随后尝试的所有构造计为 lazy;这正是上游 `mathFlow`(本构造之后被尝试的构造)在列表项内以空块结束的原因。不认领同时把打断决定交给上游 flow:它自己的检查不消耗换行就短路返回,并且只认领它接受的围栏,因此两个构造都不接受的候选(`**before` 后接 `$$a\$b`)保持原段落。反斜杠构造没有竞争的上游构造,仍然照旧消耗换行。 - -[parse.ts](../../../../packages/client/ui-primitives/src/markdown/parse.ts) 把 `mathCompatibility()` 注册在 `math()` 之后:micromark 先派发最后注册的扩展,上面的 dollar flow 因此优先于上游 `mathFlow`,而行内 `$…$` 仍由 `math()` 负责。 - -## Alternatives considered - -**兼容层维持只处理同一行 `$$…$$`。** 多行写法是 GitHub、KaTeX auto-render、VS Code、Typora 都接受的形状,也是模型写多分支公式时实际采用的形状;不解析它意味着公式位置显示为红色错误块,并连带吞掉后文。 - -**解析后修补语法树。** 被吞掉的正文已经进入 `mathFlowValue`,与数学源码无法区分;`meta` 和 `value` 无法还原成原意的块,而且后面的块根本没有被解析。 - -**解析前用文本替换改写 `$$` 围栏。** 兼容层的设计就是语法扩展;文本替换需要自己定位代码 span、围栏和转义,而且改的是作者原文而不是解析它。 - -**闭合失败后继续扫描。** 这正是单纯打开 `multiline` 会得到的行为:`$$x$$ trailing\n\n$$y$$` 会一路扫到第二个块的 `$$`,渲染成一个同时含着两行文本的 math 节点;而上游行内数学会把 `x`、正文和 `y` 分开渲染。`$$x$$ trailing` 的既有行为已经固定了这条回退,因此该构造放弃这个候选。对任意一个 `$`(而不是完整的 `$$` 序列)就放弃,还会破坏在 `\text{}` 内使用单个 `$` 的公式。 - -**只要有一行解析不下去就结束尝试。** 对每次同一行闭合失败都放弃虽然不再吞文,却会让 `$$a$b` 这类行变成平方级扫描,并丢掉上面那些含单个 `$` 的公式。判据是完整的 `$$` 序列,不是那个字符。 - -**在检查阶段认领段落打断。** 像上游 flow 那样返回成功可以避免破坏列表用例的 lazy 记账,但也会让最终失败的候选提前结束段落(`**before\n$$a\$b\nafter**` 被拆成两段并暴露 `**`)。改为不认领,把决定交给上游自己的检查。 - -**把打断守卫也用在反斜杠构造上。** 这个守卫是为了保护随后被尝试的构造;`\[`/`\(` 没有第二个构造,无条件套用会丢掉它们的跨行块(`Prose line` 后接 `\[`)。 - -## Consequences - -三种写法现在产生同一个 math 节点,公式不再在开围栏那一行被截断,也不再吞掉其后的正文。`$$` 围栏 meta 不再生效:`$$asciimath$$` 会解析成 value 为 `asciimath` 的公式,而上游 flow 会把该段当作 fence meta 丢弃。这种写法在本仓库没有使用者,且渲染器本来就从不读 `meta`。 - -有六种输入仍会走到上游 flow,或留在所属段落里,因为兼容 flow 主动放弃它们。闭合 `$$` 之后还有文本时(`$$x$$ trailing`,或用中文引号收尾的散文行)走上游行内数学,这一点由 `markdown.client.spec.tsx` 中已有用例固定,后面还有别的 `$$` 块时同样如此。「后面不是行尾」的 `$$` 序列会让块放弃:出现在后续行时立即放弃,出现在开围栏行时在该行行尾放弃。未闭合的 `$$` 块仍像本次改动之前那样延伸到下一个独占行 `$$` 或文件结尾,因为上游 flow 在 EOF 处闭合。 - -第四种是「开围栏行含孤立 `$`、且需要打断段落、前面又没有空行」的多行块。两个 flow 都不认领这次打断——本 flow 出于设计,上游则因为它的围栏 meta 在 `$` 处即停止——该块因此留在段落里,渲染成行内数学或根本不渲染。用空行把块与段落分开,本 flow 就会拥有它并渲染 display。 - -第五种来自注释门控:当块唯一的闭合围栏位于「带文本的注释」之后时,块继续扫描而不是在那里闭合,若再没有别的围栏闭合它,就会像上面几种一样走到上游 flow。若围栏之前只有空白,则块在该处闭合,此后单独一行的 `$$` 会成为它自己的空块——而被替换掉的语法那时只给出一个节点。 - -第六种是容器内续行退回容器缩进的多行块。`- Define:` 之后以列表项缩进写 `$$f(x)=x`,再接一行不缩进的续行,上游 flow 会得到有 meta、无 value 的结果:读者看到一个空的 display 块加一行散文,公式首行无声消失。续行保持同样缩进,或把整块移到列表之外,即可正常渲染。这两种 flow 行为都与本次替换掉的语法一致;真正新增的只是「本 flow 拥有的多行块」。 - -另有一项不属于回退的限制:flow 只读取围栏之前的六个字符、不解析原样文本区域,因此未闭合区域内部的围栏(`\verb|$$`)会在那里闭合块,而内容以文本 `\verb` 结尾的区域(`\verb**\verb*$$`)其围栏会被读成该文本的分隔符。两种情况下围栏前的六个字符在局部完全相同,仅凭这段尾部无法区分。 - -重复的未闭合候选保持线性解析开销:未闭合的候选会在下一行遇到无法闭合的完整 `$$` 时放弃,而不是把每个候选都扫到 EOF——否则 9.6 KB 的 `$$a$b` 行会花约 4 秒而不是约 16 毫秒。公式自身源码层面的 KaTeX 失败,例如 `\arccot`,仍按设计报错。 - -## Testing - -`packages/client/ui-primitives/tests/markdown.client.spec.tsx` 新增多行用例——开围栏行内容由内容行行尾 `$$` 闭合、由独占行 `$$` 闭合、出现在段落之后、出现在列表项内,以及列表项之后的零缩进围栏——该用例去掉改动即失败。同一文件还固定了「使用单个 `$` 的多行公式」,它与上面的多行用例一样只有本次改动才会渲染成 display。另有一组用例各自对应一个条件:后面还有块时的尾随文本候选(flow 必须放弃「后面不是行尾」的完整 `$$`)、单行显示公式内的单个 `$`(不得因为一个 `$` 就放弃)、保持段落完整性的转义美元候选(打断检查不得认领段落)、保持段落完整性的未闭合 `\[` 候选(守卫不得作用于反斜杠构造)、以奇数个反斜杠结尾的候选(转义状态必须在换行处结束)、TeX 注释内的闭合围栏、紧邻围栏或只隔空白的 `%`、已开启注释内的第二个 `%`、`\verb|…|` 内的 `%`、`\verb` 与 `\verb*` 之后的分隔符及其空区域、`verb` 之前的转义反斜杠、不跨行的 verb 尾部、以 `verb` 结尾的注释、后续行尾随文本围栏(其后正文由上游接管)、注释内失败的围栏,以及带该反斜杠、不带该反斜杠、以 verb 尾部结尾三种重复候选的有界解析开销。 - -DOM 兼容语料新增 `math-multiline-display` 及其 `.settled.txt`、`.streaming.txt`,同时固定了「列表项之后的零缩进 `$$` 不进入列表项内」。`apps/web/tests/math-rendering.e2e.ts` 在浏览器 lane 渲染多行写法。 diff --git a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.i18n.yaml b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.i18n.yaml index 6566e1a57e..ef8bb48089 100644 --- a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.i18n.yaml @@ -9,8 +9,8 @@ en: a72071eeedb77402 zh: 818d16ce429fd610 /agent-note-continuable-subagents/decision: - en: 3420195435e02a8f - zh: 6156eedb3c23d360 + en: 6ba1bf6184794aa8 + zh: 71b4e41556dafb93 /agent-note-continuable-subagents/decision/materialization-and-public-operations: en: c3a83ff748a02143 zh: 468bf62c8ddabf70 diff --git a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md index e76aae22fe..f5d178fec7 100644 --- a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md +++ b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.md @@ -18,6 +18,8 @@ Parent Agents need to send later work to the same live child without changing it ## Decision +Human control addressing and permissions are superseded by [target Session user controls](../architecture/2026-10-22-subagent-target-user-controls.md); model-message adjacency and parent-owned runtime restrictions are superseded by [tree-wide communication](../architecture/2026-10-16-tree-wide-agent-communication.md). The direct-parent authorization statements below do not govern those current operations. + The shared activation entry point, external execution ownership, and caller-versus-parent result delivery are governed by [Unified subagent activations](../simplification/2026-09-17-unified-subagent-activations.md). This record retains the independent rationale described below. A continuable subagent has one durable Session and at most one process-local Activation: diff --git a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.zh.md b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.zh.md index ce543b4efa..44f51e1d9e 100644 --- a/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.zh.md +++ b/.agents/notes/implemented/feature/2026-07-28-continuable-subagent-conversations.zh.md @@ -18,6 +18,8 @@ parent Agent 还需要在不改变当前轮次的前提下,向同一个在线 ## 决策 +人工控制的地址和权限由[目标 Session 用户控制](../architecture/2026-10-22-subagent-target-user-controls.zh.md)取代;模型消息的相邻关系限制和父级运行时所有权限制由[整树通信](../architecture/2026-10-16-tree-wide-agent-communication.zh.md)取代。下文的直接父级授权表述不约束这些当前操作。 + 共享 activation 入口、外部执行所有权,以及调用方与父级之间的结果投递选择由[统一 subagent activation](../simplification/2026-09-17-unified-subagent-activations.zh.md) 决策拥有。本记录保留下述独立理由。 一个可继续 subagent 拥有一个持久化会话,并且至多拥有一个进程内激活: diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml b/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml index 68ef489fe0..dd2778d632 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.i18n.yaml @@ -6,35 +6,35 @@ en: c914d8148bfc4bf9 zh: a8115f87c0ac6cae /agent-note-durable-agent-teams-over-continuable-children/problem: - en: bab62798c2dc07b4 - zh: fe42c5abf9127d37 + en: 567b68ab8eb4b5b2 + zh: 31a40aa22821d63a /agent-note-durable-agent-teams-over-continuable-children/decision: - en: 35650a30529c01f8 - zh: 4f9ee01b568d2fed + en: affeddb8788ea73b + zh: 73615d3ccbd71871 /agent-note-durable-agent-teams-over-continuable-children/profile-delegation: - en: 4835fb8c0c0d8a0d - zh: 5f9438a0d58104c4 + en: f4c8d8760c7ebcf4 + zh: 32ccca202a7769ac /agent-note-durable-agent-teams-over-continuable-children/team-identity: - en: f82812d6ac0ac78d - zh: 7dd80a6ad13674ca + en: d79f4425f2c1929f + zh: 6586410db4a02cd1 /agent-note-durable-agent-teams-over-continuable-children/provisioning-and-recovery: - en: 4345ac9a6ac7ad04 - zh: 1d19ecbb128a75a3 + en: 624e9d42af1af859 + zh: 020dcbb26211ea67 /agent-note-durable-agent-teams-over-continuable-children/mailbox-and-task-transactions: - en: bfc3063536837c0e - zh: 6b8e69ba85cc2bb1 + en: bfa07b5bc6354360 + zh: c82119c0a5ea7f01 /agent-note-durable-agent-teams-over-continuable-children/shared-checkout-boundary: - en: 34920da68b5763e0 - zh: 7604392594e4b8a8 + en: 384f75638b0f1fb6 + zh: b7ab1191784d3d27 /agent-note-durable-agent-teams-over-continuable-children/web-projection: - en: e6348054f024725b - zh: 8740636e99940308 + en: 1dc1386f5033e83b + zh: 533803da51f3716f /agent-note-durable-agent-teams-over-continuable-children/alternatives-considered: - en: 8cb2fd8839f5f8b7 - zh: e302ca03e569de65 + en: 087ffae4744a129b + zh: 842dc1ded7f8d9c3 /agent-note-durable-agent-teams-over-continuable-children/testing: - en: 092ac3c2b6f552aa - zh: c688c1bec5ad8a07 + en: 2ff7adaaaa65fad7 + zh: 9c7dd682abe988d1 /agent-note-durable-agent-teams-over-continuable-children/consequences: - en: da9cd22b1185a793 - zh: e20d7ef9226f237f + en: c071fa2ccdb911b5 + zh: 3b8cf0d3303a4d40 diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.md b/.agents/notes/implemented/feature/2026-08-05-agent-teams.md index b93e2716f9..2056882e73 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.md +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.md @@ -10,47 +10,41 @@ The subagent seam supplies fresh/fork providers, durable child Sessions, FIFO fo All same-process Agents also share one checkout. Filesystem edit tools can reject an observed stale version, but Bash, formatters, generators, and external writers bypass that fence. Treating a teammate name or task owner as a file lock would hide rather than solve this concurrency boundary. -Agent Teams needs an explicit opt-in composition while its public contracts remain experimental. The default tool catalog and simple-task behavior must remain unchanged, while an explicitly requested Team must survive child Activation settlement and mailbox delivery races long enough for the Lead to aggregate the result before process teardown. +Team collaboration requires explicit opt-in; [Session selection](../architecture/2026-10-20-session-team-mode.md) owns its granularity and default composition. The default tool catalog and simple-task behavior must remain unchanged, while an explicitly requested Team must survive child Activation settlement and mailbox delivery races long enough for the Lead to aggregate the result before process teardown. ## Decision -Every ordinary runtime root is the implicit Lead of a Team identified by that root's `SessionId`. The Team has no creation event: its Lead pseudo-row exists by identity, while durable state begins with the first member, message, or task event. A roster is flat and contains at most the configured number of immutable lowercase-kebab-case names. Each teammate is a continuable direct child with a reserved Session id; only the Lead creates or interrupts teammates. Ordinary provider-owned subagents outside the roster are not Team members, and an ordinary fork is a new root whose inherited Team records are excluded by their ancestor `TeamId`. +Every ordinary root and its descendants form the Team identified by the root `SessionId`; durable task state begins with the first task event. [Subagent teammates](../architecture/2026-10-15-agent-teams-as-subagents.md) owns the single agent identity. [Inbox-only waiting](../simplification/2026-10-29-inbox-only-agent-wait.md) keeps task-board changes independent of inbox waiting. An ordinary Session fork leads a new tree and excludes inherited Team authority. -The implementation is split into `@deepseek-ai/dsh-experimental-agent-team`, which owns `ctx.agentTeams` and durable semantics, and `@deepseek-ai/dsh-experimental-tool-agent-team`, which owns scoped schemas and model guidance. Every Team tool declares its complete result schema and renders that value as compact JSON, so the compiler checks each `execute` against what the model is promised and no result spends tokens on indentation. Deployments mount both plugins explicitly and may disable legacy continuable controls with the same model-visible names. The shared policy announces Team availability and describes coordination responsibilities. Both packages are public members of `packages/experimental/`; the [experimental package reference](../../../../packages/experimental/AGENTS.md) owns publication, dependency isolation, and promotion. +The implementation is split into `@deepseek-ai/dsh-agent-team`, which owns `ctx.agentTeams` and durable semantics, and `@deepseek-ai/dsh-tool-agent-team`, which owns scoped schemas and model guidance. Every Team tool declares its complete result schema and renders that value as compact JSON, so the compiler checks each `execute` against what the model is promised and no result spends tokens on indentation. The base bundle mounts both plugins; Team registers no tool that shares a name with the subagent controls. The shared policy announces Team availability and describes coordination responsibilities. Both packages belong to the [subagent family](../../../../packages/subagent/README.md); the root Session’s saved selection gates the task tools and policy. The [Session-mode upgrade guide](../../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md) describes profile migration. The Lead must wait for required work before its final answer. Process teardown remains the final lifecycle owner and drains continuation Activations; a Team task owner is durable state and is not automatically released by idle, interruption, or process exit. ## Profile delegation -The [Team profile](../../../../packages/experimental/agent-team-profile/README.md) disables `subagent` and `subagent_fork` together with the overlapping global controls. Direct model delegation uses `spawn_teammate` with fresh or fork context, keeping those children in the durable roster. Workflow remains available through the base profile’s fresh `spawn` provider for scripted orchestration; it cannot inherit a teammate’s conversation identity through the model tool. The Subagent services and providers remain shared infrastructure. Ordinary Session forks retain their history; [current identity handling](../architecture/2026-10-13-team-identity-runtime-context.md) supplies the fork’s own role. +The [base bundle](../../../../packages/bundle/base/README.md) inserts the Team rows and keeps the base delegation and control tools; teammates are started with those tools as described in [subagents](../architecture/2026-10-15-agent-teams-as-subagents.md). Ordinary Session forks retain their history; [current identity handling](../architecture/2026-10-13-team-identity-runtime-context.md) supplies the fork's own role. ## Team identity -Shared system policy and all tool schemas stay uniform across members; execution owns role restrictions. Team tools resolve the caller’s Team and accept member names, so the model needs no Team id. [Required runtime-context identity](../architecture/2026-10-13-team-identity-runtime-context.md) owns identity injection, retention, and fork handling. +Shared system policy and tool schemas stay uniform across members; execution enforces role restrictions. Team tools resolve the caller’s Team and use Session ids as task owners. [Required runtime-context identity](../architecture/2026-10-13-team-identity-runtime-context.md) owns identity injection, retention, and fork handling. ## Provisioning and recovery -Creation first appends and flushes a `team/member` provisioning snapshot in the Lead Session, then starts the reserved continuable child through the selected fresh or fork provider. Failure before initial inbox acceptance appends a failed snapshot. Success flushes the child's accepted inbox item before appending active. Recovery recognizes that initial message while it is still pending or after it enters user-message history. Names are reserved by the first provisioning record and never reused, including after failure. Disposal closes admission, aborts and awaits admitted creation and send operations, then stops every live child recorded by the roster; a failed child remains cleanup-owned until its Activation exits, and cleanup rejection fails disposal. - -A root recovery reconciles an unterminated provisioning record against the child's independently persisted Session. Matching direct-parent and continuable descriptors plus a recorded initial user message prove successful admission and produce active; absence, corruption, mismatched provider/lineage, or a missing admitted message produces failed. The creator re-reads the terminal phase under the same Lead-log serializer; if recovery marked failed while creation succeeded, it drains the child and reports a provisioning conflict instead of retaining an orphan. This avoids reconstructing an initial prompt that was never retained in the Team log and contains plugin-reload races. - -Fresh children have no inherited conversation. Fork children capture the Lead's completed-turn prefix once and retain it as their own durable seed. The current delegation turn remains excluded, matching the existing fork provider contract. +Teammate creation and cold resume belong to the subagent runtime ([subagent teammates](../architecture/2026-10-15-agent-teams-as-subagents.md)). Historical `team/member` records remain readable with their phases and descriptions; Team writes no new membership records. ## Mailbox and task transactions -The historical Lead-log mailbox remains a readable format: queued and delivered records keep their stable identity and sender, and Team payload validation still applies to them. Team no longer delivers or acknowledges them; new sends follow the [direct inbox decision](../simplification/2026-09-26-team-direct-inbox.md). +The historical Lead-log mailbox remains readable in original Session logs. The [task-only projection decision](../simplification/2026-10-29-team-task-only-projection.md) supersedes mailbox projection, checkpoint retention, and Team payload validation. Historical queued messages are never delivered or acknowledged. -Unknown mailbox content stays as decoded JSON during event projection and checkpoint admission. Validation inspects its type without rebuilding its fields, because generic object parsing can omit a valid own `__proto__` key. Locally declared content variants undergo structural validation; opaque plugin fields do not gain Team semantics. Cache invalidation is necessary because parser correction alone cannot recover keys omitted from cached state. The [Team documentation](../../../../packages/experimental/agent-team/README.md) owns the restore behavior. - -`send_message` uses Steer for running, idle, and cold targets. New sends return inbox acceptance. The [Team Steer messaging decision](../../archived/simplification/2026-08-30-team-send-message-steer.md) records the single-tool scheduling rationale. +Member messages use the subagent `send_message` operation, which steers running, idle, and cold targets and returns inbox acceptance. Shared tasks are complete snapshots with Team-local ids and monotonic revisions. Every mutation carries `expectedRevision`. Any member creates, reads, or claims a ready unowned task; the owner or Lead edits and transitions it, while only the Lead assigns another member. Numeric task ids remain within the safe-integer allocation range, and exhaustion fails without reusing an id. Dependencies must name non-deleted tasks and form a complete DAG. Deleted tasks are retained tombstones. `writeScopes` are normalized path prefixes that produce overlap diagnostics but never block claim or authorize a write. -`wait_agent` blocks on one roster, mailbox, task, or live-status edge registered after the call starts instead of encouraging model polling. It does not replay an earlier edge, so callers re-read authoritative state after wakeup or timeout. Lead-only interruption cancels the current turn with inbox preservation and does not alter mailbox or task ownership. +`wait_agent` belongs to ordinary subagent controls and waits for the exact caller’s next-step inbox, including already-pending input. Task commits do not end waits, deliver messages, or start idle turns. Agents send messages when another member needs to act on a task change. Ancestors may interrupt descendants without changing task ownership. ## Shared checkout boundary -Members start in the Lead’s current directory and observe shared filesystem writes immediately. Later directory changes stay local to each Session. The policy tells members to partition tasks, record advisory write scopes, order dependent work, and let the Lead inspect the final diff and run tests. A filesystem stale-version rejection requires rereading and rebasing the intended change. No equivalent guarantee is claimed for Bash, formatters, code generation, or direct external writes. +Members start in the Lead’s current directory and observe shared filesystem writes immediately. Later directory changes stay local to each Session. The task policy tells members to claim ready tasks, use advisory write scopes and dependencies, and complete tasks after doing the work. A filesystem stale-version rejection requires rereading and rebasing the intended change. No equivalent guarantee is claimed for Bash, formatters, code generation, or direct external writes. The Team domain does not infer branches, create worktrees, merge changes, or silently change cwd. A deployment or caller can use [explicit worktree creation](2026-09-13-explicit-worktree-creation.md) separately. This preserves the existing same-world subagent and sandbox contracts. @@ -58,36 +52,36 @@ The Team domain does not infer branches, create worktrees, merge changes, or sil The Web panel reads the Lead Session's `agentTeam` wire projection because the existing projection stream keeps browser state current without a separate Team read API. Both Lead and teammate conversations select values from the shared cross-Session store. The panel owns no projection reads: Session loading, cached list values, and control baselines supply the data. -The wire view carries durable roster phases, non-deleted task views with shared readiness and overlap derivation, and `failure` beside the last valid state. Live activity comes from Session status. Model selection has its own durable projection; the panel displays the shared store's available values without opening member conversations. A missing cached value remains absent until Session loading or a live update supplies it. +The task panel uses non-deleted task views with readiness and overlap diagnostics, plus `failure` beside the last valid state. Historical roster fields remain decodable but have no current UI or assignment authority. Ordinary subagent navigation owns member discovery; task owner labels reuse Session and catalog metadata. -Publication requires `apply` to return a new state object per applied Team event and replace only the touched collection. Mailbox-only events retain the view reference and publish nothing. The existing carrier sends each changed complete view to every connected browser; the package README records that cost. +Publication requires `apply` to return a new state per applied event and replace only the touched collection. Mailbox-only events retain the client view and publish nothing. The existing carrier sends each changed complete view to connected browsers; the package README records that cost. ## Alternatives considered -**Extend direct-child subagent tools with peer ids.** Rejected because parent/child authority and Team peer membership are different domains. Adding peer access to the continuation seam would weaken its exact-parent authorization and still leave roster and tasks without a persistence owner. +**Keep a separate Team communication authority.** The later [tree-wide communication decision](../architecture/2026-10-16-tree-wide-agent-communication.md) places routing and authorization in the subagent runtime; a task board cannot grant another route. -**Store mail in each target Session before Lead-log enqueue.** Rejected because target materialization and acceptance can fail after the Team has committed the send. The always-live Lead Session is the transaction home; target recording is the acknowledgement and de-duplication boundary. +**Keep a durable Team mailbox.** Target admission and task commit are independent operations. The historical Team mailbox remains readable, while current messaging uses the target inbox. Task commits neither deliver messages nor end waits. **Treat task ownership or write scopes as locks.** Rejected because external writers bypass them, crashed owners remain durable, and path-prefix overlap cannot prove semantic independence. False mutual exclusion is more dangerous than an explicit warning. **Create isolated worktrees automatically.** Rejected because worktree creation, branch naming, merge policy, ignored files, build artifacts, and cleanup are deployment choices. It also changes the same-world behavior existing subagents and sandboxes expose. -**Enable Teams in the default catalog.** Rejected because scoped Team controls would shadow same-named legacy globals and unsolicited delegation would add latency and token cost to simple tasks. An opt-in profile bundle inserts Team and disables the legacy controls without adding Team packages to shipped dependency graphs. +**Enable Teams in the default catalog.** Rejected because unsolicited coordination and Team tool schemas would add latency and token cost to simple tasks. An opt-in profile bundle inserts Team without adding Team packages to shipped dependency graphs. -**Use an in-memory board and mailbox.** Roster and task state must survive settlement, HMR, and interruption. Historical mailbox records stay readable; message ownership follows the target inbox. +**Use an in-memory board and mailbox.** Task state must survive settlement, HMR, and interruption. Historical mailbox records stay readable; message ownership follows the target inbox. -**Return Team tool results as untyped JSON.** Rejected because an undeclared result type lets `execute` drift from the value the model is promised without a compiler error, and it invites indentation that costs tokens on every roster, task, and receipt. Each Team tool therefore declares its complete result schema and one shared helper renders it compactly. +**Return Team tool results as untyped JSON.** Rejected because an undeclared result type lets `execute` drift from the value the model is promised without a compiler error, and it invites indentation that costs tokens on every task and wait result. Each Team tool therefore declares its complete result schema and one shared helper renders it compactly. ## Testing -Package tests cover Team authority, provisioning durability, task transitions, direct inbox acceptance, sender attribution, lifecycle cancellation, and historical mailbox readability. The keyless Team profile snapshot pins the policy, tools, and workflow; the CLI composition test checks persisted Team and child logs. +Package tests cover task transitions, tree-based assignment, historical roster and mailbox decoding, and task commits that leave inbox waits pending. Ordinary subagent tests cover inbox waiting; recorded Team compositions cover identity, task policy, and tools. -Model-facing member identities and availability follow the [tool projection reference](../../../../packages/experimental/tool-agent-team/README.md); service residency and durable identity remain distinct. +Identity and inbox waiting follow [subagent controls](../../../../packages/subagent/tool-subagent-control/README.md); task policy follows the [Team tool reference](../../../../packages/team/tool-agent-team/README.md). ## Consequences -The Lead Session retains whole task/member snapshots and historical mailbox records. This favors inspectable recovery over compact deltas; deleted and delivered history remains append-only until broader Session retention applies. +The Lead Session retains whole task snapshots and historical member and mailbox records. This favors inspectable recovery over compact deltas; deleted and delivered history remains append-only until broader Session retention applies. -An active roster member can be non-resident, so `inactive` is not failure and sends can incur cold-resume latency. Admission failures reject new sends. Historical pending mail is never delivered. Failed provisioning permanently consumes its name and member slot. +A teammate can be non-resident, so `inactive` is not failure and sends can incur cold-resume latency. Historical pending mail is never delivered. Coordination reduces likely checkout conflicts but cannot eliminate writes outside filesystem compare-and-set tools. The final diff and tests remain the Lead's integration boundary. diff --git a/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md b/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md index f38c6f68c4..3fbb92daf3 100644 --- a/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md +++ b/.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md @@ -10,47 +10,41 @@ subagent seam 已提供 fresh/fork provider、持久 child Session、FIFO foll 同进程 Agent 还共享一个 checkout。文件系统 edit 工具可以拒绝已观察到的陈旧版本,但 Bash、formatter、generator 与外部 writer 会绕过该屏障。把 teammate name 或 task owner 当作文件锁只会掩盖而不是解决该并发边界。 -Agent Teams 的公开约定仍处于实验阶段,因此需要显式启用的组合。默认工具目录与简单任务行为必须保持不变;而显式请求的 Team 必须能跨越 child Activation settlement 与 mailbox 投递竞争,使 Lead 在进程 teardown 前汇总结果。 +Team 协作需要显式开启;[Session 选择](../architecture/2026-10-20-session-team-mode.zh.md)负责选择粒度与默认组合。默认工具目录与简单任务行为必须保持不变;而显式请求的 Team 必须能跨越 child Activation settlement 与 mailbox 投递竞争,使 Lead 在进程 teardown 前汇总结果。 ## Decision -每个普通运行时 Root 都是一个隐式 Team 的 Lead,Team id 等于该 Root 的 `SessionId`。Team 没有 creation event:Lead pseudo-row 由身份直接存在,持久状态从第一条 member、message 或 task event 开始。roster 是扁平结构,最多包含配置数量、不可变且采用小写 kebab-case 的名字。每个 teammate 都是使用预留 Session id 的 continuable 直接 child;只有 Lead 可以创建或 interrupt teammate。roster 外由 provider 管理的普通 subagent 不是 Team member;普通 fork 是新的 Root,继承的 Team 记录会因 ancestor `TeamId` 被排除。 +每个普通根及其后代组成以根 `SessionId` 标识的 Team;持久任务状态从首个任务事件开始。[subagent 队友](../architecture/2026-10-15-agent-teams-as-subagents.zh.md)负责单一 agent 身份。[仅等待收件箱](../simplification/2026-10-29-inbox-only-agent-wait.zh.md)使任务板变更独立于收件箱等待。普通 Session fork 成为一棵新树的根,并排除继承的 Team 权限。 -实现拆分为 `@deepseek-ai/dsh-experimental-agent-team` 与 `@deepseek-ai/dsh-experimental-tool-agent-team`:前者负责 `ctx.agentTeams` 和持久语义,后者负责 scoped schema 与模型指引。每个 Team 工具都声明完整的结果 schema,并把该值渲染为紧凑 JSON,因此编译器会检查每个 `execute` 是否符合对模型的承诺,也没有结果把 token 花在缩进上。部署显式挂载两个插件,并可禁用具有相同模型可见名称的旧 continuable control。共享策略声明 Team 可用,并说明协调责任。两个包都是 `packages/experimental/` 的公开成员;[实验性包参考](../../../../packages/experimental/AGENTS.md)负责发布、依赖隔离与 promotion。 +实现拆分为 `@deepseek-ai/dsh-agent-team` 与 `@deepseek-ai/dsh-tool-agent-team`:前者负责 `ctx.agentTeams` 和持久语义,后者负责 scoped schema 与模型指引。每个 Team 工具都声明完整的结果 schema,并把该值渲染为紧凑 JSON,因此编译器会检查每个 `execute` 是否符合对模型的承诺,也没有结果把 token 花在缩进上。基础 bundle 挂载两个插件;Team 不注册与 subagent control 同名的工具。共享策略声明 Team 可用,并说明协调责任。两个包属于 [subagent 家族](../../../../packages/subagent/README.zh.md);根 Session 保存的选择控制任务工具与策略。[Session 模式升级指南](../../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md)说明 profile 迁移。 Lead 必须等待所需工作后才能给出最终答案。进程 teardown 仍是最终生命周期 owner,并会 drain continuation Activation;Team task owner 是持久状态,不会因 idle、interrupt 或进程退出自动释放。 ## Profile delegation -[Team profile](../../../../packages/experimental/agent-team-profile/README.zh.md) 禁用 `subagent`、`subagent_fork` 以及名称重叠的全局控件。模型直接委派使用支持 fresh 或 fork 上下文的 `spawn_teammate`,使这些子代理进入持久 roster。Workflow 仍通过 base profile 的 fresh `spawn` 提供方执行脚本编排;经模型工具创建的 workflow 子代理不会继承 teammate 的对话身份。Subagent 服务和提供方仍是共享基础设施。普通 Session fork 保留历史;[当前身份处理](../architecture/2026-10-13-team-identity-runtime-context.zh.md)提供 fork 自己的角色。 +[基础 bundle](../../../../packages/bundle/base/README.zh.md) 插入 Team 行,并保留 base 的委派与控制工具;teammate 按[subagent](../architecture/2026-10-15-agent-teams-as-subagents.zh.md)所述使用这些工具启动。普通 Session fork 保留历史;[当前身份处理](../architecture/2026-10-13-team-identity-runtime-context.zh.md)提供 fork 自己的角色。 ## Team identity -共享 system 策略和全部工具 schema 在成员间保持一致;执行时检查角色权限。Team 工具根据调用者确定 Team,并接受成员名字,因此模型不需要 Team id。[必需 runtime-context 身份](../architecture/2026-10-13-team-identity-runtime-context.zh.md)负责身份注入、保留与 fork 处理。 +成员共享统一系统策略和工具模式;执行时强制角色权限。Team 工具解析调用方所属 Team,并使用 Session id 作为任务负责人。[必需运行时身份](../architecture/2026-10-13-team-identity-runtime-context.zh.md)负责身份注入、保留和分叉处理。 ## Provisioning and recovery -创建操作先在 Lead Session 中追加并 flush `team/member` provisioning 快照,再通过选定 fresh 或 fork provider 启动预留的 continuable child。初始 inbox 获准前的失败会追加 failed 快照;成功会先 flush child 中已接受的 inbox 条目,再追加 active。恢复会在初始消息仍处于 pending 或已进入用户消息历史时识别它。名字由第一条 provisioning 记录永久保留,包括失败后也不能复用。dispose 会关闭准入,中止并等待已获准的创建与发送操作,再停止 roster 记录的所有 live child;failed child 在 Activation 退出前仍由 cleanup 拥有,cleanup 拒绝会让 dispose 失败。 - -Root 恢复时会把未终结 provisioning 记录与独立持久 child Session 对账。直接 parent 与 continuable descriptor 匹配,并且已经记录初始用户消息,才能证明准入成功并转为 active;缺失、损坏、provider/lineage 不匹配或缺少已准入消息都会转为 failed。creator 会在同一 Lead 日志 serializer 内重读终态;如果 recovery 在创建成功时先标记 failed,creator 会 drain child 并报告 provisioning conflict,而不是遗留孤儿。这样既无需重建从未保存在 Team 日志中的初始 prompt,也能约束插件 reload 竞争。 - -fresh child 不继承对话。fork child 只捕获一次 Lead 已完成 turn 前缀,并保留为自己的持久 seed。当前 delegation turn 保持排除,与既有 fork provider 契约一致。 +队友创建和冷恢复属于子代理运行时([子代理队友](../architecture/2026-10-15-agent-teams-as-subagents.zh.md))。历史 `team/member` 记录保留阶段和描述并继续可读;Team 不写入新成员记录。 ## Mailbox and task transactions -历史 Lead-log mailbox 仍是可读格式:queued 与 delivered 记录保留稳定身份与发送者,Team payload 校验仍适用于它们。Team 不再投递或确认这些记录;新发送遵循[直接 inbox 决策](../simplification/2026-09-26-team-direct-inbox.zh.md)。 +历史 Lead-log mailbox 仍可从原始 Session 日志读取。[仅投影任务的决策](../simplification/2026-10-29-team-task-only-projection.zh.md)取代邮箱投影、检查点保留和 Team 载荷校验。历史排队消息绝不再投递或确认。 -事件投影和 checkpoint 准入期间,未知 mailbox 内容保持为已解码 JSON。校验只检查其 type,不重建字段,因为通用对象解析可能省略有效的自有 `__proto__` 键。本地声明的内容变体接受结构校验;不透明的插件字段不获得 Team 语义。缓存失效是必要的,因为只修正解析器无法恢复缓存状态中省略的键。[Team 文档](../../../../packages/experimental/agent-team/README.zh.md)拥有恢复行为的说明。 - -`send_message` 对 running、idle 和 cold target 使用 Steer。新发送返回 inbox 接收结果。[Team Steer 消息决策](../../archived/simplification/2026-08-30-team-send-message-steer.md)记录单一工具调度的理由。 +member 消息使用 subagent 的 `send_message` 操作,它对 running、idle 和 cold target 使用 Steer,并返回 inbox 接收结果。 共享 task 是带 Team-local id 与单调 revision 的完整快照。每次变更都携带 `expectedRevision`。任意 member 可以创建、读取或 claim ready 且无 owner 的任务;Owner 或 Lead 可以编辑和转换;只有 Lead 可以分配给另一个 member。数字 task id 保持在安全整数分配范围内;该范围耗尽时会失败,不会复用 id。依赖必须指向未删除任务,并形成完整 DAG。删除任务保留为 tombstone。`writeScopes` 是规范化路径前缀,只产生重叠诊断,绝不会阻止 claim 或授予写权限。 -`wait_agent` 等待调用注册后发生的下一条 roster、mailbox、task 或实时 status 边,避免模型轮询。它不会回放更早的边,因此调用方需要在唤醒或超时后重新读取权威状态。仅限 Lead 的 interrupt 使用 inbox preservation 取消当前 turn,不改变 mailbox 或 task owner。 +`wait_agent` 属于普通 subagent 控制工具,等待当前调用者的下一步收件箱,包括已有待处理输入。任务提交不结束等待、不投递消息,也不启动空闲轮次。需要另一个成员处理任务变更时,Agent 应发送消息。祖先可中断后代,不改变任务归属。 ## Shared checkout boundary -所有 member 创建时使用 Lead 的当前目录,并立即观察共享文件系统写入。后续目录变更仅影响各自 Session。策略要求 member 切分任务、记录提示性 write scope、为有序工作添加依赖,并由 Lead 检查最终 diff 和运行测试。文件系统 stale-version 拒绝后必须重新读取并 rebase 修改意图。Bash、formatter、codegen 与直接外部写入不具备等价保证。 +所有 member 创建时使用 Lead 的当前目录,并立即观察共享文件系统写入。后续目录变更仅影响各自 Session。任务策略要求 member 认领就绪任务、使用提示性 write scope 和依赖,并在完成工作后完成任务。文件系统 stale-version 拒绝后必须重新读取并 rebase 修改意图。Bash、formatter、codegen 与直接外部写入不具备等价保证。 Team 领域不会推断 branch、创建 worktree、merge 变更或静默改变 cwd。deployment 或调用方可以另外使用[显式工作树创建](2026-09-13-explicit-worktree-creation.zh.md)。这样保留既有 same-world subagent 与 sandbox 契约。 @@ -58,36 +52,36 @@ Team 领域不会推断 branch、创建 worktree、merge 变更或静默改变 c Web panel 读取 Lead Session 的 `agentTeam` 传输投影,因为现有投影流能持续更新浏览器状态,无需独立的 Team 读取 API。Lead 与 teammate 会话均从共享的跨 Session store 选择值。面板不负责投影读取:Session 加载、列表缓存值与控制基线提供数据。 -传输视图携带持久 roster phase、使用共享就绪与重叠派生逻辑的未删除任务视图,以及最后有效状态旁的 `failure`。实时活动来自 Session 状态。模型选择有自己的持久投影;面板展示共享 store 中可用的值,不打开成员会话。缺少的缓存值保持缺失,直到 Session 加载或实时更新提供它。 +任务面板使用包含就绪和重叠诊断的未删除任务视图,以及最后有效状态旁的 `failure`。历史名册字段仍可解码,但不拥有当前 UI 或分配权限。普通 subagent 导航负责成员发现;任务所有者标签复用 Session 和目录元数据。 -发布要求 `apply` 对每个已应用的 Team 事件返回新的 state 对象,并只替换被触及的集合。仅邮箱的事件保留视图引用,不发布 frame。现有传输层将每个变化后的完整视图发送给所有已连接浏览器;包 README 记录了这项开销。 +发布要求 `apply` 为每个应用的事件返回新状态,且只替换触及的集合。仅邮箱事件保留客户端视图,不发布更新。现有载体向已连接浏览器发送变更后的完整视图;包 README 记录该成本。 ## Alternatives considered -**用 peer id 扩展 direct-child subagent tool。** 拒绝,因为 parent/child 权限与 Team peer membership 是不同领域。向 continuation seam 增加 peer access 会削弱 exact-parent authorization,仍无法为 roster 与 task 提供持久 owner。 +**保留独立 Team 通信权限。** 后续的[整树通信决策](../architecture/2026-10-16-tree-wide-agent-communication.zh.md)将路由和授权置于 subagent 运行时;任务板不能授予另一条路由。 -**在 Lead 日志入队前把 mail 存入每个 target Session。** 拒绝,因为 Team 提交发送之后,target materialization 与准入仍可能失败。始终 live 的 Lead Session 是事务 owner;target recording 是 acknowledgement 与去重边界。 +**保留持久化 Team 邮箱。** 目标接纳和任务提交是独立操作。历史 Team 邮箱保持可读,当前通信使用目标收件箱。任务提交既不投递消息,也不结束等待。 **把 task ownership 或 write scope 当作锁。** 拒绝,因为外部 writer 会绕过它们,崩溃 owner 会持久保留,而路径前缀重叠不能证明语义独立。虚假的互斥保证比明确 warning 更危险。 **自动创建隔离 worktree。** 拒绝,因为 worktree 创建、branch 命名、merge 策略、ignored file、构建产物与 cleanup 都是 deployment 选择;它也会改变既有 subagent 与 sandbox 暴露的 same-world 行为。 -**在默认工具目录中启用 Team。** 拒绝,因为 scoped Team control 会覆盖同名旧全局工具,主动 delegation 也会给简单任务增加延迟和 token 成本。opt-in profile bundle 会插入 Team 并禁用旧 control,同时不向随附依赖图添加 Team 包。 +**在默认工具目录中启用 Team。** 拒绝,因为主动协调与 Team 工具 schema 会给简单任务增加延迟和 token 成本。opt-in profile bundle 会插入 Team,同时不向随附依赖图添加 Team 包。 -**使用内存 board 与 mailbox。** roster 与任务状态必须经受 settlement、HMR 与中断。历史 mailbox 记录保持可读;消息归属目标 inbox。 +**使用内存 board 与 mailbox。** 任务状态必须经受 settlement、HMR 与中断。历史 mailbox 记录保持可读;消息归属目标 inbox。 -**让 Team 工具返回未类型化 JSON。** 拒绝,因为未声明的结果类型会让 `execute` 在没有编译错误的情况下偏离对模型的承诺,也会引入在每份 roster、task 与回执上都消耗 token 的缩进。因此每个 Team 工具都声明完整的结果 schema,并由一个共享 helper 紧凑渲染。 +**让 Team 工具返回未类型化 JSON。** 拒绝,因为未声明的结果类型会让 `execute` 在没有编译错误的情况下偏离对模型的承诺,也会引入在每份 task 与 wait 结果上都消耗 token 的缩进。因此每个 Team 工具都声明完整的结果 schema,并由一个共享 helper 紧凑渲染。 ## Testing -包测试覆盖 Team 权限、provisioning 持久性、任务转换、直接 inbox 接收、发送者归属、生命周期取消和历史 mailbox 可读性。无密钥 Team profile 快照固定 policy、工具与工作流;CLI 组合测试检查持久 Team 和 child 日志。 +包测试覆盖任务转换、基于树的分配、历史名册和邮箱解码,以及任务提交后收件箱等待保持未完成。普通 subagent 测试覆盖收件箱等待;录制 Team 组合覆盖身份、任务策略和工具。 -模型可见的成员身份与可用状态遵循[工具投影说明](../../../../packages/experimental/tool-agent-team/README.zh.md);服务驻留状态和持久身份仍保持区分。 +身份和收件箱等待遵循 [subagent 控制工具](../../../../packages/subagent/tool-subagent-control/README.zh.md);任务策略遵循 [Team 工具参考](../../../../packages/team/tool-agent-team/README.zh.md)。 ## Consequences -Lead Session 保留完整 task/member 快照和历史 mailbox 记录。这优先支持可检查的恢复,而不是紧凑增量;deleted 与 delivered 历史在更广泛的 Session 保留策略生效前仍只追加。 +Lead Session 保留完整 task 快照以及历史 member 与 mailbox 记录。这优先支持可检查的恢复,而不是紧凑增量;deleted 与 delivered 历史在更广泛的 Session 保留策略生效前仍只追加。 -active roster 成员可能不驻留,因此 `inactive` 不表示失败,发送可能产生冷恢复延迟。准入失败会拒绝新发送。历史 pending 邮件永远不会被投递。provisioning 失败永久占用其名称和成员槽位。 +teammate 可能不驻留,因此 `inactive` 不表示失败,发送可能产生冷恢复延迟。历史 pending 邮件永远不会被投递。 协调可以降低 checkout 冲突概率,但无法消除文件系统 CAS 工具之外的写入。最终 diff 与测试仍是 Lead 的集成边界。 diff --git a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.i18n.yaml b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.i18n.yaml index bf652c02d6..db15a4f23d 100644 --- a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.i18n.yaml @@ -9,8 +9,8 @@ en: 7926983089aebab2 zh: 366e32db00674a83 /agent-note-archiving-a-session-with-running-work/decision: - en: 23adfbe72d671d6c - zh: 6fec976acfa54720 + en: 703d8b6f837cc894 + zh: aabe24d201ca0d81 /agent-note-archiving-a-session-with-running-work/alternatives-considered: en: 708268e1fe4b4b75 zh: 64a8f6d6f333e090 diff --git a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.md b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.md index 4bc3bab644..fcaba90418 100644 --- a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.md +++ b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.md @@ -14,8 +14,8 @@ Archive never hides running work. The registry owns the rule and declares one ca - **Refuse by default.** `archiveSession(sessionId)` rejects a non-empty activity answer with `WorkspaceActiveSessionError`; the API maps it to `workspace/session-active`, whose details carry the families with item ids and labels. A caller that did not ask to stop work never hides it, whichever client or SDK it is. - **Stop on request, after the write.** `archiveSession(sessionId, { stopActivity: true })` skips the activity check, writes the archive, and then dispatches the stop event: the durable archive set is what the pre-step gate reads, so every wake a stop induces — a cancelled child's settlement, a queued follow-up — is already blocked. The stops are issued and never awaited to settlement, so the Remote returns once every provider's request is out and the user's row hides at once; a stop that fails is a logged warning, not a reason to undo the archive. -- **The stop is the user's stop.** The Agent registry cancels the turn with `agent.cancel({ kind: 'user' })` — the stop button's path, so the aborted tool call settles as a `tool/result` and the turn ends as `aborted`, but without the button's `keepInbox`, so queued input is discarded with a logged inbox splice. The job registry seam kills the owned jobs, installed by its constructor for every implementation through the abstract `list` and `kill`. The Subagent runtime cancels running subagent descendants (durable lineage, subagent origin, any depth, never a fork) as their parent would. Each request is contained on its own, so one child or job that throws does not keep the others running. The Schedule plugin deletes every active Host task stored for the Session ([archive admission reads the stored tasks](2026-09-22-archive-admission-reads-stored-tasks.md)) inside one slot of the same serialized queue the tools use. It reads the stored rows rather than a runtime fold of the Session log, because a Host task outlives its Session's Agent and is the only place a due reminder can be seen. Each provider owns exactly the vocabulary it already has: the Agent registry knows turns, the job seam knows jobs, the Subagent runtime knows children, the Schedule plugin knows reminders; the API Session Controller keeps only the archived-lineage step gate. No new event type and no write inside another owner's turn, so a restored Session continues from a regularly ended log and unarchive brings nothing back that was stopped. -- **Archived means no model step.** The API Session Controller's `agent/pre-step` listener rejects a step proposed for an archived Session or for a subagent descendant of one, which the loop ends as `blocked` without a request. This closes the window in which a late waking delivery — a subagent settlement, a queued follow-up, a turn started between the activity answer and the write — would run a hidden turn, and keeps a child whose cancel was ignored from working for a parent nobody can see; unarchiving lifts the gate for the lineage. +- **The stop is the user's stop.** The Agent registry cancels the turn with `agent.cancel({ kind: 'user' })` — the stop button's path, so the aborted tool call settles as a `tool/result` and the turn ends as `aborted`, but without the button's `keepInbox`, so queued input is discarded with a logged inbox splice. The job registry seam kills the owned jobs, installed by its constructor for every implementation through the abstract `list` and `kill`. The Subagent runtime reports and cancels running descendants through each Activation’s verified ancestry, with live header ancestry for unmanaged Agents (any depth, never a fork). Releasing a creator does not erase its descendants’ membership. Each request is contained on its own, so one child or job that throws does not keep the others running. The Schedule plugin deletes every active Host task stored for the Session ([archive admission reads the stored tasks](2026-09-22-archive-admission-reads-stored-tasks.md)) inside one slot of the same serialized queue the tools use. It reads the stored rows rather than a runtime fold of the Session log, because a Host task outlives its Session's Agent and is the only place a due reminder can be seen. Each provider owns exactly the vocabulary it already has: the Agent registry knows turns, the job seam knows jobs, the Subagent runtime knows children, the Schedule plugin knows reminders; the API Session Controller keeps only the archived-lineage step gate. No new event type and no write inside another owner's turn, so a restored Session continues from a regularly ended log and unarchive brings nothing back that was stopped. +- **Archived means no model step.** The API Session Controller checks archived Sessions and available header ancestry in `agent/pre-step`. The Subagent runtime checks each managed Agent’s retained creation ancestors in the same event; intermediate creators may be offline. Both reject the step, which the loop ends as `blocked` without a request. This closes the window in which a late waking delivery — a subagent settlement, a queued follow-up, a turn started between the activity answer and the write — would run a hidden turn, and keeps a child whose cancel was ignored from working for a parent nobody can see; unarchiving lifts the gate for the lineage. - **The refusal is the confirmation.** The sidebar sends the plain archive first; a quiet Session archives without a dialog as before. The `workspace/session-active` refusal opens the stop-and-archive dialog, whose list comes from the Host's answer rather than a client-side mirror of running state, so the dialog names exactly what the Host will stop. Confirming resends with `stopActivity`; the notice offers undo, which restores the Session without resuming the stopped work. ## Alternatives considered diff --git a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.zh.md b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.zh.md index c7a912fa65..c511810b1d 100644 --- a/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.zh.md +++ b/.agents/notes/implemented/feature/2026-09-21-archive-stops-running-session-work.zh.md @@ -14,8 +14,8 @@ - **默认拒绝。** `archiveSession(sessionId)` 对非空的活动答案以 `WorkspaceActiveSessionError` 拒绝;API 把它映射为 `workspace/session-active`,details 携带各族及各项的 id 与名称。没有要求停止工作的调用方绝不会把工作藏起来,无论它是哪个客户端或 SDK。 - **按请求停止,先写后停。** `archiveSession(sessionId, { stopActivity: true })` 跳过活动检查,先写入归档,再派发停止事件:pre-step 门禁读取的正是持久化的归档集合,因此停止所引发的每一次唤醒——被取消子代理的结算、排队的 follow-up——都已被拦下。停止请求只发出、从不等待收敛,因此 Remote 在每个提供方的请求发出后即返回,用户的行随即隐藏;停止失败只是一条 warn 日志,不是撤销归档的理由。 -- **停止即用户的停止。** Agent 注册表用 `agent.cancel({ kind: 'user' })` 取消回合——与停止按钮同一条路径,因此被打断的工具调用以 `tool/result` 收口、回合以 `aborted` 结束,但不带按钮的 `keepInbox`,因此排队输入被丢弃并记录一次收件箱拼接。任务注册表接缝 kill 所属任务,由其构造函数只通过抽象的 `list` 与 `kill` 为每个实现安装。Subagent runtime 以父身份取消运行中的子代理子孙(持久化血缘、subagent 来源、任意深度、从不包括 fork)。每个请求各自兜住,一个抛错的子代理或任务不会让其余的继续跑。Schedule 插件在与工具相同的串行队列的一个槽位里删除该 Session 已存储的全部活动宿主任务([归档准入读取已存储的任务](2026-09-22-archive-admission-reads-stored-tasks.zh.md))。它读已存储的行,而不是对会话日志做 runtime fold,因为宿主任务比其 Session 的 Agent 活得更久,是到期提醒唯一能被看见的地方。每个提供方只拥有它本来就有的词汇:Agent 注册表认识回合,任务接缝认识任务,Subagent runtime 认识子代理,Schedule 插件认识提醒;API Session Controller 只保留已归档血缘的步骤门禁。没有新事件类型,也不在别的所有者的回合内写入,因此恢复后的 Session 从一份正常收尾的日志继续,取消归档不会带回任何被停止的东西。 -- **已归档即不跑模型步。** API Session Controller 的 `agent/pre-step` 监听器拒绝为已归档 Session 或其子代理子孙提出的步骤,loop 以 `blocked` 收口且不发请求。这封住了迟到的唤醒投递——子代理结算、排队的 follow-up、在活动作答与写入之间开始的回合——跑出隐藏回合的窗口,也让无视 cancel 的子代理无法替一个谁也看不见的父级干活;取消归档即为整条血缘解除门禁。 +- **停止即用户的停止。** Agent 注册表用 `agent.cancel({ kind: 'user' })` 取消回合——与停止按钮同一条路径,因此被打断的工具调用以 `tool/result` 收口、回合以 `aborted` 结束,但不带按钮的 `keepInbox`,因此排队输入被丢弃并记录一次收件箱拼接。任务注册表接缝 kill 所属任务,由其构造函数只通过抽象的 `list` 与 `kill` 为每个实现安装。Subagent runtime 通过各 Activation 已验证的祖先关系报告并取消运行中的后代,非托管 Agent 使用在线 header 血缘(任意深度,从不包括 fork)。释放创建者不会抹去后代的归属。每个请求各自兜住,一个抛错的子代理或任务不会让其余的继续跑。Schedule 插件在与工具相同的串行队列的一个槽位里删除该 Session 已存储的全部活动宿主任务([归档准入读取已存储的任务](2026-09-22-archive-admission-reads-stored-tasks.zh.md))。它读已存储的行,而不是对会话日志做 runtime fold,因为宿主任务比其 Session 的 Agent 活得更久,是到期提醒唯一能被看见的地方。每个提供方只拥有它本来就有的词汇:Agent 注册表认识回合,任务接缝认识任务,Subagent runtime 认识子代理,Schedule 插件认识提醒;API Session Controller 只保留已归档血缘的步骤门禁。没有新事件类型,也不在别的所有者的回合内写入,因此恢复后的 Session 从一份正常收尾的日志继续,取消归档不会带回任何被停止的东西。 +- **已归档即不跑模型步。** API Session Controller 在 `agent/pre-step` 中检查已归档 Session 和可用的 header 血缘。Subagent runtime 在同一事件中检查每个托管 Agent 保留的创建祖先;中间创建者可以离线。两者都会拒绝该步骤,loop 以 `blocked` 收口且不发请求。这封住了迟到的唤醒投递——子代理结算、排队的 follow-up、在活动作答与写入之间开始的回合——跑出隐藏回合的窗口,也让无视 cancel 的子代理无法替一个谁也看不见的父级干活;取消归档即为整条血缘解除门禁。 - **拒绝即确认。** 侧栏先发普通归档;静止的 Session 一如既往无对话框直接归档。`workspace/session-active` 拒绝会打开"停止并归档"对话框,其清单来自宿主的答案而非客户端对运行状态的镜像,因此对话框列出的正是宿主将要停止的内容。确认后带 `stopActivity` 重发;提示提供撤销,撤销只恢复 Session,不会让被停止的工作继续。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.i18n.yaml b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.i18n.yaml index cc02859b0e..b242ae38e1 100644 --- a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.i18n.yaml @@ -6,14 +6,14 @@ en: 8be4b1d210d5d8bf zh: e9124b48467818b3 /agent-note-archive-admission-reads-the-stored-tasks/problem: - en: 093de39b40f7cc97 - zh: 50c712bde174bc96 + en: 4e5bdccf5388d0e5 + zh: 29e68a698f1fa746 /agent-note-archive-admission-reads-the-stored-tasks/decision: - en: afbf818442c0794a - zh: 4749e63d9757bbbb + en: fa45f421aab1315c + zh: d8982ea5833d3770 /agent-note-archive-admission-reads-the-stored-tasks/alternatives-considered: - en: 099360f2c97a50ea - zh: eac4746c4602f152 + en: b38b58e4d91b66ac + zh: f9c7253ffa94d76c /agent-note-archive-admission-reads-the-stored-tasks/consequences: - en: cb2883b34c2c73fa - zh: 9bb1489c9711cf99 + en: b034eb6ea31341b9 + zh: f78029ff55addc4e diff --git a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.md b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.md index 2073ae420d..06a429efe4 100644 --- a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.md +++ b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.md @@ -8,20 +8,20 @@ English | [中文](2026-09-22-archive-admission-reads-stored-tasks.zh.md) Archive admission asks every provider what still runs for a Session before the archive is written, and a stop-archive then asks those providers to end it ([archiving a Session with running work](2026-09-21-archive-stops-running-session-work.md)). The Schedule provider answered from its owned runtime's fold of the live Session log, so only a Session with a live Agent reported the `schedule` family, and the stop deleted through the management `delete` path. -Host tasks are stored in the Schedule domain document and outlive their Session's Agent ([the storage decision](../architecture/2026-09-16-host-schedule-storage.md)), so that fold no longer exists: `ScheduleRuntime.activeRecords()` is gone, and the stored task table is the only place a due reminder can be seen. A cold Session whose stored rows were still armed therefore reported nothing, archived without the confirmation dialog the running case asks for, and nobody was told which reminder the Host would keep. +Host tasks are stored in the Schedule domain and outlive their Session's Agent ([the storage decision](../architecture/2026-09-16-host-schedule-storage.md)), so that fold no longer exists: `ScheduleRuntime.activeRecords()` is gone, and the stored task table is the only place a due reminder can be seen. A cold Session whose stored rows were still armed therefore reported nothing, archived without the confirmation dialog the running case asks for, and nobody was told which reminder the Host would keep. ## Decision -The Schedule provider answers archive admission from the stored Host task rows, and a stop deletes them. `workspace/session-activity` reads `list({ sessionId })` — the stored rows whose binding is that Session and whose status is active — reports them as the `schedule` family, one item per task with its stored id and title, and prepends that family to `next()` so every other provider keeps its entries. `workspace/session-stop` removes those rows directly inside one slot of the same serialized queue the tools use, so a stop is ordered behind a create whose write is still in flight and cannot miss the row that create is about to commit; it attempts every row, because a row left armed would still fire, and it notifies observers for the rows that landed before the first failure reaches the caller. Session liveness is never consulted: an idle or cold Session whose stored rows are armed refuses the archive, and the confirmation dialog names exactly those reminders. Both listeners are registered in one effect named `schedule.archiveAdmission()`, so unloading the plugin withdraws them together. +The Schedule provider answers archive admission from the stored Host task rows, and a stop deletes them. `workspace/session-activity` reads the stored tasks whose status is active and whose `session` or reserved `new_once` target has the matching Session id, reports them as the `schedule` family, one item per task with its stored id and title, and prepends that family to `next()` so every other provider keeps its entries. `workspace/session-stop` removes those rows in one `deleteMany` batch inside one slot of the same serialized queue the tools use, so a stop is ordered behind a create whose write is still in flight and cannot miss the row that create is about to commit. A successful nonempty batch announces `schedule/changed`, re-drives the timer once, and queues deletion notices for other loaded involved Agents. Session liveness is never consulted: an idle or cold Session whose stored rows are armed refuses the archive, and the confirmation dialog names exactly those reminders. Both listeners are registered in one effect named `schedule.archiveAdmission()`, so unloading the plugin withdraws them together. ## Alternatives considered -**Report the `schedule` family from live Sessions only.** The stored tasks are authoritative and outlive their Session's Agent, so consulting liveness would let a cold Session with armed rows archive silently, and its due row then dispatches into a turn the gate ends as `blocked`, consuming the occurrence without a model step. The admission answer costs one table read either way. +**Report the `schedule` family from live Sessions only.** The stored tasks are authoritative and outlive their Session's Agent, so consulting liveness would let a cold Session with armed rows archive silently; its due delivery then rejects the archived destination. The admission answer costs one table read either way. -**Delete each row through the public management `delete` path.** Re-entering the serialized queue from inside the slot that already holds it deadlocks, so the stop removes the rows itself: the same durable change, with one notification and one timer re-drive per stop instead of one per row. +**Delete each row through the `delete` action of public `edit`.** Re-entering the serialized queue from inside the slot that already holds it deadlocks, so the stop removes the rows itself: the same durable change, with one `schedule/changed` notification and one timer re-drive per stop instead of one per row. -**Keep a runtime-side mirror of the Session's active tasks.** A mirror duplicates the authoritative document, drifts after a restart, and disappears with the Agent — the exact case admission must still answer for. +**Keep a runtime-side mirror of the Session's active tasks.** A mirror duplicates the authoritative store, drifts after a restart, and disappears with the Agent — the exact case admission must still answer for. ## Consequences -Admission costs one stored-table read, and a Session with no live Agent can refuse the archive: a Session that looks quiet may now ask for confirmation because its stored reminders are armed. A stop deletes rows one at a time — the domain table offers no batch delete — so a failure partway leaves the earlier deletes committed; observers hear about those, every row was attempted, and the first failure still reaches the caller. One residue follows. A crash between the archive write and the stop leaves stored rows armed in an archived Session: unarchiving shows them again, and when such a row's target passes the Schedule runtime selects it on its own timer and resolves the Session's Agent itself — that resolution is ungated, and only `agent/pre-step` refuses the model step — so a one-shot dispatches a follow-up into a turn the gate ends as `blocked` and that occurrence is consumed without a model step. The seam itself is unchanged: the workspace package still knows no Schedule vocabulary, and this provider owns only reminders. +Admission costs one stored-table read, and a Session with no live Agent can refuse the archive: a Session that looks quiet may now ask for confirmation because its stored reminders are armed. A stop uses one domain `deleteMany` batch. A normal write failure preserves every row; an `unknown-state` failure may have removed rows and quarantines the domain until it is reopened. Either failure announces `schedule/changed` so observers reread and then reaches the caller. A crash between the archive write and the stop can leave stored rows armed in an archived Session; delivery rejects with `schedule/target-archived` before enqueue, without writing a receipt or consuming the occurrence. The seam itself is unchanged: the workspace package still knows no Schedule vocabulary, and this provider owns only reminders. diff --git a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.zh.md b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.zh.md index c95fb280c3..c83ff1c896 100644 --- a/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.zh.md +++ b/.agents/notes/implemented/feature/2026-09-22-archive-admission-reads-stored-tasks.zh.md @@ -8,20 +8,20 @@ 归档准入在写入归档前询问每个提供方:该 Session 还有什么在跑;随后「停止并归档」再要求它们结束这些工作([归档仍有工作在跑的 Session](2026-09-21-archive-stops-running-session-work.zh.md))。Schedule 提供方原先回答的是其归属 runtime 对活会话日志的 fold,因此只有带活 Agent 的 Session 才报告 `schedule` 族,停止也走管理 `delete` 路径。 -宿主任务存储在 Schedule 领域文档中,且比其 Session 的 Agent 活得更久([存储决策](../architecture/2026-09-16-host-schedule-storage.zh.md)),因此那个 fold 已不存在:`ScheduleRuntime.activeRecords()` 已经移除,已存储的任务表是到期提醒唯一能被看见的地方。存储行仍被武装的冷 Session 因此什么也不报告,归档时不会弹出运行态才会弹出的确认对话框,也没有人被告知宿主会继续保留哪条提醒。 +宿主任务存储在 Schedule 领域中,且比其 Session 的 Agent 活得更久([存储决策](../architecture/2026-09-16-host-schedule-storage.zh.md)),因此那个 fold 已不存在:`ScheduleRuntime.activeRecords()` 已经移除,已存储的任务表是到期提醒唯一能被看见的地方。存储行仍被武装的冷 Session 因此什么也不报告,归档时不会弹出运行态才会弹出的确认对话框,也没有人被告知宿主会继续保留哪条提醒。 ## 决策 -Schedule 提供方从已存储的宿主任务行回答归档准入,并由停止删除这些行。`workspace/session-activity` 读取 `list({ sessionId })`——绑定到该 Session 且状态为活动的已存储行——把它们作为 `schedule` 族报告,每条任务一项、携带其已存储 id 与 title,并把该族前插到 `next()` 的结果之前,使其他提供方保留各自条目。`workspace/session-stop` 在与工具相同的串行队列的一个槽位里直接删除这些行,因此停止会排在写入尚未完成的创建之后,不会漏掉那个创建即将提交的行;它会尝试每一行,因为留下的行仍会触发;对已经落地的行先通知观察者,再把首个失败交给调用方。是否存活从不参与判断:存储行仍被武装的空闲或冷 Session 会拒绝归档,确认对话框会准确列出这些提醒。两个监听器注册在同一个名为 `schedule.archiveAdmission()` 的 effect 中,卸载插件即一并撤回。 +Schedule 提供方从已存储的宿主任务行回答归档准入,并由停止删除这些行。`workspace/session-activity` 读取状态为活动且 `session` 或预留的 `new_once` 目标的 `sessionId` 与该 Session 匹配的已存储任务,把它们作为 `schedule` 族报告,每条任务一项、携带其已存储 id 与 title,并把该族前插到 `next()` 的结果之前,使其他提供方保留各自条目。`workspace/session-stop` 在与工具相同的串行队列的一个槽位里通过一次 `deleteMany` 批量写入删除这些行,因此停止会排在写入尚未完成的创建之后,不会漏掉那个创建即将提交的行。非空批量写入成功后发出 `schedule/changed`,重算计时器一次,并向其他已加载的相关 Agent 排入删除通知。是否存活从不参与判断:存储行仍被武装的空闲或冷 Session 会拒绝归档,确认对话框会准确列出这些提醒。两个监听器注册在同一个名为 `schedule.archiveAdmission()` 的 effect 中,卸载插件即一并撤回。 ## 已考虑的备选 -**只由活着的 Session 报告 `schedule` 族。** 已存储的任务才是权威,且比其 Session 的 Agent 活得更久,因此以存活为条件会让存储行被武装的冷 Session 静默归档,其到期行随后投递进一个被门禁以 `blocked` 收口的回合,在没有模型步的情况下消耗掉这次触发。两种做法在准入上都只需一次读表。 +**只由活着的 Session 报告 `schedule` 族。** 已存储的任务才是权威,且比其 Session 的 Agent 活得更久,因此以存活为条件会让存储行被武装的冷 Session 静默归档;其到期投递随后因目标已归档而被拒绝。两种做法在准入上都只需一次读表。 -**每行都走公开的管理 `delete` 路径删除。** 在已经持有该槽位的串行队列内部再次进入队列会自锁,因此停止自己删行:同样的持久化变更,每次停止一次通知、一次计时器重算,而不是每行各一次。 +**每行都通过公开 `edit` 的 `delete` 操作删除。** 在已经持有该槽位的串行队列内部再次进入队列会自锁,因此停止自己删行:同样的持久化变更,每次停止一次 `schedule/changed` 通知、一次计时器重算,而不是每行各一次。 -**在 runtime 侧保留该 Session 活动任务的镜像。** 镜像会重复权威文档、在重启后漂移、并随 Agent 一起消失——而这正是准入必须仍能回答的情形。 +**在 runtime 侧保留该 Session 活动任务的镜像。** 镜像会重复权威存储、在重启后漂移、并随 Agent 一起消失——而这正是准入必须仍能回答的情形。 ## 后果 -准入的代价是一次读已存储的表,而没有活 Agent 的 Session 也能拒绝归档:看起来安静的 Session 现在可能因为其已存储提醒仍被武装而要求确认。停止逐行删除——领域表不提供批量删除——因此删到一半失败时,先前删除已提交;观察者会被告知这些,每一行都已被尝试,首个失败仍交给调用方。由此剩下一处残余:在归档写入与停止之间崩溃,会在已归档的 Session 里留下仍被武装的已存储行;取消归档时它们再次出现;当这类行的目标时刻过去,Schedule runtime 会按自己的定时器选中它并自行 resolve 该 Session 的 Agent——这一步没有门禁,只有 `agent/pre-step` 拒绝模型步——一次性提醒于是把 follow-up 投递进一个被门禁以 `blocked` 收口的回合,该次触发在没有模型步的情况下被消耗。接缝本身未变:workspace 包仍然不认识 Schedule 词汇,而这个提供方只拥有提醒。 +准入的代价是一次读已存储的表,而没有活 Agent 的 Session 也能拒绝归档:看起来安静的 Session 现在可能因为其已存储提醒仍被武装而要求确认。停止使用一次领域 `deleteMany` 批量写入。正常写入失败保留全部行;`unknown-state` 失败可能已移除行,并隔离领域直到重新打开。两种失败均发出 `schedule/changed`,让观察方重读,再交给调用方。在归档写入与停止之间崩溃,仍可能在已归档的 Session 中留下仍被武装的已存储行;投递在入队前以 `schedule/target-archived` 拒绝,不写入回执,也不消耗该次发生时点。接缝本身未变:workspace 包仍然不认识 Schedule 词汇,而这个提供方只拥有提醒。 diff --git a/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.i18n.yaml b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.i18n.yaml new file mode 100644 index 0000000000..4cb149615f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.i18n.yaml @@ -0,0 +1,25 @@ +# Bilingual-pair consistency record for 2026-09-28-apply-patch-file-editing.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.md +/agent-note-apply-patch-file-editing: + en: 2ff887cb8deab0eb + zh: b503b00d8690955c +/agent-note-apply-patch-file-editing/problem: + en: de9b76d89795ccec + zh: 588d45b7d9ca9582 +/agent-note-apply-patch-file-editing/decision: + en: e3e174513948d0dd + zh: 80b13d7e40d38dee +/agent-note-apply-patch-file-editing/alternatives-considered: + en: fb743c9558cf24ed + zh: e74bdfff00dea417 +/agent-note-apply-patch-file-editing/consequences: + en: b58b7324663c3c90 + zh: 649c18a83e33e71d +/agent-note-apply-patch-file-editing/testing: + en: 82ae0a96fbae53bc + zh: 9a8194bdb134ae8c +/agent-note-apply-patch-file-editing/deferred: + en: 9fa35fed544d9a9d + zh: 32fced0939325341 diff --git a/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.md b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.md new file mode 100644 index 0000000000..1b911eba1c --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.md @@ -0,0 +1,47 @@ +# Agent Note: Apply patch file editing + +Status: implemented + +English | [中文](2026-09-28-apply-patch-file-editing.zh.md) + +## Problem + +A model editing several files or separated regions needs multiple literal-edit calls or a shell script. Shell and Python edits do not expose filesystem mutation intents, so a working directory without Git cannot reliably present those edits in the turn Review tab. A patch tool expresses related edits in one call while retaining guarded filesystem operations. #5121 asks for the capability and its effectiveness evaluation; #4556 supplies the broader motivation for efficient file editing. + +## Decision + +`apply_patch` accepts one Codex-style patch for add, update, delete, and move operations, including multiple files and hunks. The pure [dsh-fs-patch library](../../../../packages/fs/fs-patch/README.md) follows Codex `rust-v0.158.0` parsing, sequential matching, whitespace tolerance, and `NormalizeToLf` reconstruction; the matcher receives LF text only, so Codex `PreserveLineEndings` is not implemented. + +The [filesystem service](../../../../packages/fs/fs/README.md) exposes `patchText`, `deleteFile`, and `moveFile`; local, sandboxed, and SSH providers implement them. `fs/delete-intent` requires the same present observation as `fs/edit-intent`, while move destinations use `fs/write-intent`. Version guards and sandbox enforcement remain with the provider. A move publishes its destination before deleting its source, and `sourceDeleted` distinguishes a completed move from a published destination whose source could not be removed. + +The [tool executor](../../../../packages/fs/tool-fs/README.md) resolves paths and simulates expected state during whole-patch preflight, including repeated paths and moves, without writing files; a refused preflight commits nothing. Commit reobtains observation guards for each operation and stops at the first failure or cancellation without rollback. After an I/O or cancellation failure, a `stat` comparison checks whether every affected target retains its prior version; changed state or a failed comparison produces `unknown`, which requires rereading before retry. Reports retain completed, failed, unknown, and skipped operations, including a partially published move. + +Commit reports return `isError: false` so completed diff metadata survives a stopped patch; their operation statuses and stopped flag expose the failure. Syntax and preflight rejection produce tool errors. Successful move summaries use `M `. Applied diff paths use canonical absolute `processPath` for client navigation, while operation records retain display paths and unresolved paths keep their patch spelling. + +[Review capture](../../../../packages/deliverables/workspace-changes/README.md) uses filesystem intent listeners, not argument parsing. `tools/pre-execute` associates the execution with its turn recorder; prepended write, edit, and delete listeners first await the policy decision, then await capture before provider mutation. Moves capture both endpoints. Each turn retains its first baseline and compares actual final bytes, so repeated edits yield one net diff and reverted changes disappear. Existing size, count, time, location, and Session-lifetime limits remain. + +`tool-fs.applyPatch` defaults to `false`; each shipped `tool-fs` row that enables `edit` states its own value, so turning the tool on or off is one line per composition, or a profile patch on the `tool-fs` id where no preset owns the row. The tool consults the `fs/*` intent waterfalls like `write` and `edit`, so a mounted observation policy requires a prior read and rejects stale versions for every patch operation. The shipped values of those rows and of the `fs-observation-policy` row are decided by [Shipped filesystem mutation defaults](2026-10-29-shipped-fs-mutation-defaults.md), which supersedes this note's opt-in baseline. The schema names its argument `input` as the Codex tool does: across 2,226 recorded DS-Bench and DeepSWE rollouts, 14% of `apply_patch` calls arrived with that key and were rejected while the argument was named `patch`. The tool registers its schema, guidance, native/PTC execution, and tool presentation through plugin effects; the agent loop is unchanged. + +## Alternatives considered + +**Keep using shell or Python for patches.** This leaves non-Git changes without filesystem intent capture and does not provide the requested model-facing editing tool. + +**Reuse Codex markers with an independently strict matcher.** This reduces initial implementation work but makes familiar patches fail differently. A pinned Codex parser and matcher make deviations reviewable; Harness policies stay explicit. + +**Make the whole patch transactional.** Cross-file rollback adds recovery state and can overwrite concurrent external edits. Preflight and ordered commits reject known failures early and expose partial results without promising rollback. + +**Expand Review while adding the tool.** Rename presentation, persistent storage, SSH capture, and capture-failure policy are independent product decisions; existing whole-file capture and rendering cover this integration. + +**Register the tool by default wherever `write` and `edit` are both enabled.** This would add a schema and a guidance section to every default model request and change every recorded request expectation before the tool's effect on ordinary sessions is measured; the explicit switch keeps the baseline composition unchanged and lets comparison runs opt in. The shipped defaults were decided afterwards in [Shipped filesystem mutation defaults](2026-10-29-shipped-fs-mutation-defaults.md). + +## Consequences + +One call can express related edits. A composition that enables the switch includes another tool schema and its guidance, so its recorded request expectations differ from a composition without it. Preflight cannot prevent a later conflict, cancellation, or storage failure; callers inspect operation statuses before retrying. Permissive upstream matching remains pinned and tested rather than tightened. Provider implementations and external subclasses must support three additional operations, and partial moves require handling both endpoints. + +## Testing + +Parser and matcher fixtures cover the pinned syntax, whitespace, repeated contexts, and EOF behavior. Provider and executor tests cover observation, version and sandbox refusals, repeated paths, partial moves, cancellation, and uncertain outcomes. The real-tool Review matrix runs with no repository and with Git unavailable, checking all operation kinds, first-to-last baselines, rejected edits, partial publication, reverted changes, capture ordering, malformed syntax, and path aliases. Real model Session recordings cover successful updates, read-policy rejection and retry, and partial execution; deterministic cancellation stays in executor tests. + +## Deferred + +SSH Review, closing-prose file references for `apply_patch`, and Codex `PreserveLineEndings`. diff --git a/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.zh.md b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.zh.md new file mode 100644 index 0000000000..6948abe0ea --- /dev/null +++ b/.agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.zh.md @@ -0,0 +1,47 @@ +# Agent Note: apply_patch 文件编辑 + +Status: implemented + +[English](2026-09-28-apply-patch-file-editing.md) | 中文 + +## 问题 + +模型编辑多个文件或分离区域时,需要多次字面量编辑调用或 shell 脚本。shell 和 Python 编辑不发出文件系统修改 intent,因此没有 Git 的工作目录无法在轮次 Review tab 中可靠呈现这些修改。补丁工具用一次调用表达相关编辑,同时保留受保护的文件系统操作。#5121 要求实现能力并评测效果;#4556 提供高效文件编辑的更广泛动机。 + +## 决策 + +`apply_patch` 接收一份 Codex 风格补丁,支持新增、更新、删除和移动,以及多个文件和 hunk。[dsh-fs-patch 纯库](../../../../packages/fs/fs-patch/README.zh.md)遵循 Codex `rust-v0.158.0` 的解析、顺序匹配、空白容忍和 `NormalizeToLf` 重建。匹配器只接收 LF 文本,因此不实现 Codex `PreserveLineEndings`。 + +[文件系统服务](../../../../packages/fs/fs/README.zh.md)提供 `patchText`、`deleteFile` 和 `moveFile`;本地、沙箱和 SSH 提供方均实现它们。`fs/delete-intent` 与 `fs/edit-intent` 要求相同的存在观察,移动目标使用 `fs/write-intent`。版本防护和沙箱约束仍由提供方负责。移动先发布目标,再删除源;`sourceDeleted` 区分已完成的移动与目标已发布但源未能删除的情况。 + +[工具执行器](../../../../packages/fs/tool-fs/README.zh.md)在整份补丁预检时解析路径并模拟预期状态,包括重复路径和移动,不写入文件;预检拒绝时没有提交。提交时为每条操作重新获取观察防护,在首次失败或取消时停止,不回滚。I/O 或取消失败后,`stat` 比较检查所有受影响目标是否仍保持先前版本;状态变化或比较失败会产生 `unknown`,要求重试前重新读取。报告保留已完成、失败、未知和跳过的操作,包括部分发布的移动。 + +提交报告返回 `isError: false`,让已完成的 diff 元数据在补丁中止后仍被保留;操作状态和 stopped 标记暴露失败。语法和预检拒绝产生工具错误。成功移动的摘要使用 `M `。已应用 diff 的路径采用规范绝对 `processPath`,供客户端导航使用;操作记录保留显示路径,未解析的路径保留补丁原始写法。 + +[Review 采集](../../../../packages/deliverables/workspace-changes/README.zh.md)使用文件系统 intent 监听器,不解析参数。`tools/pre-execute` 将执行关联到轮次记录器;前置的 write、edit 和 delete 监听器先等待策略决策,再等待捕获完成,然后提供方才修改文件。移动捕获两端。每轮保留首次基线,比较实际最终字节,因此重复编辑形成一份净 diff,还原的变化不再显示。现有大小、数量、时间、位置和 Session 生命周期限制保持适用。 + +`tool-fs.applyPatch` 默认为 `false`;每个启用 `edit` 的随发行版交付的 `tool-fs` 行都显式写出自己的值,因此开关该工具是每个组合一行改动,没有 preset 拥有该行时可通过针对 `tool-fs` id 的 profile patch 开启。该工具像 `write` 和 `edit` 一样咨询 `fs/*` intent waterfall,因此已挂载的观察策略对每个补丁操作要求先读并拒绝过期版本。这些行以及 `fs-observation-policy` 行随发行版交付的值由[随发行版交付的文件系统修改默认值](2026-10-29-shipped-fs-mutation-defaults.zh.md)决定,该 Note 取代本 Note 的 opt-in 基线。schema 沿用 Codex 的参数名 `input`:在 2,226 条 DS-Bench 与 DeepSWE 录制轨迹中,14% 的 `apply_patch` 调用带着这个键发出,而参数名为 `patch` 时它们都被拒绝。工具通过插件 effect 注册 schema、指导文本、native/PTC 执行与调用展示;不修改 agent loop(智能体循环)。 + +## 考虑过的替代方案 + +**继续使用 shell 或 Python 打补丁。** 这使非 Git 修改缺少文件系统 intent 采集,也不能提供所需的模型文件编辑工具。 + +**复用 Codex 标记但采用独立的严格匹配器。** 这能减少初期实现工作,但会让熟悉的补丁以不同方式失败。固定 Codex 解析器和匹配器使偏差可审查;Harness 策略继续显式存在。 + +**将整份补丁做成事务。** 跨文件回滚增加恢复状态,还可能覆盖并发外部修改。预检和顺序提交可以提早拒绝已知失败,并公开部分结果,而不承诺回滚。 + +**加入工具时同时扩展 Review。** 重命名展示、持久存储、SSH 采集和捕获失败策略是独立产品决策;既有整文件采集和展示覆盖本次接入。 + +**在同时启用 `write` 与 `edit` 的地方默认注册该工具。** 这会在尚未衡量该工具对普通会话的影响之前,给每个默认模型请求增加一个 schema 和一段指导文本,并改变所有录制请求的预期;显式开关保持基线组合不变,让对比评测自行选择开启。随发行版交付的默认值随后在[随发行版交付的文件系统修改默认值](2026-10-29-shipped-fs-mutation-defaults.zh.md)中决定。 + +## 后果 + +一次调用可以表达相关编辑。开启该开关的组合会包含额外的工具 schema 及其指导文本,因此其录制请求的预期与未开启的组合不同。预检不能阻止之后的冲突、取消或存储失败;调用方在重试前检查操作状态。上游宽松匹配保持固定版本并受到测试约束,不会被收紧。提供方实现和外部子类必须支持三个新增操作,部分移动要求处理两端状态。 + +## 测试 + +解析器和匹配器 fixture 覆盖固定版本的语法、空白、重复上下文与 EOF 行为。提供方和执行器测试覆盖观察、版本和沙箱拒绝、重复路径、部分移动、取消和未知结果。真实工具 Review 矩阵分别在无仓库和 Git 不可用环境运行,检查所有操作类型、首末基线、被拒编辑、部分发布、还原变化、采集顺序、无效语法与路径别名。真实模型 Session 录制覆盖成功更新、读取策略拒绝后重试与部分执行;确定性取消保留在执行器测试中。 + +## 延期工作 + +SSH Review、`apply_patch` 的收尾文案文件引用,以及 Codex `PreserveLineEndings`。 diff --git a/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.i18n.yaml b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.i18n.yaml new file mode 100644 index 0000000000..7a918c2500 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-10-29-shipped-fs-mutation-defaults.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.md +/agent-note-shipped-filesystem-mutation-defaults: + en: ca322529f759f46a + zh: a8881e2284631255 +/agent-note-shipped-filesystem-mutation-defaults/problem: + en: 57dcac3bdbcf1c21 + zh: f5bf64888e6dd973 +/agent-note-shipped-filesystem-mutation-defaults/decision: + en: bcdaca6bff9411b7 + zh: 7adfc3a9b9d8853b +/agent-note-shipped-filesystem-mutation-defaults/alternatives-considered: + en: 1249a7868ff2a069 + zh: 739f191121bf5293 +/agent-note-shipped-filesystem-mutation-defaults/consequences: + en: 3def7f0443b41d34 + zh: 70df709d1fcbe8fa +/agent-note-shipped-filesystem-mutation-defaults/testing: + en: 625a8af588dc0ba8 + zh: 9d489f1bbed14fb3 diff --git a/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.md b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.md new file mode 100644 index 0000000000..542c4fd7ea --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.md @@ -0,0 +1,32 @@ +# Agent Note: Shipped filesystem mutation defaults + +Status: implemented + +English | [中文](2026-10-29-shipped-fs-mutation-defaults.zh.md) + +## Problem + +[Apply patch file editing](2026-09-28-apply-patch-file-editing.md) shipped `apply_patch` opt-in and kept `dsh-fs-observation-policy` mounted, so every base-backed profile refused `write`, `edit`, and `apply_patch` on a file the model had not read or that had changed since the read. Benchmark runs of the shipped compositions with the tool enabled and with the policy disabled were compared against the baseline, and the shipped defaults were decided from those results in discussion between the maintainers. + +## Decision + +- The `dsh-base` `tool-fs` row (headless, SDK, and ACP) and the Web `standard` preset state `applyPatch: true`. The Web `ptc` and `cordis` presets state `applyPatch: false`, and the shipped [PTC overlay](../../../../apps/cli/config/examples/ptc.yml) sets the same on the base row, so the SDK and Desktop PTC tool sets stay equal without a parity exception. +- The `dsh-base` `fs-observation-policy` row ships `disabled: true`. Every mutating tool in a base-backed profile runs against the bare provider: `write` overwrites, `edit` replaces the unique literal match, and `apply_patch` applies hunks on context match alone. A deployment restores the guard for all three with `disabled: false` on that row. `sdk-minimal` stacks no `dsh-base` and is unaffected. +- The `write` and `edit` guidance keeps asking for a prior read without naming the policy; the `apply_patch` guidance asks for enough hunk context to match one place instead of a prior read. +- The policy package is classified as an optional product package, since no default composition mounts it. The two recordings that capture a policy refusal, `fs-policy-reject` and `apply-patch-rejected`, re-enable the row through a per-scenario `runtime.cordis.yml`; the fixed-budget compaction scenarios pin `applyPatch: false` in both their live and replay patches because their thresholds were tuned to the recorded tool set. + +## Alternatives considered + +**Enable `apply_patch` only in the Web `standard` preset.** The SDK/Desktop parity check compares the SDK profile's `standard` tool set with the Desktop preset, so a Web-only change needs a permanent parity exception for a difference with no product reason; enabling the base row keeps the two equal. + +**Disable the policy for `apply_patch` only.** A `tool-fs` switch that skipped the intent waterfalls for patches alone was built and evaluated, but it left `write` and `edit` under a guard the shipped compositions no longer wanted and added a second configuration axis beside the policy row; disabling the row decides all three tools in one place and keeps the policy package intact for deployments that want it. + +**Enable `apply_patch` in the PTC presets too.** Under PTC the tool is a `run_code` binding rather than a JSON schema, so the cost is small, but the PTC compositions were evaluated without it; the overlay and the Web preset keep the evaluated tool set. + +## Consequences + +Default model requests in base-backed profiles carry the `apply_patch` schema and guidance, so every recorded request expectation outside the fixed-budget compaction scenarios changed. A model can overwrite or edit a file it never read; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md) names the one-line patches that restore the guard or drop the tool. Sandbox confinement, Review capture, and `fs/observed` events are unchanged. + +## Testing + +`tool-fs` unit tests cover the unguarded paths (`policy: false`). The keyless SDK smoke edits an existing file the model never read through the shipped `sdk` profile and checks the bytes on disk. `desktop-tools.expected.e2e.ts` compares the SDK and Desktop `standard` and `ptc` tool sets. The recorded corpus replays with the shipped defaults; `fs-policy-reject` and `apply-patch-rejected` replay with the policy re-enabled. diff --git a/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.zh.md b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.zh.md new file mode 100644 index 0000000000..068077797e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-10-29-shipped-fs-mutation-defaults.zh.md @@ -0,0 +1,32 @@ +# Agent Note: 随发行版交付的文件系统修改默认值 + +状态:implemented + +[English](2026-10-29-shipped-fs-mutation-defaults.md) | 中文 + +## 问题 + +[Apply patch 文件编辑](2026-09-28-apply-patch-file-editing.zh.md)以 opt-in 方式交付 `apply_patch`,并保持 `dsh-fs-observation-policy` 挂载,因此所有叠加 base 的 profile 都会拒绝对模型未读过、或读后已变化的文件执行 `write`、`edit` 与 `apply_patch`。维护者对随发行版交付的组合分别在开启该工具和禁用该策略的情况下跑了 benchmark,与基线比较后讨论得出了随发行版交付的默认值。 + +## 决策 + +- `dsh-base` 的 `tool-fs` 行(headless、SDK、ACP)与 Web 的 `standard` preset 写出 `applyPatch: true`。Web 的 `ptc`、`cordis` preset 写出 `applyPatch: false`,随发行版交付的 [PTC overlay](../../../../apps/cli/config/examples/ptc.yml) 在 base 行上也设为 `false`,因此 SDK 与 Desktop 的 PTC 工具集保持一致,无需一致性例外。 +- `dsh-base` 的 `fs-observation-policy` 行以 `disabled: true` 交付。叠加 base 的 profile 中每个修改工具都直接作用于裸提供方:`write` 覆盖,`edit` 替换唯一的字面匹配,`apply_patch` 只凭上下文匹配应用 hunk。部署在该行上写 `disabled: false` 即可为三者恢复防护。`sdk-minimal` 不叠加 `dsh-base`,不受影响。 +- `write` 与 `edit` 的提示语仍要求先读,但不再点名该策略;`apply_patch` 的提示语要求给每个 hunk 足够的上下文以匹配唯一位置,而非先读。 +- 由于没有默认组合挂载策略包,它被归类为可选产品包。录的是策略拒绝的两个场景 `fs-policy-reject` 与 `apply-patch-rejected` 通过各自的 `runtime.cordis.yml` 把该行开回来;固定 token 预算的压缩场景在 live 与 replay patch 中都钉住 `applyPatch: false`,因为它们的阈值是按录制时的工具集调的。 + +## 考虑过的替代方案 + +**只在 Web `standard` preset 开启 `apply_patch`。** SDK/Desktop 一致性检查会把 SDK profile 的 `standard` 工具集与 Desktop preset 比较,仅改 Web 需要为一个没有产品理由的差异永久保留一致性例外;开启 base 行让两边保持一致。 + +**只对 `apply_patch` 关闭策略。** 曾实现并评测过一个让补丁跳过 intent waterfall 的 `tool-fs` 开关,但它让 `write` 与 `edit` 继续受随发行版交付的组合已不需要的防护,并在策略行之外增加了第二个配置维度;禁用该行在一处决定三个工具,并为需要防护的部署完整保留策略包。 + +**在 PTC preset 中也开启 `apply_patch`。** PTC 下该工具是 `run_code` 内的绑定而非 JSON schema,代价很小,但 PTC 组合是在没有它的情况下评测的;overlay 与 Web preset 保持评测时的工具集。 + +## 后果 + +叠加 base 的 profile 的默认模型请求带有 `apply_patch` schema 与提示语,因此固定预算压缩场景之外的所有录制请求预期都变化了。模型可以覆盖或编辑从未读过的文件;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md)给出恢复防护或去掉该工具的一行 patch。沙箱围栏、Review 采集与 `fs/observed` 事件不变。 + +## 测试 + +`tool-fs` 单元测试覆盖无防护路径(`policy: false`)。keyless SDK smoke 通过随发行版交付的 `sdk` profile 对模型从未读过的既有文件执行 edit 并检查磁盘字节。`desktop-tools.expected.e2e.ts` 比较 SDK 与 Desktop 的 `standard` 和 `ptc` 工具集。录制 corpus 以随发行版交付的默认值回放;`fs-policy-reject` 与 `apply-patch-rejected` 在策略开回的情况下回放。 diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml index 9e538f26c6..970eaf9557 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.i18n.yaml @@ -9,8 +9,8 @@ en: dc43ba84345e1405 zh: dbc03572ab7710d2 /agent-note-ship-optional-bundles-with-the-installation/decision: - en: 2f20e356517715a6 - zh: 35c7ff8c4cd8a712 + en: 0f3e0daee65b6510 + zh: 2e9c8000da75fb6c /agent-note-ship-optional-bundles-with-the-installation/alternatives-considered: en: 95b48b61757f1f13 zh: e9fb2d6ea492a4bc diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md index 74f824fc88..aaa055f7b5 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.md @@ -14,7 +14,6 @@ The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bu Default-product isolation keeps its rules with one declared exception: an optional bundle's dependency graph is outside the default product. The static gate skips the `dependencies` edge from `@deepseek-ai/dsh` to a listed bundle and still rejects a runtime import, a shipped composition, a preset, or a default template that names it, an experimental dependency the list does not name, and a listed name that is not a runtime dependency or not a bundle. The workspace-constraints check accepts the same `dependencies` edges and no other runtime section, and the packed-install release check skips them from the installed entry package while requiring each listed bundle to be installed. -The [single-bundle reference](../../../../packages/experimental/agent-team-profile/README.md) supersedes the two Agent Teams selections with one `@deepseek-ai/dsh-experimental-agent-team-profile` selection. This note retains the installation-owned optional-bundle policy; the [optional-bundle decision for experimental capabilities](../architecture/2026-09-21-experimental-capabilities-as-optional-bundles.md) owns composition and display metadata; `OPTIONAL_BUNDLES` owns the current shipped list. ## Alternatives considered diff --git a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md index 129f76c454..6135f08763 100644 --- a/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md +++ b/.agents/notes/implemented/process/2026-09-15-shipped-optional-bundles.zh.md @@ -14,7 +14,6 @@ Web 插件页只管理用户装进 profile 的组合包。像 Agent Teams 这样 默认产品隔离的规则保持不变,只声明一个例外:可选组合包的依赖图在默认产品之外。静态门禁跳过从 `@deepseek-ai/dsh` 到列表中组合包的 `dependencies` 边,仍然拒绝运行时 import、随附组合、preset 或默认模板对它的引用,拒绝列表没有点名的实验依赖,也拒绝不是运行时依赖或不是组合包的列表项。workspace 约束检查接受同样的 `dependencies` 边而不接受其他运行时依赖段;发布时的 packed-install 检查对已安装入口包跳过这些边,并要求列表中的每个组合包都已安装。 -[单组合包参考](../../../../packages/experimental/agent-team-profile/README.zh.md)将两个 Agent Teams 选项替换为一个 `@deepseek-ai/dsh-experimental-agent-team-profile` 选项。本记录保留由安装方决定可选组合包的策略;[实验能力的可选 bundle 决策](../architecture/2026-09-21-experimental-capabilities-as-optional-bundles.zh.md)定义组合与显示元数据;当前随附名单由 `OPTIONAL_BUNDLES` 管理。 ## 考虑过的替代方案 diff --git a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.i18n.yaml b/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.i18n.yaml deleted file mode 100644 index f830391e86..0000000000 --- a/.agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.i18n.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# Bilingual-pair consistency record for 2026-09-26-team-direct-inbox.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-09-26-team-direct-inbox.md -/agent-note-team-messages-use-the-target-inbox: - en: ae17b789652784b5 - zh: fa462ace95c8cdaa -/agent-note-team-messages-use-the-target-inbox/problem: - en: 83296699f94c77d3 - zh: e681a426bf0a703a -/agent-note-team-messages-use-the-target-inbox/decision: - en: 8d5fed34f19c7302 - zh: 25417793d3797775 -/agent-note-team-messages-use-the-target-inbox/alternatives-considered: - en: e847556d8e9f1071 - zh: bf1abe2f0e201eac -/agent-note-team-messages-use-the-target-inbox/consequences: - en: 24085acb09438dc8 - zh: 27c92e8de8cf7dbe diff --git a/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.i18n.yaml b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.i18n.yaml new file mode 100644 index 0000000000..3c03e11100 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-29-inbox-only-agent-wait.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.md +/agent-note-inbox-only-agent-waits: + en: 8a451f9706af8dea + zh: 9818b5abdee12a9c +/agent-note-inbox-only-agent-waits/problem: + en: 7a6e28745bda3305 + zh: e862166572cb9a9f +/agent-note-inbox-only-agent-waits/decision: + en: 553a1e166dd7e7e9 + zh: c05f16577fa6753c +/agent-note-inbox-only-agent-waits/alternatives-considered: + en: 64a44ad3884a90c3 + zh: 1fffe0c6fd78acbe +/agent-note-inbox-only-agent-waits/consequences: + en: 45b6d456c3ca226c + zh: e9ebacd4b6bcaeca diff --git a/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.md b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.md new file mode 100644 index 0000000000..80e46f63e6 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.md @@ -0,0 +1,31 @@ +# Agent Note: Inbox-only Agent waits + +Status: implemented + +English | [中文](2026-10-29-inbox-only-agent-wait.zh.md) + +## Problem + +A task-board commit changes shared state but does not deliver input to a member. Ending every member's wait on each edit couples ordinary subagent controls to Team coordination and makes callers resume without a message explaining what needs attention. + +## Decision + +`wait_agent` observes only its exact caller's next-step inbox through the existing insertion event. It subscribes before checking pending input, consumes nothing, and removes listeners and timers on input, timeout, cancellation, caller disposal, or tool unload. Queued next-turn input, other Agents' activity, and task-board changes do not end the wait. + +Task commands append and flush their revisions without notifying waits or writing inbox messages. A caller sends an explicit message when a member needs to act on an update. No Agent method, shared waiting service, or task-specific waiting event is introduced. + +This supersedes only the wait-signal decision in [Team task boards](../architecture/2026-10-19-team-task-board-inbox.md). Its tree authority, durable task storage, historical non-authority, and separation from ordinary controls remain applicable. No Session event generation changes. + +## Alternatives considered + +**Notify all current waits after every task commit.** This avoids duplicate inbox state but still makes unrelated task edits interrupt every waiting member. Moving the notification behind a service method retains that behavior and coupling. + +**Persist each task change as a message.** The task journal already preserves revisions; per-member notices add unread state and delivery recovery. Explicit messages communicate which updates require action. + +**Add waiting to Agent or its inbox.** Existing input events and tool-owned cancellation already implement the required wait without extending the core API. + +## Consequences + +Task updates alone do not resume a waiting or idle member. Callers must communicate when work should continue. The tool returns no task contents; members query the board when needed. Task changes before or during a wait have the same effect: none. + +Unit tests cover pending input, caller isolation, concurrent waits, cancellation, disposal, and task commits that leave waits pending. The recorded task-board scenario checks past and concurrent commits against timed-out waits, while completion notification remains ordinary inbox input. diff --git a/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.zh.md b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.zh.md new file mode 100644 index 0000000000..6bf2e39562 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-inbox-only-agent-wait.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 仅等待收件箱的 Agent 等待 + +Status: implemented + +[English](2026-10-29-inbox-only-agent-wait.md) | 中文 + +## 问题 + +任务板提交改变共享状态,但不向成员投递输入。每次编辑都结束所有成员的等待,会使普通 subagent 控制依赖 Team 协调,并让调用者在没有消息说明需要关注什么时恢复执行。 + +## 决策 + +`wait_agent` 仅通过现有插入事件观察当前调用者自己的下一步收件箱。它先订阅再检查待处理输入,不消费输入,并在输入到达、超时、取消、调用者释放或工具卸载时移除监听器和定时器。排队的下一轮输入、其他 Agent 的活动和任务板变化不会结束等待。 + +任务命令追加并刷盘修订,不通知等待者,也不写入收件箱消息。需要成员处理更新时,调用者发送明确消息。不新增 Agent 方法、共享等待服务或任务专用等待事件。 + +这仅取代[Team 任务板](../architecture/2026-10-19-team-task-board-inbox.zh.md)中的等待信号决策。树权限、持久任务存储、历史记录不授予权限及与普通控制工具分离的决策仍然适用。不改变 Session 事件代次。 + +## 考虑过的替代方案 + +**每次任务提交后通知所有当前等待。** 这避免了重复收件箱状态,但仍让无关任务编辑打断每个等待成员。将通知移到服务方法后仍保留该行为和耦合。 + +**将每次任务变化持久化为消息。** 任务日志已经保留修订;逐成员通知增加未读状态和投递恢复。明确消息可以表达哪些更新需要行动。 + +**在 Agent 或收件箱中增加等待。** 现有输入事件和工具拥有的取消机制已能实现所需等待,无须扩展核心 API。 + +## 后果 + +仅更新任务不会恢复等待中或空闲的成员。需要继续工作时,调用者必须通信。工具不返回任务内容;成员按需查询任务板。等待前和等待期间发生的任务变化效果相同:都不影响等待。 + +单元测试覆盖已有输入、调用者隔离、并行等待、取消、释放,以及不结束等待的任务提交。任务板录制场景检查过去和并发提交下的等待超时,完成通知仍作为普通收件箱输入。 diff --git a/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.i18n.yaml b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.i18n.yaml new file mode 100644 index 0000000000..cf5fb34bc3 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-10-29-team-task-only-projection.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.md +/agent-note-team-projection-retains-only-tasks-and-mode: + en: 030f2abb8b5137fe + zh: e661455f374c8b1f +/agent-note-team-projection-retains-only-tasks-and-mode/problem: + en: 43bd1c0daacd2b86 + zh: a35efb4e84cd9288 +/agent-note-team-projection-retains-only-tasks-and-mode/decision: + en: dd21640eb965f332 + zh: 345bc4df573cbadf +/agent-note-team-projection-retains-only-tasks-and-mode/alternatives-considered: + en: 96a0f421f9f92746 + zh: 314f4557f391f90d +/agent-note-team-projection-retains-only-tasks-and-mode/consequences: + en: 1c1b767b7905869f + zh: 1241351bfc433b70 diff --git a/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.md b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.md new file mode 100644 index 0000000000..57a85f4105 --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.md @@ -0,0 +1,29 @@ +# Agent Note: Team projection retains only tasks and mode + +Status: implemented + +English | [中文](2026-10-29-team-task-only-projection.zh.md) + +## Problem + +The Team projection retained historical member, message, and delivery collections after subagent discovery and messaging replaced their runtime consumers. Its retired lifecycle and mailbox validators could still fail the current task board, while checkpoints retained message bodies with no current reader. + +## Decision + +Project only tasks, saved mode, and their recovery metadata. Ignore `team/member` and `team/message/*` payloads without rebuilding or validating their former state machines. This deliberately gives up historical teammate and mailbox state recovery and the associated validation failures. The user accepted that loss; task recovery remains required. + +Checkpoint version 7 invalidates prior state, including failures caused by retired records. The registry rebuilds from the unchanged Session log. Historical event declarations, format migrations, message sources, and attachment export remain supported; no Session format bump or log conversion is needed. + +This partially supersedes the projection and mailbox-validation decisions in [Agent Teams](../feature/2026-08-05-agent-teams.md). The [subagent identity](../architecture/2026-10-15-agent-teams-as-subagents.md) and [inbox-only wait](2026-10-29-inbox-only-agent-wait.md) decisions remain active, as do task durability and shared-checkout semantics. + +## Alternatives considered + +**Retain decode-only roster and mailbox projections.** No production consumer reads these collections. Keeping them preserves message history in checkpoints and lets obsolete validation stop current task operations. + +**Migrate or delete historical log events.** The task board can ignore these records directly. Rewriting them adds migration work and would discard archival data that existing format readers and exports can still use. + +## Consequences + +Old teammate and mailbox state is unavailable through Team projection. Original log records remain readable, but neither grant authority nor trigger delivery. Reintroducing recovery requires a concrete consumer and an explicit decision about its retained data and failure scope. + +Tests cover ignored legacy payloads, version-6 checkpoint invalidation, current checkpoint suffix replay, JSONL restart with task mutation, stable view references, and a recorded headless profile accepting a task after retired lifecycle and mailbox records. Task and mode validation still fail visibly. diff --git a/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.zh.md b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.zh.md new file mode 100644 index 0000000000..221abe771b --- /dev/null +++ b/.agents/notes/implemented/simplification/2026-10-29-team-task-only-projection.zh.md @@ -0,0 +1,29 @@ +# Agent Note: Team 投影仅保留任务与模式 + +Status: implemented + +[English](2026-10-29-team-task-only-projection.md) | 中文 + +## Problem + +子代理发现和通信替代运行时消费者后,Team 投影仍保留历史成员、消息与投递集合。已退役的生命周期和邮箱校验器仍可能使当前任务板失败,而检查点保留着没有当前读取方的消息正文。 + +## Decision + +仅投影任务、保存的模式及其恢复元数据。忽略 `team/member` 和 `team/message/*` 载荷,不再重建或校验原有状态机。这明确放弃历史队友与邮箱状态恢复,以及相应的校验失败行为。用户接受这一能力损失;任务恢复仍为必要能力。 + +检查点版本 7 使旧状态失效,包括退役记录导致的失败。注册表从未改写的 Session 日志重建状态。历史事件声明、格式迁移、消息来源和附件导出仍受支持;无需提升 Session 格式版本或转换日志。 + +本决策部分取代 [Agent Teams](../feature/2026-08-05-agent-teams.zh.md) 的投影与邮箱校验决策。[子代理身份](../architecture/2026-10-15-agent-teams-as-subagents.zh.md)和[仅等待收件箱](2026-10-29-inbox-only-agent-wait.zh.md)决策仍有效,任务持久性与共享检出语义也保持有效。 + +## Alternatives considered + +**保留仅供解码的名册与邮箱投影。** 没有生产消费者读取这些集合。保留它们会在检查点中保存消息历史,并允许过时校验阻断当前任务操作。 + +**迁移或删除历史日志事件。** 任务板可以直接忽略这些记录。改写增加迁移工作,还会丢失现有格式读取器和导出功能仍可使用的归档数据。 + +## Consequences + +Team 投影不再提供旧队友与邮箱状态。原始日志记录仍可读取,但不授予权限,也不触发投递。重新引入恢复需要具体消费者,并明确决定保留的数据和失败影响范围。 + +测试覆盖忽略旧载荷、版本 6 检查点失效、当前检查点后缀重放、JSONL 重启后修改任务、稳定视图引用,以及录制的 headless profile 在退役生命周期与邮箱记录之后接受任务。任务和模式校验仍可见地报错。 diff --git a/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.i18n.yaml b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.i18n.yaml new file mode 100644 index 0000000000..8db24c9d07 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.i18n.yaml @@ -0,0 +1,43 @@ +# Bilingual-pair consistency record for 2026-10-29-event-triggered-automation-tasks.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.md +/agent-note-event-triggered-automation-tasks: + en: fe57a78907eab083 + zh: 4ac96eeb365ac012 +/agent-note-event-triggered-automation-tasks/problem: + en: 491a791a201d0b2c + zh: 5a98f693ac4b5e77 +/agent-note-event-triggered-automation-tasks/proposal: + en: 7906d9f791e0ba02 + zh: 3a083d451344f072 +/agent-note-event-triggered-automation-tasks/proposal/layers: + en: 8bf2fc8ccb162c59 + zh: e993b9ae72f8d9a2 +/agent-note-event-triggered-automation-tasks/proposal/sessions: + en: 7ec83684c8c19e31 + zh: 27df2725836e5f7b +/agent-note-event-triggered-automation-tasks/proposal/configuration: + en: 21be7e27081aff54 + zh: 7973f7f0d064db35 +/agent-note-event-triggered-automation-tasks/proposal/mechanisms: + en: 2403ec84b12279ec + zh: 7e245af54dcf4a1a +/agent-note-event-triggered-automation-tasks/proposal/product-scope: + en: c003c908f407ccb2 + zh: 6113569a44d52202 +/agent-note-event-triggered-automation-tasks/proposal/event-triggers-as-infrastructure: + en: 4c62e16718896e9b + zh: 9c61ea9b6e1f4f22 +/agent-note-event-triggered-automation-tasks/proposal/delivery-order: + en: 79cf498bf3566051 + zh: 4537f1bd3df527b4 +/agent-note-event-triggered-automation-tasks/alternatives-considered: + en: 21df079f7d7c3f4d + zh: 67f4ab221aacf2cf +/agent-note-event-triggered-automation-tasks/acceptance-criteria: + en: 504feb2cc59f4457 + zh: c78cd50f2f336562 +/agent-note-event-triggered-automation-tasks/risks: + en: 35edb8d5b6a1cfa4 + zh: cb8dbc339c6055be diff --git a/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.md b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.md new file mode 100644 index 0000000000..af3f170fca --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.md @@ -0,0 +1,153 @@ +# Agent Note: Event-triggered automation tasks + +Status: proposed + +English | [中文](2026-10-29-event-triggered-automation-tasks.zh.md) + +## Problem + +Automation tasks run only on time rules today. The Host stores each rule, and every due time queues the task's instruction as a follow-up message in the task's original Session ([Host-owned scheduled messages](../../implemented/architecture/2026-09-16-host-schedule-storage.md)); the model creates and edits tasks through preset-scoped tools ([Preset-scoped Schedule tools](../../implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md)). Work that should start when something else changes, such as a pull request's checks failing, a reviewer requesting changes, or a message arriving, cannot be expressed as a task, so users check those sources by hand across Sessions. + +Reacting to changes brings two problems that time rules do not have. + +- **Cost and noise.** Most observations of a source contain nothing worth a model turn. If every observation reaches the model and silence depends on the model replying with a marker, each poll costs a full turn, and a model that holds a messaging tool reports "nothing new" anyway. +- **Untrusted input.** Event content is written by other people: comments, reviews, messages. A turn started by that content must not edit, push, or send anything before the user has seen it. + +## Proposal + +An automation task becomes an instruction, a source with parameters, and a Session mode. Time is one source among several, so a scheduled task is an automation task whose source is time. Each observation passes three layers, and only the last one calls a model: a source event passes the trigger's filter and becomes a candidate, the candidate is delivered to a Session where the model judges it, and only a notify call produces a notice for the user. This partially supersedes the two notes linked above: tasks stop being bound to their original Session, and task records stop meaning inbox delivery only. + +```mermaid +flowchart TD + Task["Task: instruction, source parameters, Session mode
written by the model, shown read-only"] + Prov["Source providers: plugins, code
time, GitHub; later mail, IM, memory"] + Trig["Event trigger: shared code, state per task
compare with stored state, match parameters, merge"] + Rec[("Run records")] + Src{"Source"} + Exec["Run the instruction in the target Session
with its permissions"] + RO["Read-only turn in the task's own Session
the model judges the candidate"] + Note["Notice: action card, unread mark,
system notification"] + Quiet["No notice"] + Acc["User accepts: the action runs in the Session
that created the task, with its permissions"] + Task --> Trig + Prov -- "source events" --> Trig + Trig -- "each change or failure" --> Rec + Trig -- candidate --> Src + Src -- time --> Exec + Src -- "other sources" --> RO + RO -- notify --> Note + RO -- "no notify call" --> Quiet + Note --> Acc +``` + +| Layer | Decides | Model call | Output | +|---|---|---|---| +| Source provider | What changed in the source | No | Events | +| Event trigger | Whether the change matters to this task | No | A run record; a candidate or nothing | +| Agent | Whether the user needs to act, and what to propose | Only for delivered candidates | A notice through notify, or nothing | + +### Layers + +**Source providers** are code, packaged as plugins; they provide event sources and are unrelated to model, SSH, or credential providers. A provider owns one kind of source: it polls or subscribes, reports changes as events with a subject, a one-line summary, detail, and links, and declares the JSON schema of the parameters a task can set. One provider serves every task of its kind. Time is the first provider, and today's schedule rules become its parameters. Any installed plugin can register a provider, including one written in Creator mode; a task can name only a registered provider. + +**The event trigger** is shared code, registered per source kind and version; each task holds only its parameters and the source state it last observed. For each observation it compares the new state with the stored one, and an observation without a change only updates the last-checked time. A check that turns from passing to failing is a change, a check that stays failing is not, and a pass followed by a new failure is a change again. For a change, the trigger matches the task's conditions, which are parameter fields such as conclusion is failure, author is the user, or commenter is not a bot; merges changes to the same subject inside the provider's merge window, so one push that fails three checks becomes one event; stores the new state with the task; and either delivers a candidate to the Session or drops the change. Each change and each failure writes a run record, listed in the task's Records tab next to today's delivery records: candidate delivered, filtered with its reason, or failed. Consecutive failures with the same cause share one record with a count. Delivery ends the trigger's work: it does not wait for the turn or read a receipt. One queue per task orders its evaluations. + +**The agent** receives the candidate as a message in the target Session, together with the task's instruction in the user's words. What the turn may do depends on the source. + +- **Time**: the turn runs the instruction with the Session's permissions, and its reply is the result, as scheduled tasks behave today. +- **Other sources**: the turn gets the read-only tool set described under Mechanisms. It can read files and the source's state, such as check logs and pull request diffs, but has no tool that edits, pushes, or sends. One new tool, **notify** (`automation_notify`), takes a title, a summary, and a proposed action and produces a notice: an [action card](../../../../packages/experimental/action-cards/README.md) with the proposed action in the Session, the Session's unread mark, and a desktop system notification. The model decides whether to call it. A turn without notify produces no notice; there is no end tool, and nothing checks how the turn ended. When the user accepts the card, the Host sends a follow-up to the Session that handles the task, as described under Sessions; the follow-up names the task and the event and quotes the proposed action as the automation's proposal, not as the user's words, and that turn runs with that Session's permissions. + +### Sessions + +A task delivers to its target Session in one of three modes: a specified Session, a new Session per trigger, or a new Session on the first trigger that later triggers reuse. Time tasks keep today's target, the Session they were created in. Event tasks separate judging from handling. The read-only turn runs in the task's own Session, created on the first trigger and reused afterwards, because it needs the instruction, the event, and the task's earlier decisions rather than the long history of the conversation the task came from. When the model creates a task in a conversation, it writes the facts the judgment needs into the instruction, such as which check is known to be flaky. When the user accepts a card, the proposed action goes to the Session the task was created in, where the code and its history are. The automation page's New action already creates tasks in a new Session, which then handles them; a task enabled from an official template, which a later step adds, continues in its own Session. The user can change the mode on the task. + +No task runs while the Host is stopped. On restart, each task compares the current source state with its stored state once and does not replay intermediate changes. Time keeps today's rule: a recurring task runs its latest missed occurrence once. + +### Configuration + +Configuration has two layers. Provider code decides what can be observed and how; task parameters decide what one task watches. The model writes the parameters from the user's words through the task tools, and the provider's schema validates them. A task carries no scripts or other code, so observing something new means changing or installing a provider plugin. The automation page shows source parameters read-only, and they change through conversation; the time editor stays. + +### Mechanisms + +- **Event-turn tool set.** Sandbox read-only mode limits only the filesystem, so it cannot stop a push or an outbound request. An event turn is offered a fixed tool set instead of the Session's: file reads and searches, the source provider's read operations, and `automation_notify`. Shell, file writes, web fetch, and MCP tools are absent. The tool set is recorded in the Session log, and a user message queued during the turn starts a normal turn after it ends. +- **Notify card.** The automation package registers an action-card kind, and `automation_notify` creates its card through the action-card service; the tool exists only in event turns, so no skill load precedes it. Accepting runs the kind's handler, which queues the follow-up through the Host, so the handling Session need not be open. A newer card replaces an unanswered older one in the same Session, as the service does today; the older card is in that Session's history, so the newer turn sees it and carries over what is still open. A refused card returns an error to the turn. +- **Unread mark.** The client derives the unread mark from turn completion. A task's own Session is marked as an automation Session, and for such a Session the client shows the mark only for notices, so a turn without notify leaves no mark. +- **Logging.** The delivered candidate, the turn's tool set, and the notify call are Session events, so replay rebuilds the turn; the TypeScript and Python SDK expected outputs and a recorded-session snapshot cover them. +- **Storage.** Source, parameters, Session mode, trigger state, and run records extend the Host task domain in a new record version with an adjacent migration. A version-1 task reads as a time task, is not rewritten until it changes, and gets no invented records. Run records have their own count and age bounds, separate from delivery records. +- **Provider configuration.** Polling intervals and request budgets are validated Config fields of each provider in cordis.yml. + +### Product scope + +- No new entry point and no page redesign: scheduled and event-triggered tasks share the automation page. +- The task list adds a source-type filter next to the status filter. +- Task details add the source with its parameters, read-only, and the Session mode, editable. +- A task's Records tab also lists filtered and failed evaluations. +- Notifications reuse the Session unread mark and action cards; the desktop app adds a system notification. + +### Event triggers as infrastructure + +The trigger layer is shared infrastructure for DSH, not a feature of the automation page. A feature that watches something and hands changes to an agent becomes a task on this layer instead of building its own polling, state, records, and notifications. + +- **DSH's own state as sources**: a Session turn ending in an error, a background job settling, and, once memory lands, a memory consolidation pass finishing or memory entries changing. +- **Features on those sources**: plugin recommendations, where a workflow the user repeats by hand shows up after consolidation and the agent proposes a plugin on an action card, and task recommendations, where a review of the day's Sessions proposes follow-up work. Each is a template task with a DSH source, an instruction, and the same notify step. The plugin recommendations package, which proposes cards from conversation turns today, can move onto such a source once consolidation lands. +- **What every consumer keeps**: change detection and condition matching in code, run records, Session modes, read-only event turns, and notify as the only way a task reaches the user. + +### Delivery order + +1. Task–Session decoupling with the three Session modes. +2. The trigger layer with time as its first provider and the task-domain migration; existing scheduled tasks behave as before. +3. The GitHub provider for pull request checks, reviews, and comments; the event-turn tool set and `automation_notify`; action cards leave experimental status or ship with the automation bundle. +4. Mail and IM providers and official templates, then DSH's own sources. + +## Alternatives considered + +**Judge every observation in a resident Session.** The model reads each poll and replies with a silence marker when nothing changed. It lost because each observation costs a full turn over the Session's context, polls spaced beyond the prefix cache lifetime read that context uncached, and silence depends on the model following an instruction while it holds a messaging tool. Here code drops unchanged and unmatched observations, and only a notify call reaches the user. + +**Judge in the Session that created the task.** That conversation already holds the code and its history, so the instruction would need no extra facts. It lost because most candidates produce no notice, and each of them would add a turn over the conversation's whole context, read uncached once the prefix cache has expired, and queue behind or interrupt the user's own work there. Only accepted work goes to that Session. + +**Let the agent choose the Session for each event.** The choice could differ from one event to the next, so the user could not predict where a notification appears, and deciding whether the history is needed requires reading it first. + +**Condition scripts per task.** A task would carry a script that fetches and decides. It lost because the script runs with the user's credentials without the review a plugin installation gets, and each task would carry its own fetch logic instead of sharing a provider. + +**Notify from code when code can decide.** A failed check could notify without a model. It lost because the notification would carry only the raw status. With one path, the agent reads the logs first and the notification states the cause; change-only delivery keeps these turns rare. + +**One model call outside any Session.** A single call per event costs less and leaves no Session record. It lost because the call cannot read files or logs before deciding, and acting on its result needs a Session anyway. + +**Event turns with the Session's permissions.** Acting directly would save one click. It lost because event content comes from other people, and a read-only turn keeps that text from driving edits, pushes, or messages before the user accepts. + +**A read-only sandbox for event turns.** It lost because sandbox read-only mode limits only the filesystem, and a turn in it can still push or send requests. + +**An end tool and a check on how the turn ended.** A second tool would record why a turn produced no notice, and the trigger would wait for that outcome. It lost because nothing acts on that reason: delivery ends the trigger's work, and a turn without notify is already silent. + +**Parameter forms on the automation page.** Each provider would need its own form, validation, and display. Parameters written by the model and shown read-only cover creation and change through conversation, and the provider schema keeps a generated form possible later. + +**A separate notification entry.** An inbox page or tab would separate the notification from the Session that holds its context. The unread mark and the system notification lead to that Session, and the automation page keeps the records. + +## Acceptance criteria + +- Existing scheduled tasks behave the same after time becomes a provider: the same due times, the same catch-up rule, and the same delivery into the Session. +- A version-1 task loads as a time task without being rewritten and without invented records. +- A GitHub task on a pull request's checks delivers one candidate when a check turns from passing to failing, none while it stays failing, and another after a pass followed by a new failure. +- One push that fails three checks produces one candidate. +- An observation without a change writes no record and starts no turn; a change that fails the conditions writes a filtered record and starts no turn; consecutive failures with the same cause write one record with a count. +- A run record ends at delivery: it records the candidate, not what the turn did. +- An event turn is offered no shell, file-write, web-fetch, or MCP tool, and its tool set appears in the Session log; after the user accepts its card, the next turn runs with the Session's permissions. +- A notify call produces the card, the unread mark, and the desktop system notification together. +- An event turn without a notify call leaves no unread mark and sends no system notification. +- An event task's read-only turns run in the task's own Session, and accepting its card sends the proposed action to the Session the task was created in. +- Each Session mode delivers as defined: a specified Session receives every trigger, a new Session opens per trigger, or one Session opens on the first trigger and is reused. +- Replaying the Session log rebuilds an event turn's candidate, tool set, and notify call. +- After a restart, a task compares the current source state with its stored state once and does not replay intermediate changes. +- The task list filters by source type, task details show source parameters read-only, and the Session mode can be changed. + +## Risks + +- The read-only turn sees the instruction, the event, and the task's earlier decisions, not the conversation the task came from. Facts the judgment needs from that conversation must be written into the instruction when the task is created; a user who switches the task to its original Session gets the history back at the cost of reading the long context on each delivery. +- A notification appears in the task's own Session, not in the conversation that created the task; accepting its card moves the work to that conversation. +- The agent may notify too often or stay silent when it should not. Accepted and dismissed cards show over-notification, but a missed notice leaves no trace in the run records, which end at delivery. +- Source parameters cannot be edited by hand; every change goes through the model. +- A fix on an event waits for the user to accept the card instead of running unattended. +- A source without a provider plugin cannot be watched. +- Tasks run only while the Host runs: nothing runs while the app is closed or the machine sleeps. +- Event tasks depend on action cards, which are experimental and mounted only by the Personalized recommendations bundle today. +- The read-only tool set limits judgment to what files and the provider's read operations show; for a source whose provider offers no read operations, the agent judges from the event alone. diff --git a/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.zh.md b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.zh.md new file mode 100644 index 0000000000..c23e4684c8 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.zh.md @@ -0,0 +1,153 @@ +# Agent Note: 事件触发的自动化任务 + +Status: proposed + +[English](2026-10-29-event-triggered-automation-tasks.md) | 中文 + +## 问题 + +目前自动化任务只能按时间规则运行。Host 保存每条规则,每到一个到期时间,就把任务的指令作为一条后续消息排进任务的原会话([Host 拥有的定时消息](../../implemented/architecture/2026-09-16-host-schedule-storage.zh.md));模型通过按 preset 提供的工具创建和修改任务([按 preset 提供的 Schedule 工具](../../implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md))。有些工作应当在别处发生变化时开始,例如 PR(Pull Request)的检查失败、评审人要求修改、收到一条消息,这些都无法建成任务,用户只能在多个会话之间手动查看这些来源。 + +响应变化会带来两个时间规则没有的问题。 + +- **成本和噪音。** 对来源的大多数观察里,没有值得花一个模型轮次处理的内容。如果每次观察都交给模型,并依靠模型回复一个标记来保持安静,每次轮询都要花一个完整轮次;手里有发消息工具的模型仍然会报告“没有新情况”。 +- **不可信的输入。** 事件内容由其他人写成:评论、评审、消息。由这类内容启动的轮次,在用户看到之前不能修改、推送或发送任何东西。 + +## 提案 + +自动化任务改为由指令、带参数的来源和会话模式组成。时间是多种来源中的一种,因此定时任务就是来源为时间的自动化任务。每次观察依次经过三层,只有最后一层调用模型:来源事件经过触发器过滤成为候选事件(candidate),候选事件投递到会话,由模型在会话中判断,只有调用通知工具才会为用户产生一条通知(notice)。本提案部分取代上面链接的两篇笔记:任务不再绑定原会话,任务记录也不再只表示收件箱投递。 + +```mermaid +flowchart TD + Task["Task: instruction, source parameters, Session mode
written by the model, shown read-only"] + Prov["Source providers: plugins, code
time, GitHub; later mail, IM, memory"] + Trig["Event trigger: shared code, state per task
compare with stored state, match parameters, merge"] + Rec[("Run records")] + Src{"Source"} + Exec["Run the instruction in the target Session
with its permissions"] + RO["Read-only turn in the task's own Session
the model judges the candidate"] + Note["Notice: action card, unread mark,
system notification"] + Quiet["No notice"] + Acc["User accepts: the action runs in the Session
that created the task, with its permissions"] + Task --> Trig + Prov -- "source events" --> Trig + Trig -- "each change or failure" --> Rec + Trig -- candidate --> Src + Src -- time --> Exec + Src -- "other sources" --> RO + RO -- notify --> Note + RO -- "no notify call" --> Quiet + Note --> Acc +``` + +| 层 | 判断什么 | 是否调用模型 | 输出 | +|---|---|---|---| +| 来源提供方(source provider) | 来源里发生了什么变化 | 否 | 事件 | +| 事件触发器(event trigger) | 这个变化与本任务是否相关 | 否 | 一条运行记录;一个候选事件,或者没有 | +| agent(智能体) | 用户是否需要处理,以及建议怎么处理 | 只对已投递的候选事件 | 通过通知工具产生通知,或者没有 | + +### 分层 + +**来源提供方**是代码,以插件形式提供;它们提供事件来源,与模型、SSH 或凭据的提供方无关。一个来源提供方负责一类来源:它轮询或订阅来源,把变化报告为事件(包含对象、一行摘要、详细内容和链接),并声明任务可设置参数的 JSON schema。同类的所有任务共用同一个来源提供方。时间是第一个来源提供方,现有的定时规则成为它的参数。任何已安装的插件都可以注册来源提供方,包括在创造模式中写出的插件;任务只能指定已注册的来源提供方。 + +**事件触发器**是共享的代码,按来源类型和版本注册;每个任务只保存自己的参数和上次观察到的来源状态。每次观察时,它把新状态与保存的状态比较;没有变化的观察只更新最近检查时间。检查从通过变为失败算一次变化,持续失败不算,通过之后再次失败又算一次变化。对一次变化,触发器先匹配任务的条件(参数中的字段,例如结论为失败、作者是用户本人、评论者不是 bot),再在来源提供方的合并窗口内合并同一对象的多次变化(一次推送导致三项检查失败,只算一个事件),然后把新状态和任务一起保存,向会话投递一个候选事件,或者丢弃这次变化。每次变化和每次失败都写一条运行记录,列在任务的运行记录页签中,与现有的投递记录并列:已投递候选事件、已过滤(附原因)或失败。同一原因的连续失败共用一条记录并计数。投递之后触发器的工作就结束了,不等待该轮次,也不读取回执。每个任务用一个队列排定自己的判定顺序。 + +**agent** 在目标会话中以一条消息收到候选事件,消息附带以用户原话写成的任务指令。轮次能做什么取决于来源。 + +- **时间**:轮次按会话的权限执行指令,回复就是结果,与现在的定时任务一致。 +- **其他来源**:轮次使用“机制”一节所述的只读工具集。它可以读文件和来源的状态,例如检查日志和 PR diff,但没有修改、推送或发送的工具。新增一个工具 **通知**(`automation_notify`),接收标题、摘要和建议的操作,产生一条通知:会话中出现带有建议操作的[操作卡片](../../../../packages/experimental/action-cards/README.zh.md)、会话显示未读标记、桌面端发送系统通知。是否调用由模型决定。没有调用通知的轮次不产生通知;没有结束工具,也不检查轮次如何结束。用户接受卡片后,Host 向处理该任务的会话(见“会话”一节)发送一条后续消息:消息写明任务和事件,并把建议的操作作为自动化提出的建议引用,而不是作为用户的话;该轮次按该会话的权限执行。 + +### 会话 + +任务按三种模式之一投递到目标会话:指定的会话、每次触发新建会话、首次触发时新建会话并在之后的触发中复用。定时任务沿用现在的目标,即创建它的会话。事件任务把判断和处理分开。只读轮次在任务自己的会话中运行,首次触发时新建,之后复用,因为它需要的是指令、本次事件和该任务之前的判断,而不是任务来源会话的长历史。模型在会话中创建任务时,把判断需要的事实写进指令,例如哪项检查已知不稳定。用户接受卡片后,建议的操作发往创建任务的会话,代码和相关历史都在那里。自动化页的“新建”本来就在一个新会话中创建任务,之后由该会话处理;从官方模板启用的任务(后续步骤加入)在自己的会话中继续执行。用户可以在任务上修改模式。 + +Host 停止期间不运行任何任务。重启后,每个任务把当前来源状态与保存的状态比较一次,不重放中间的变化。时间沿用现有规则:周期任务只补跑最近一次错过的时间点。 + +### 配置 + +配置分两层。来源提供方的代码决定能观察什么、如何观察;任务参数决定一个任务观察什么。模型根据用户原话,通过任务工具写入参数,由来源提供方的 schema 校验。任务不携带脚本或其他代码,因此要观察新的东西,就修改或安装来源提供方插件。自动化页以只读方式显示来源参数,参数通过对话修改;时间编辑器保留。 + +### 机制 + +- **事件轮次的工具集。** 沙箱的只读模式只限制文件系统,挡不住推送或外发请求。因此事件轮次使用固定的工具集,而不是会话的工具集:读文件和搜索、来源提供方的读取操作,以及 `automation_notify`。没有 shell、写文件、网页抓取和 MCP 工具。工具集记录在会话日志中;轮次进行中排队的用户消息,在该轮次结束后作为普通轮次执行。 +- **通知卡片。** 自动化包注册一种操作卡片类型,`automation_notify` 通过操作卡片服务创建这类卡片;该工具只在事件轮次中提供,因此调用前不需要加载 Skill。接受卡片时执行该类型的处理器,由处理器通过 Host 排入后续消息,所以处理任务的会话不必处于打开状态。同一会话中,新卡片会替换尚未处理的旧卡片,与操作卡片服务现在的行为一致;旧卡片在该会话的历史中,新的轮次能看到它,并把仍未处理的内容带到新卡片里。被拒绝的卡片会把错误返回给该轮次。 +- **未读标记。** 客户端根据轮次完成推导未读标记。任务自己的会话标记为自动化会话,对这类会话,客户端只为通知显示未读标记,因此没有调用通知的轮次不留下标记。 +- **日志。** 已投递的候选事件、轮次的工具集和通知调用都是会话事件,回放可以重建该轮次;TypeScript 和 Python SDK 的期望输出以及一个录制会话快照覆盖这些内容。 +- **存储。** 来源、参数、会话模式、触发器状态和运行记录以新的记录版本扩展 Host 任务域,并提供相邻迁移。版本 1 的任务按时间任务读取,在发生修改前不重写,也不补造记录。运行记录有自己的数量和时长上限,与投递记录分开。 +- **来源提供方配置。** 轮询间隔和请求额度是每个来源提供方在 cordis.yml 中经过校验的 Config 字段。 + +### 产品范围 + +- 不新增入口,不重做页面:定时任务和事件触发的任务共用自动化页。 +- 任务列表在状态筛选旁增加来源类型筛选。 +- 任务详情增加来源及其参数(只读)和会话模式(可修改)。 +- 任务运行记录同时列出已过滤和失败的判定。 +- 通知复用会话的未读标记和操作卡片;桌面端新增系统通知。 + +### 事件触发作为基础设施 + +触发层是 DSH 共用的基础设施,而不是自动化页的一项功能。需要观察某样东西并把变化交给 agent 的功能,都作为这一层上的任务实现,不再各自实现轮询、状态、记录和通知。 + +- **DSH 自身状态作为来源**:会话轮次以错误结束、后台作业结束;memory 落地后,还包括一次 memory 整理完成,或 memory 条目发生变化。 +- **基于这些来源的功能**:插件推荐,即 memory 整理后发现用户反复手动执行的流程,由 agent 在操作卡片上推荐插件;任务推荐,即回顾当天的会话,提出后续要做的事。每一项都是一个模板任务,由一个 DSH 来源、一条指令和同样的通知步骤组成。插件推荐包现在从对话轮次中提出卡片,memory 整理落地后可以改为基于这类来源。 +- **每个使用方都保留的规则**:变化检测和条件匹配由代码完成、运行记录、会话模式、只读的事件轮次,以及只有通知能让任务触达用户。 + +### 交付顺序 + +1. 任务与会话解耦,支持三种会话模式。 +2. 上线触发层和任务域迁移,以时间作为第一个来源提供方;现有定时任务行为不变。 +3. GitHub 来源提供方,覆盖 PR 的检查、评审和评论;事件轮次工具集和 `automation_notify`;操作卡片结束实验状态,或随自动化 bundle 一起提供。 +4. 邮件和 IM 来源提供方以及官方模板,然后是 DSH 自身的来源。 + +## 考虑过的替代方案 + +**在常驻会话中判断每次观察。** 模型读取每次轮询的结果,没有变化时回复一个静默标记。没有采用,原因是:每次观察都要在会话的完整上下文上花一个轮次;轮询间隔超过前缀缓存的有效期时,每次都要在没有缓存的情况下读取整个上下文;而且模型手里有发消息工具时,能否保持安静取决于它是否遵守指令。本方案由代码丢弃没有变化和不匹配的观察,只有调用通知才会触达用户。 + +**在创建任务的会话中判断。** 该会话已经有代码和相关历史,指令里不需要额外写事实。没有采用,原因是大多数候选事件不产生通知,每一次都会在该会话的完整上下文上增加一个轮次,前缀缓存过期后要在没有缓存的情况下读取整个上下文,用户正在那里工作时还要排队或打断。只有被接受的工作才会进入该会话。 + +**由 agent 为每个事件选择会话。** 每次的选择可能不同,用户无法预料通知出现在哪里;而且要判断是否需要历史,得先读取历史。 + +**每个任务自带条件脚本。** 任务携带一个脚本,由脚本获取数据并作出判断。没有采用,原因是脚本以用户的凭据运行,却没有经过安装插件时的审查;而且每个任务都要自带获取逻辑,无法共用来源提供方。 + +**代码能判断时由代码直接通知。** 检查失败可以不经模型直接通知。没有采用,原因是这样的通知只包含原始状态。只保留一条路径时,agent 会先读日志,通知中写明失败原因;只在变化时投递,这类轮次很少。 + +**在会话之外调用一次模型。** 每个事件调用一次模型,成本更低,也不留下会话记录。没有采用,原因是这次调用在判断前无法读取文件或日志,而且要根据结果采取行动仍然需要会话。 + +**事件轮次沿用会话的权限。** 直接行动可以省去一次点击。没有采用,原因是事件内容来自其他人,只读轮次能防止这些文字在用户接受之前驱动修改、推送或发消息。 + +**事件轮次使用只读沙箱。** 没有采用,原因是沙箱的只读模式只限制文件系统,处于该模式的轮次仍然可以推送或发出请求。 + +**结束工具和对轮次结束方式的检查。** 第二个工具可以记录某一轮为什么没有产生通知,触发器则要等待这个结果。没有采用,原因是没有任何环节会使用这个原因:投递之后触发器的工作就结束了,而没有调用通知的轮次本来就是静默的。 + +**在自动化页提供参数表单。** 每个来源提供方都需要各自的表单、校验和展示。由模型写入参数并以只读方式展示,已经覆盖通过对话创建和修改;来源提供方的 schema 让以后生成表单仍然可行。 + +**单独的通知入口。** 收件箱页面或标签页会把通知与持有其上下文的会话分开。未读标记和系统通知都指向该会话,自动化页保留记录。 + +## 验收标准 + +- 时间改为来源提供方后,现有定时任务行为不变:到期时间相同、补跑规则相同、投递到会话的方式相同。 +- 版本 1 的任务按时间任务加载,不重写,也不补造记录。 +- 观察 PR 检查的 GitHub 任务,在检查从通过变为失败时投递一个候选事件,持续失败期间不再投递,通过之后再次失败时再投递一个。 +- 一次推送导致三项检查失败,只产生一个候选事件。 +- 没有变化的观察不写记录,也不启动轮次;不满足条件的变化写一条已过滤记录,不启动轮次;同一原因的连续失败只写一条带计数的记录。 +- 运行记录到投递为止:记录候选事件,不记录该轮次做了什么。 +- 事件轮次不提供 shell、写文件、网页抓取或 MCP 工具,其工具集出现在会话日志中;用户接受卡片后,下一轮次按会话的权限执行。 +- 一次通知调用同时产生卡片、未读标记和桌面端系统通知。 +- 没有调用通知的事件轮次不留下未读标记,也不发送系统通知。 +- 事件任务的只读轮次在任务自己的会话中运行;接受卡片后,建议的操作发往创建任务的会话。 +- 每种会话模式按定义投递:指定的会话接收每次触发,或每次触发新建一个会话,或首次触发时新建一个会话并在之后复用。 +- 回放会话日志可以重建事件轮次的候选事件、工具集和通知调用。 +- 重启后,任务把当前来源状态与保存的状态比较一次,不重放中间的变化。 +- 任务列表可以按来源类型筛选,任务详情以只读方式显示来源参数,会话模式可以修改。 + +## 风险 + +- 只读轮次看到的是指令、本次事件和该任务之前的判断,看不到任务来源的会话。判断需要的、来自那个会话的事实,必须在创建任务时写进指令;用户把任务改成投回原会话,就能拿回历史,代价是每次投递都要读取很长的上下文。 +- 通知出现在任务自己的会话里,而不是创建任务的对话里;接受卡片后,工作转到那个对话。 +- agent 可能通知过于频繁,或者在应该提醒时保持静默。被接受和被忽略的卡片能看出通知过多,但漏掉的通知不会在运行记录中留下痕迹,因为运行记录到投递为止。 +- 来源参数不能手动编辑,每次修改都要经过模型。 +- 针对事件的修复要等用户接受卡片,不会在无人值守时执行。 +- 没有来源提供方插件的来源无法观察。 +- 任务只在 Host 运行时执行:应用关闭或机器休眠期间不运行任何任务。 +- 事件任务依赖操作卡片,而它目前是实验包,只由个性化推荐 Bundle 装入。 +- 只读工具集把判断限制在文件和来源提供方读取操作能看到的内容;来源提供方不提供读取操作时,agent 只能根据事件本身判断。 diff --git a/.github/AGENTS.md b/.github/AGENTS.md index bde3142e27..57830f1af0 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -4,6 +4,6 @@ Run jobs on Windows runners (`windows-*` labels) under native `pwsh`. Native Win The manual [Windows packaging workflow](workflows/windows-package.yml) uses the dedicated self-hosted Windows x64 label `dsh-win-package-trial` under native `pwsh`; preserve this routing separately from the automatic CI lanes. -The merge checks run from three workflows named `Policy`, which run on `pull_request_target` so their definitions come from master, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check` and `Policy / Reviewer Evaluate`, and `pr-check-on-base-branch.yml` on master pushes re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each check reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, `MERGE_POLICY_HEAD_DIFF`, and `MERGE_POLICY_REVIEW`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`; a merge it cannot do and a build that fails both follow its own mode, so `report` warns and skips the build while `block` fails the job. `Policy / Pre-Merge Check` runs `scripts/pre-merge-check.ts` under plain Node and knows nothing else about the merged tree: that script checks the released manifests against the root version, installs, and builds the Host and Client contracts, so change it in one pull request together with the build it orchestrates. +The merge checks run from three workflows named `Policy`, which run on `pull_request_target` so their definitions come from master, and call the `deepseek-harness-check` action directly: `pr-check-on-head-branch.yml` on pull-request updates gives `Policy / Master Change` and `Policy / Pre-Merge Check`, `pr-check-after-approve.yml` on pull-request updates and submitted or dismissed reviews gives `Policy / Approve Check`, which also publishes the review verdict as the check run `Policy / Reviewer Check`, and `pr-check-on-base-branch.yml` on master pushes re-runs the head-branch checks as `Policy / Recheck`. Branch rules require those check names, so keep the job names and the workflow name. Each job reads its mode from a repository variable: `MERGE_POLICY_MASTER_DIFF`, `MERGE_POLICY_PRE_MERGE`, and `MERGE_POLICY_HEAD_DIFF`, each `off` (skip), `report` (run without failing the job), or `block` (fail the job); a missing value or an unknown one counts as `report`. `MERGE_POLICY_HEAD_DIFF` decides whether `Policy / Approve Check` runs and fails; while it runs, `Policy / Reviewer Check` is published whatever that mode says, with `success` when every file that needs review has one and `action_required` with the reviewers to ask otherwise. `Policy / Pre-Merge Check` merges the commit `Policy / Master Change` reports, so it runs only after that job and stays off while `MERGE_POLICY_MASTER_DIFF` is `off`; a merge it cannot do and a build that fails both follow its own mode, so `report` warns and skips the build while `block` fails the job. `Policy / Pre-Merge Check` runs `scripts/pre-merge-check.ts` under plain Node and knows nothing else about the merged tree: that script checks the released manifests against the root version, installs, and builds the Host and Client contracts, so change it in one pull request together with the build it orchestrates. The manual Desktop publication workflow selects a successful package run and attempt, then routes each retained build through `DESKTOP_PUBLISH_RUNNERS` to its original machine's unique label. Keep Windows run steps on native PowerShell and Mac run steps on the default POSIX shell; shared entrypoints are Node scripts. Test and production jobs use separate `desktop-test` and `desktop-production` approval Environments after a credential-free preparation job. diff --git a/.github/workflows/pr-check-after-approve.yml b/.github/workflows/pr-check-after-approve.yml index 1255ae9373..092b5b957d 100644 --- a/.github/workflows/pr-check-after-approve.yml +++ b/.github/workflows/pr-check-after-approve.yml @@ -14,47 +14,15 @@ concurrency: jobs: approve: name: Approve Check - # Each check runs only while its repository variable is neither empty nor `off`; otherwise the job is skipped. + # Skipped while MERGE_POLICY_HEAD_DIFF is empty or `off`; otherwise the job fails by that mode and publishes + # `Policy / Reviewer Check` whatever that mode says. if: ${{ vars.MERGE_POLICY_HEAD_DIFF != '' && vars.MERGE_POLICY_HEAD_DIFF != 'off' }} runs-on: ubuntu-latest timeout-minutes: 15 permissions: contents: read pull-requests: read - steps: - # The head checkout is only the Git repository the check fetches into; it needs no files and runs no code. - - uses: actions/checkout@v7.0.1 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 1 - filter: blob:none - sparse-checkout: README.md - sparse-checkout-cone-mode: false - - - uses: actions/setup-node@v7.0.0 - with: - node-version: '24' - package-manager-cache: false - - - uses: deepseek-harness/deepseek-harness-check@master - env: - CHECK_MODE: ${{ vars.MERGE_POLICY_HEAD_DIFF }} - with: - check: head-diff - base-branch: ${{ github.event.pull_request.base.ref }} - head-sha: ${{ github.event.pull_request.head.sha }} - pr-number: ${{ github.event.pull_request.number }} - pr-author: ${{ github.event.pull_request.user.login }} - - review: - name: Reviewer Evaluate - if: ${{ vars.MERGE_POLICY_REVIEW != '' && vars.MERGE_POLICY_REVIEW != 'off' }} - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - contents: read - pull-requests: read - # The check posts its verdict as a check run of its own. + # The check posts the review verdict as a check run of its own. checks: write steps: # The head checkout is only the Git repository the check fetches into; it needs no files and runs no code. @@ -84,7 +52,7 @@ jobs: - uses: deepseek-harness/deepseek-harness-check@master env: - CHECK_MODE: ${{ vars.MERGE_POLICY_REVIEW }} + CHECK_MODE: ${{ vars.MERGE_POLICY_HEAD_DIFF }} CHECK_TOKEN: ${{ steps.token.outputs.token }} with: check: review diff --git a/AGENTS.md b/AGENTS.md index 69dbd7d69e..db164319da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ packages/ @deepseek-ai/dsh- workspaces at packages/// compaction/ context compaction context/ request context subagent/ delegated agents + team/ shared task coordination jobs/ background jobs bundle/ profile bundles workflow/ workflow execution diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index dbc95653e7..c8cfe0d79b 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -92,6 +92,8 @@ External packages installed for runtime use or embedded in distributed Host or b | [`diff`](https://github.com/kpdecker/jsdiff) | BSD-3-Clause | | [`dompurify`](https://github.com/cure53/DOMPurify) | (MPL-2.0 OR Apache-2.0) | | [`electron-updater`](https://github.com/electron-userland/electron-builder) | MIT | +| [`eslint-scope`](https://github.com/eslint/js) | BSD-2-Clause | +| [`eslint-visitor-keys`](https://github.com/eslint/js) | Apache-2.0 | | [`eventsource-parser`](https://github.com/rexxars/eventsource-parser) | MIT | | [`exceljs`](https://github.com/exceljs/exceljs) | MIT | | [`execa`](https://github.com/sindresorhus/execa) | MIT | @@ -132,6 +134,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`react-dom`](https://github.com/facebook/react) | MIT | | [`readable-stream`](https://github.com/nodejs/readable-stream) | MIT | | [`resolve.exports`](https://github.com/lukeed/resolve.exports) | MIT | +| [`rrule`](https://github.com/jakubroztocil/rrule) | BSD-3-Clause | | [`semver`](https://github.com/npm/node-semver) | ISC | | [`serve-static`](https://github.com/expressjs/serve-static) | MIT | | [`sharp`](https://github.com/lovell/sharp) | Apache-2.0 | @@ -220,6 +223,7 @@ External packages **directly declared** for development, tests, types, or toolin | [`@types/babel__code-frame`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | | [`@types/big.js`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | | [`@types/compression`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | +| [`@types/estree`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | | [`@types/hosted-git-info`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | | [`@types/js-yaml`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | | [`@types/jsdom`](https://github.com/DefinitelyTyped/DefinitelyTyped) | MIT | diff --git a/apps/cli/composition.md b/apps/cli/composition.md index 21150774cc..96b711a333 100644 --- a/apps/cli/composition.md +++ b/apps/cli/composition.md @@ -140,6 +140,10 @@ flowchart LR cfg --> plugin_dsh_base_command_compact plugin_dsh_base_subagent["subagent
@deepseek-ai/dsh-subagent"] cfg --> plugin_dsh_base_subagent + plugin_dsh_base_agent_team["agent-team
@deepseek-ai/dsh-agent-team"] + cfg --> plugin_dsh_base_agent_team + plugin_dsh_base_tool_agent_team["tool-agent-team
@deepseek-ai/dsh-tool-agent-team"] + cfg --> plugin_dsh_base_tool_agent_team plugin_dsh_base_subagent_spawn_in_process["subagent-spawn-in-process
@deepseek-ai/dsh-subagent-spawn-in-process"] cfg --> plugin_dsh_base_subagent_spawn_in_process plugin_dsh_base_subagent_fork_in_process["subagent-fork-in-process
@deepseek-ai/dsh-subagent-fork-in-process"] @@ -272,6 +276,8 @@ flowchart LR | `compaction-basic` | `@deepseek-ai/dsh-compaction-basic` | | `command-compact` | `@deepseek-ai/dsh-command-compact` | | `subagent` | `@deepseek-ai/dsh-subagent` | +| `agent-team` | `@deepseek-ai/dsh-agent-team` | +| `tool-agent-team` | `@deepseek-ai/dsh-tool-agent-team` | | `subagent-spawn-in-process` | `@deepseek-ai/dsh-subagent-spawn-in-process` | | `subagent-fork-in-process` | `@deepseek-ai/dsh-subagent-fork-in-process` | | `tool-subagent-control` | `@deepseek-ai/dsh-tool-subagent-control` | diff --git a/apps/cli/config/examples/ptc.yml b/apps/cli/config/examples/ptc.yml index d0c2cc888a..65905eacdd 100644 --- a/apps/cli/config/examples/ptc.yml +++ b/apps/cli/config/examples/ptc.yml @@ -3,3 +3,8 @@ - id: tool-executor-ptc disabled: false + +# PTC mode exposes the pre-apply_patch tool set, as the Web ptc preset does. +- id: tool-fs + config: + applyPatch: false diff --git a/apps/cli/package.json b/apps/cli/package.json index 463f4f1b9e..c194a246b9 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -38,7 +38,6 @@ "@deepseek-ai/dsh-compaction-basic": "workspace:*", "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-cordis-client-runner": "workspace:*", - "@deepseek-ai/dsh-experimental-agent-team-profile": "workspace:*", "@deepseek-ai/dsh-experimental-inspector-profile": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-goal": "workspace:*", @@ -127,9 +126,9 @@ "@deepseek-ai/dsh-bash-local": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", - "@deepseek-ai/dsh-experimental-agent-team": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-experimental-ptc-runtime-python": "workspace:*", - "@deepseek-ai/dsh-experimental-tool-agent-team": "workspace:*", + "@deepseek-ai/dsh-tool-agent-team": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", "@deepseek-ai/dsh-fs-sandbox": "workspace:*", "@deepseek-ai/dsh-host-frontend-static": "workspace:*", diff --git a/apps/cli/tests/agent-team-headless.e2e.ts b/apps/cli/tests/agent-team-headless.e2e.ts index dd4e456252..e38a33777d 100644 --- a/apps/cli/tests/agent-team-headless.e2e.ts +++ b/apps/cli/tests/agent-team-headless.e2e.ts @@ -17,7 +17,7 @@ function records(content: string): Record[] { } describe('dsh run with Agent Teams enabled', () => { - it('runs two teammates, direct peer messages, dependent tasks, waiting, and final aggregation', async () => { + it('runs two teammates, sibling messages, dependent tasks, waiting, and final aggregation', async () => { const cwd = await mkdtemp(join(tmpdir(), 'dsh-agent-team-headless-')) try { const home = join(cwd, '.dsh') @@ -27,15 +27,12 @@ describe('dsh run with Agent Teams enabled', () => { await writeFile(join(profileDir, 'package.json'), JSON.stringify({ name: 'dsh-profile-headless', private: true, - dependencies: { - '@deepseek-ai/dsh-experimental-agent-team-profile': 'workspace:^', - }, + dependencies: {}, dsh: { profile: { bundles: [ '@deepseek-ai/dsh-base', '@deepseek-ai/dsh-headless', - '@deepseek-ai/dsh-experimental-agent-team-profile', ], }, }, @@ -91,8 +88,8 @@ describe('dsh run with Agent Teams enabled', () => { const workflowChild = parsed.find(log => log.some(record => record.type === 'user/message' && JSON.stringify((record.data as { content: unknown }).content) === JSON.stringify([{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }]))) expect(workflowChild).toBeDefined() - expect(workflowChild!.find(record => record.type === 'subagent/descriptor')?.data) - .toMatchObject({ mode: 'continuable', provider: 'spawn' }) + const workflowDescriptor = workflowChild!.find(record => record.type === 'subagent/descriptor')?.data as Record + expect(workflowDescriptor).toMatchObject({ mode: 'continuable', provider: 'spawn' }) expect(workflowChild!.filter(record => record.type === 'user/message' && (record.data as { source: { kind: string } }).source.kind === 'user').map(record => record.data)) .toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })]) @@ -102,7 +99,15 @@ describe('dsh run with Agent Teams enabled', () => { }) expect(root).toBeDefined() const eventTypes = root!.map(record => record.type) - expect(eventTypes.filter(type => type === 'team/member')).toHaveLength(4) + expect(eventTypes).not.toContain('team/member') + const catalog = root!.filter(record => record.type === 'subagent/catalog').map(record => record.data) + expect(catalog).toEqual(expect.arrayContaining([ + expect.objectContaining({ version: 0, childId: workflowChild![0]?.id }), + expect.objectContaining({ version: 0, label: 'Own deterministic implementation.' }), + expect.objectContaining({ version: 0, label: 'Own deterministic research.' }), + ])) + for (const entry of catalog) expect(entry).not.toHaveProperty('name') + expect(eventTypes).not.toContain('subagent-name/bound') expect(eventTypes).not.toContain('team/message/queued') expect(eventTypes).not.toContain('team/message/delivered') const peerMessages = parsed.flatMap(log => log.filter(record => record.type === 'user/message' diff --git a/apps/cli/tests/optional-bundle-transitions.e2e.ts b/apps/cli/tests/optional-bundle-transitions.e2e.ts index b5a5eecbaf..8db33a3a87 100644 --- a/apps/cli/tests/optional-bundle-transitions.e2e.ts +++ b/apps/cli/tests/optional-bundle-transitions.e2e.ts @@ -171,8 +171,8 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option it('keeps the default host and minimal tool catalogs while every optional bundle is off', async () => { const minimal = await agent('minimal') const standard = await agent() - expect(names()).toEqual(['working_directory']) - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'working_directory']) + expect(names()).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) for (const name of ['str_replace_editor', 'session_search', 'terminal_open', 'ralph']) expect(names(standard.agent)).not.toContain(name) expect((await ctx.skills.list({ cwd: workspace, scope: standard.agent })).some(skill => skill.name === 'dsh-badge')).toBe(false) }) @@ -246,7 +246,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option expect(toolResult(owner.agent, 'badge-on')).toContain('dsh-badge.png') const minimal = await agent('minimal') expect((await ctx.skills.list({ cwd: workspace, scope: minimal.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'working_directory']) + expect(names(minimal.agent)).toEqual([process.platform === 'win32' ? 'pwsh' : 'bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) await select(bundles.badge, false) expect((await load('badge-after')).isError).toBe(true) }) diff --git a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl index 19495490be..8467970106 100644 --- a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl +++ b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-round-driver/session.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable two-round goal for the ACP snapshot, inspect it, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Create a durable two-round goal","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl index 7e3a02fce9..a4ac54b8c1 100644 --- a/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl +++ b/apps/cli/tests/profiles/acp/tests/goal-expected/goal-wrapup/session.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Create a durable goal for the wrap-up snapshot, then report readiness."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Create a durable goal for","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts b/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts index 259ba7341e..63715e4638 100644 --- a/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts +++ b/apps/cli/tests/profiles/acp/tests/image-offload.expected.e2e.ts @@ -117,6 +117,7 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn }, }) expect(result.stderr).toBe('') + if (result.sessionId === undefined) throw new Error('image-offload scenario did not create a session') expect(requests).toHaveLength(2) expect(fileRequests).toEqual([{ method: 'POST', path: filesPath, bytes: 69 }]) const attachmentDigest = 'b1ff9c8ea3a780bad09b346c423d2d0e46815926879b18e841d928376a946640' @@ -139,10 +140,13 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn const fileImage = { type: 'image', source: { type: 'file', file_id: 'file-api-snapshot-1' } } const offloadedImage = `[image omitted to fit request image limits; ${attachmentId}.${normalizedAccess}]` const imageHandle = `Image ${attachmentId}; request preview 1x1px.${normalizedAccess}` - const runtimeContext = (cwd: string): string => 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\n' + const runtimeContext = (cwd: string, sessionId: string): string => 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\n' + `Current working directory: ${JSON.stringify(cwd)}.\n\n` + 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\n' - + 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).' + + 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\n' + + `You are the root agent. Your agent id is ${JSON.stringify(sessionId)}.\n\n` + + 'To message other agents, use send_message({ agent_id: "", message: "..." }).\n' + + 'Use list_agents({}) to find your collaborator agents and their ids.' const messages = requests[0]?.messages as { content?: unknown }[] | undefined const offloaded = messages?.find(message => JSON.stringify(message.content).includes('[image omitted')) expect(offloaded?.content).toEqual([ @@ -152,7 +156,7 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn { type: 'text', text: imageHandle }, fileImage, { type: 'text', text: ', then use read_image on red.png and reply with DONE.' }, - { type: 'text', text: runtimeContext(result.cwd) }, + { type: 'text', text: runtimeContext(result.cwd, result.sessionId) }, ]) const followup = requests[1]?.messages as Array<{ role: string; content: Array> }> @@ -188,6 +192,7 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn }, }) expect(fallback.stderr).toBe('') + if (fallback.sessionId === undefined) throw new Error('image-offload fallback scenario did not create a session') expect(fileRequests).toEqual([ { method: 'POST', path: filesPath, bytes: 69 }, { method: 'POST', path: filesPath, bytes: 69 }, @@ -203,7 +208,7 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn { type: 'text', text: `Image ${attachmentId}; request preview 1x1px.${fallbackAccess}` }, { type: 'image', source: { type: 'base64', media_type: 'image/png', data: image } }, { type: 'text', text: ', then use read_image on red.png and reply with DONE.' }, - { type: 'text', text: runtimeContext(fallback.cwd) }, + { type: 'text', text: runtimeContext(fallback.cwd, fallback.sessionId) }, ]) } finally { await new Promise(resolve => server.close(() => { resolve() })) diff --git a/apps/cli/tests/profiles/fixtures/official-installer-observer.mjs b/apps/cli/tests/profiles/fixtures/official-installer-observer.mjs index 5ca8db1ac6..4acea7354d 100644 --- a/apps/cli/tests/profiles/fixtures/official-installer-observer.mjs +++ b/apps/cli/tests/profiles/fixtures/official-installer-observer.mjs @@ -88,7 +88,7 @@ async function exercise(ctx, config) { // A transitive repository package the registry served, absent from npm at this version. const localDependency = JSON.parse(await readFile(join(config.profile, 'node_modules', config.localDependency, 'package.json'), 'utf8')).version const provider = name.endsWith('-codex') ? 'codex' : 'claude-code' - const providerEnabled = ctx.subagents.list().includes(provider) + const providerEnabled = ctx.subagents.getProvider(provider) !== undefined const nativeDir = join(config.profile, 'node_modules', config.nativePackages[name]) const binaryName = `${provider === 'codex' ? 'codex' : 'claude'}${process.platform === 'win32' ? '.exe' : ''}` const nativeBinary = (await readdir(nativeDir, { recursive: true })).find(path => basename(path) === binaryName) diff --git a/apps/cli/tests/profiles/headless/team-snapshot.patch.yml b/apps/cli/tests/profiles/headless/team-snapshot.patch.yml index dec80a9fe9..7a1d4c8a24 100644 --- a/apps/cli/tests/profiles/headless/team-snapshot.patch.yml +++ b/apps/cli/tests/profiles/headless/team-snapshot.patch.yml @@ -21,33 +21,7 @@ root: './.sessions' compression: none -- id: tool-subagent-control - disabled: true - -- id: tool-subagent-report - disabled: true - -- id: tool-subagent - disabled: true - -- id: tool-subagent-fork - disabled: true - - insert: - - id: agent-team - name: '@deepseek-ai/dsh-experimental-agent-team' - config: - maxMembers: 8 - maxTasks: 256 - maxMessageBytes: 65536 - disposalTimeoutMs: 5000 - - - id: tool-agent-team - name: '@deepseek-ai/dsh-experimental-tool-agent-team' - config: - freshProvider: spawn - forkProvider: fork - - id: team-fixture-llm name: './tests/fixtures/team-llm.mjs' diff --git a/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl index c54f84df0b..7779eb2181 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/goal-tools/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Probe strict-schema fillers against missing-goal revision 1, then create a durable goal to finish the snapshot proof and inspect it."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Probe strict-schema fillers against miss","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl index d45d98dfd0..d4385b311d 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/headless-profile/session.expected.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Prove the product headless profile path with one real tool round trip."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"cli-mock","model":"cli-mock","reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"cli-mock","model":"cli-mock"}} {"type":"session/title","data":{"title":"Prove the product headless profile","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl index e747f996ad..6cebc92a87 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/invalid-credential/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl index bc7c728199..8cc16706c1 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/missing-credential/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"say pong"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl index 5792ae3774..8488837003 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/provider-retry/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"retry the transient provider failure"}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"retry the transient provider failure","messageSeqs":[8],"source":{"kind":"fallback"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl index 11ae2ec827..c14e345b7f 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/semantic-checkpoint/session.expected.jsonl @@ -18,7 +18,7 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Continue safely from the interrupted operation."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Perform one side-effecting remote mutati","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl index 9da1c6379a..57f93111e7 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-diagnostic/parent.expected.jsonl @@ -16,13 +16,13 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Call list_agents once and report what it shows."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Start a background job.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"list-once","name":"list_agents","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"list-once","name":"list_agents","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"list-once","name":"list_agents","arguments":"{}"}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"{{sessionId}} [inactive] — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"list-once"},"toolCallId":"list-once","content":[{"type":"text","text":"{{sessionId}} [running] — root agent\n{{sessionId}} [inactive] parent={{sessionId}} depth=1 — descriptorless child"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"step/start","data":{"turn":2,"step":2}} {"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["The catalogued subagent is ready. PARENT_DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The catalogued subagent is ready. PARENT_DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl index b0372d96c6..27712bcd00 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/child.expected.jsonl @@ -2,13 +2,13 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Delegated write probe","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash","agentReasoningEffort":"low"}} {"type":"sandbox/mode","data":{"mode":"read-only","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"{{sessionId}}\".\nYour agent id is \"{{sessionId}}\".\nThe root agent of your collaboration tree is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"{{sessionId}}\".\nYour agent id is \"{{sessionId}}\".\nThe root agent of your collaboration tree is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index 3f3dee9c95..f8796478f5 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl @@ -16,20 +16,20 @@ {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} -{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} +{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":2,"step":1,"callId":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}} {"type":"subagent/catalog","data":{"version":0,"childId":"{{sessionId}}","childCreatedAt":0,"mode":"continuable","label":"Delegated write probe"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}} -{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"delegate-write"},"toolCallId":"delegate-write","content":[{"type":"text","text":"started subagent {{sessionId}}"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[23],"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}} +{"type":"tool/result","data":{"turn":2,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"delegate-write"},"toolCallId":"delegate-write","content":[{"type":"text","text":"started subagent {{sessionId}}"}],"isError":false,"id":"{{sessionId}}"},"meta":{"kind":"activation","subagentId":"{{sessionId}}"}},"sourceEventSeqs":[23],"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":2}} -{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_DENIED [sandbox: file access denied under read-only mode]"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":2,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"The delegated child was denied by the sandbox. PARENT_DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["The delegated child was denied by the sandbox. PARENT_DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"The delegated child was denied by the sandbox. PARENT_DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":2}} {"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl index c07532bd7d..2305a8a7c2 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/child.expected.jsonl @@ -2,13 +2,13 @@ {"type":"subagent/descriptor","data":{"version":3,"mode":"continuable","provider":"spawn","label":"Return child result","agentProvider":"deepseek-official","agentModel":"deepseek-v4-flash"}} {"type":"sandbox/mode","data":{"mode":"workspace-write","source":"delegation"}} {"type":"approval/policy","data":{"policy":"never","source":"delegation"}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"}]}} {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your parent agent id is \"{{sessionId}}\". Before you finish, send your result to that agent with send_message({ agent_id: \"{{sessionId}}\", message: \"\" }). The parent shares your workspace but does not automatically receive your transcript, tool output, or reasoning. Send earlier messages as well when a finding changes what the parent should do next; sending a message does not end your turn."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"{{sessionId}}\".\nYour agent id is \"{{sessionId}}\".\nThe root agent of your collaboration tree is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"{{sessionId}}\".\nYour agent id is \"{{sessionId}}\".\nThe root agent of your collaboration tree is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl index 441cab1aa2..f05ae06cef 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-settlement/stream-json.expected.jsonl @@ -4,7 +4,7 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":6,"time":0,"data":{"turn":1,"step":1}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"system/message","seq":7,"time":0,"data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Start one continuable subagent and acknowledge its completion notice. Do not call list_agents or send_message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/header","seq":10,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"Start one continuable subagent and","messageSeqs":[8],"source":{"kind":"fallback"}}}} @@ -13,15 +13,15 @@ {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":15,"time":0,"data":{"turn":1,"step":1,"callId":"start-child","name":"subagent","arguments":"{\"description\":\"Return child result\",\"prompt\":\"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message.\"}"}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":16,"time":0,"data":{"title":"Subagent settlement","messageSeqs":[8],"source":{"kind":"provider","provider":"session-title-first-prompt-llm","model":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"subagent/catalog","seq":17,"time":0,"data":{"version":0,"childId":"{{sessionId}}","childCreatedAt":0,"mode":"continuable","label":"Return child result"}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":18,"time":0,"data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"start-child"},"toolCallId":"start-child","content":[{"type":"text","text":"started subagent {{sessionId}}"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":18,"time":0,"data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"start-child"},"toolCallId":"start-child","content":[{"type":"text","text":"started subagent {{sessionId}}"}],"isError":false,"id":"{{sessionId}}"},"meta":{"kind":"activation","subagentId":"{{sessionId}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":19,"time":0,"data":{"turn":1,"step":1}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":20,"time":0,"data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":20,"time":0,"data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"}]}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":21,"time":0,"data":{"turn":1,"step":2}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":22,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"text","text":"STARTED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["STARTED"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"STARTED"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":23,"time":0,"data":{"turn":1,"step":2}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"agent/inbox/spliced","seq":24,"time":0,"data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/start","seq":25,"time":0,"data":{"turn":1,"step":3}}} -{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":26,"time":0,"data":{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} +{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"user/message","seq":26,"time":0,"data":{"content":[{"type":"text","text":"Background subagent {{sessionId}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"CHILD_RESULT"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{sessionId}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{sessionId}}"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":27,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"PARENT_RECEIVED_SETTLEMENT_NOTICE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["PARENT_RECEIVED_SETTLEMENT_NOTICE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"PARENT_RECEIVED_SETTLEMENT_NOTICE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":28,"time":0,"data":{"turn":1,"step":3}}} {"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":29,"time":0,"data":{"turn":1,"reason":{"kind":"completed"}}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl index cbb82cb603..56b127865a 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/offline-edit/session.expected.jsonl @@ -17,7 +17,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nUpdated instructions from: AGENTS.md\n\nThis file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.\n\nNew workspace instruction after offline edit.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","changes":[{"action":"replace","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"d8375b516f158718bd3463bc8eb7ed42c011b29f"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Remember the workspace instruction.","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl index 3bd9c55f95..dfe1d171a9 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/workspace-context-resume/precedence-change/session.expected.jsonl @@ -17,7 +17,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Acknowledge the current workspace instruction."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThis complete workspace instruction baseline replaces all earlier workspace instruction baselines. The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions.\n\nInstructions from: AGENTS.md\n\nCurrent AGENTS rule.\n\n\nInstructions from: CLAUDE.md\n\nCurrent CLAUDE rule.\n\n"}],"source":{"kind":"agent-instructions","form":"instructions","baseline":true,"baselineIdentity":"{\"projectRoot\":\"\",\"projectRootMarkers\":[\".git\"],\"maxBytes\":65536,\"maxSourceBytes\":1048576,\"instructionFileCandidates\":[\"AGENTS.md\",\"CLAUDE.md\"],\"localInstructionFileCandidates\":[\"AGENTS.local.md\",\"CLAUDE.local.md\"]}","changes":[{"action":"set","scope":".\u0000AGENTS.md","path":"AGENTS.md","digest":"7f53d2327837129750aef117f9754a001c46cf68"},{"action":"set","scope":".\u0000CLAUDE.md","path":"CLAUDE.md","digest":"5b1e9e3fd759eee6b43ceff899e47fb10c64701a"}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your agent id is \"{{sessionId}}\".\n\nTo message other agents, use send_message({ agent_id: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial","startsSeries":true}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Remember the workspace instruction.","messageSeqs":[3],"source":{"kind":"fallback"}}} diff --git a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs index 9c1bedd00e..62751cd93f 100644 --- a/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs +++ b/apps/cli/tests/profiles/headless/tests/fixtures/team-llm.mjs @@ -15,6 +15,12 @@ function latestAssistantCalls(messages) { return assistant?.content.filter(block => block.type === 'tool-call').map(block => block.name) ?? [] } +function hasNewCoordinationInput(messages) { + const toolIndex = messages.findLastIndex(message => message.role === 'tool') + return messages.some((message, index) => index > toolIndex && message.role === 'user' + && ['agent-message', 'subagent-settled'].includes(message.source?.kind)) +} + function hasTaskAction(messages, action) { return messages.some(message => message.role === 'assistant' && message.content.some((block) => { @@ -63,6 +69,11 @@ function textChunks(text) { function researcher(messages) { const names = calls(messages) + if (!names.includes('list_agents')) return toolChunks([{ name: 'list_agents', args: {} }]) + const sibling = messages.filter(message => message.role === 'tool') + .flatMap(message => message.content.filter(block => block.type === 'text').flatMap(block => block.text.split('\n'))) + .find(line => line.endsWith('— Own deterministic implementation.'))?.split(' ')[0] + if (sibling === undefined) throw new Error('list_agents did not expose the implementation sibling') if (!names.includes('team_task_create')) { return toolChunks([{ name: 'team_task_create', args: { subject: 'Research', description: 'Collect the deterministic finding.', write_scopes: ['research'], @@ -76,13 +87,13 @@ function researcher(messages) { if (!names.includes('send_message')) { return toolChunks([ { name: 'team_task_update', args: { task_id: 'task-1', expected_revision: 2, action: 'complete' } }, - { name: 'send_message', args: { target: 'implementer', message: 'Research complete: use the deterministic finding.' } }, + { name: 'send_message', args: { agent_id: sibling, message: 'Research complete: use the deterministic finding.' } }, ]) } return textChunks('Research teammate complete.') } -function implementer(messages) { +function implementer(messages, parentId) { const names = calls(messages) const last = latestAssistantCalls(messages) const text = latestToolText(messages) @@ -98,7 +109,7 @@ function implementer(messages) { write_scopes: ['implementation'], } }]) } - if (last.includes('wait_agent')) { + if (last.includes('wait_agent') || hasNewCoordinationInput(messages)) { return toolChunks([{ name: 'team_task_get', args: { task_id: 'task-1' } }]) } return toolChunks([{ name: 'wait_agent', args: { timeout_ms: 10000 } }]) @@ -109,10 +120,10 @@ function implementer(messages) { task_id: 'task-2', expected_revision: 1, action: 'claim', } }]) } - if (last.includes('team_task_get')) { - return toolChunks([{ name: 'team_task_get', args: { task_id: 'task-1' } }]) + if (last.includes('team_task_get') && !hasNewCoordinationInput(messages)) { + return toolChunks([{ name: 'wait_agent', args: { timeout_ms: 10000 } }]) } - if (last.includes('wait_agent')) { + if (last.includes('wait_agent') || hasNewCoordinationInput(messages)) { return toolChunks([{ name: 'team_task_get', args: { task_id: 'task-1' } }]) } return toolChunks([{ name: 'team_task_get', args: { task_id: 'task-1' } }]) @@ -123,7 +134,7 @@ function implementer(messages) { if (!names.includes('send_message')) { return toolChunks([ { name: 'team_task_update', args: { task_id: 'task-2', expected_revision: 2, action: 'complete' } }, - { name: 'send_message', args: { target: 'lead', message: 'Implementation complete and verified.' } }, + { name: 'send_message', args: { agent_id: parentId, message: 'Implementation complete and verified.' } }, ]) } return textChunks('Implementation teammate complete.') @@ -138,26 +149,22 @@ function lead(messages) { script: 'return await agent("TEAM_WORKFLOW_CHILD");', } }]) } - const spawned = names.filter(name => name === 'spawn_teammate').length + const spawned = names.filter(name => name === 'subagent').length if (spawned === 0) { return toolChunks([{ - name: 'spawn_teammate', + name: 'subagent', args: { - name: 'implementer', description: 'Own deterministic implementation.', prompt: 'IMPLEMENTER_MARK: wait for research, complete dependent task 2, report to lead.', - context: 'fresh', }, }]) } if (spawned === 1) { return toolChunks([{ - name: 'spawn_teammate', + name: 'subagent', args: { - name: 'researcher', description: 'Own deterministic research.', prompt: 'RESEARCHER_MARK: complete research task 1, message implementer, then finish.', - context: 'fresh', }, }]) } @@ -165,35 +172,38 @@ function lead(messages) { if (last.includes('team_task_list')) { const completed = result.match(/"status":"completed"/gu)?.length ?? 0 if (completed >= 2) return toolChunks([{ name: 'list_agents', args: {} }]) - return toolChunks([{ name: 'team_task_list', args: {} }]) + return toolChunks([{ name: hasNewCoordinationInput(messages) ? 'team_task_list' : 'wait_agent', + args: hasNewCoordinationInput(messages) ? {} : { timeout_ms: 10000 } }]) } if (last.includes('list_agents')) { - const inactive = result.match(/"status":"inactive"/gu)?.length ?? 0 + const inactive = result.split('\n') + .filter(row => row.includes('— Own deterministic ') && row.includes('[inactive]')).length if (inactive >= 2) return textChunks('TEAM_WORKFLOW_OK: both teammates and dependent tasks completed.') - return toolChunks([{ name: 'list_agents', args: {} }]) + return toolChunks([{ name: hasNewCoordinationInput(messages) ? 'list_agents' : 'wait_agent', + args: hasNewCoordinationInput(messages) ? {} : { timeout_ms: 10000 } }]) } - if (last.includes('wait_agent')) return toolChunks([{ name: 'team_task_list', args: {} }]) + if (last.includes('wait_agent') || hasNewCoordinationInput(messages)) return toolChunks([{ name: 'team_task_list', args: {} }]) return toolChunks([{ name: 'wait_agent', args: { timeout_ms: 10000 } }]) } class TeamFixtureAdapter extends LlmAdapter { async * stream(options) { const tools = options.tools.map(tool => tool.name) - if (tools.includes('subagent') || tools.includes('subagent_fork')) { - throw new Error('Team profile exposes a direct subagent tool') - } const initial = options.messages.findLast(message => message.role === 'user' && message.source.kind === 'user') const workflowChild = initial?.content[0]?.text === 'TEAM_WORKFLOW_CHILD' const context = options.messages.findLast(message => message.source?.kind === 'runtime-context') - const identity = context?.source.sections?.find(section => section.name === 'team:identity')?.text - if (!workflowChild && (!tools.includes('spawn_teammate') || !tools.includes('workflow'))) { - throw new Error('Team profile is missing teammate or workflow tools') + const section = name => context?.source.sections?.find(candidate => candidate.name === name)?.text + const role = section('subagent:identity') + const parentId = role?.match(/You are a subagent delegated by agent "([^"]+)"/u)?.[1] + const task = initial?.content.filter(block => block.type === 'text').map(block => block.text).join('\n') + if (!workflowChild && (!tools.includes('subagent') || !tools.includes('workflow') || !tools.includes('team_task_create'))) { + throw new Error('Team profile is missing delegation, workflow, or task tools') } let chunks if (workflowChild) chunks = textChunks('Fresh workflow child complete.') - else if (identity?.startsWith('You are teammate "researcher".')) chunks = researcher(options.messages) - else if (identity?.startsWith('You are teammate "implementer".')) chunks = implementer(options.messages) - else if (identity?.startsWith('You are the Team Lead named "lead".')) chunks = lead(options.messages) + else if (task?.startsWith('RESEARCHER_MARK:')) chunks = researcher(options.messages) + else if (task?.startsWith('IMPLEMENTER_MARK:')) chunks = implementer(options.messages, parentId) + else if (role?.startsWith('You are the root agent. Your agent id is')) chunks = lead(options.messages) else throw new Error('Team runtime context is missing a recognized identity') for (const chunk of chunks) { options.signal?.throwIfAborted() @@ -205,9 +215,30 @@ class TeamFixtureAdapter extends LlmAdapter { /** Cordis plugin name. */ export const name = 'team-fixture-llm' /** LLM registry dependency. */ -export const inject = ['llm'] +export const inject = ['llm', 'tools', 'agentTeams'] /** Register the keyless adapter on the shipped default provider route. */ export function apply(ctx) { + ctx.on('agent/created', async ({ agent }) => { + if (agent.session.header.parentSession === undefined) await ctx.agentTeams.setEnabled(agent, true) + }) + const implementerWaiting = Promise.withResolvers() + const leadWaiting = Promise.withResolvers() + for (const gate of [implementerWaiting, leadWaiting]) void gate.promise.catch(() => undefined) + ctx.effect(() => () => { + implementerWaiting.reject(new Error('Team fixture disposed before implementer wait')) + leadWaiting.reject(new Error('Team fixture disposed before lead wait')) + }) + ctx.on('tools/execute', async (exec, next) => { + if (exec.name === 'team_task_create' && exec.arguments.subject === 'Research') { + await Promise.all([implementerWaiting.promise, leadWaiting.promise]) + } + const result = next() + if (exec.name === 'wait_agent') { + if (exec.agent.session.header.origin === 'subagent') implementerWaiting.resolve() + else leadWaiting.resolve() + } + return result + }) ctx.llm.registerAdapter(['deepseek-official'], new TeamFixtureAdapter()) } diff --git a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts index a2ae0c9f19..9f53fb980a 100644 --- a/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/headless.expected.e2e.ts @@ -1093,7 +1093,7 @@ describe('headless stream-json snapshots', () => { } }, LOADER_SMOKE_TEST_TIMEOUT_MS) - it('runs a keyless Agent Team with peer mail, dependent tasks, waiting, and Lead aggregation', async () => { + it('runs a keyless Agent Team with described teammates, sibling messages, dependent tasks, waiting, and Lead aggregation', async () => { let projection: unknown const result = await runLoaderSmoke({ label: 'Agent Teams headless snapshot', @@ -1125,8 +1125,8 @@ describe('headless stream-json snapshots', () => { expect(workflowRows.filter(row => row.type === 'user/message' && ((row.data as JsonObject).source as JsonObject).kind === 'user').map(row => row.data)) .toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'TEAM_WORKFLOW_CHILD' }] })]) - const members = rows.filter(row => row.type === 'team/member') - .map(row => ((row.data as JsonObject).member as JsonObject)) + const teammates = rows.filter(row => row.type === 'subagent/catalog') + .flatMap(row => typeof (row.data as JsonObject).label === 'string' && ((row.data as JsonObject).label as string).startsWith('Own deterministic ') ? [(row.data as JsonObject).label as string] : []) const tasks = rows.filter(row => row.type === 'team/task') .map(row => ((row.data as JsonObject).task as JsonObject)) const latestTasks = Object.values(Object.fromEntries(tasks.map(task => [String(task.subject), task]))) @@ -1179,21 +1179,51 @@ describe('headless stream-json snapshots', () => { && ((row.data as JsonObject).source as JsonObject).kind === 'user') if (initial === undefined) throw new Error('Teammate Session has no initial task') const content = (initial.data as JsonObject).content as JsonObject[] - expect(content).toHaveLength(1) + // The task block is followed by the standard return guidance naming the Lead. + expect(content).toHaveLength(2) const context = parseJsonl(log.content).find(row => row.type === 'user/message' && ((row.data as JsonObject).source as JsonObject).kind === 'runtime-context') const source = (context?.data as JsonObject)?.source as JsonObject const sections = source?.sections as JsonObject[] | undefined - const identity = sections?.find(section => section.name === 'team:identity')?.text - if (typeof identity !== 'string') throw new Error('Teammate runtime context has no identity') - return [identity] + const leadId = parent.header.id as string + const text = (name: string) => { + const value = sections?.find(section => section.name === name)?.text + if (typeof value !== 'string') throw new Error(`Teammate runtime context has no ${name}`) + return value.replaceAll(log.header.id as string, '').replaceAll(leadId, '') + } + expect(sections?.some(section => section.name === 'team:identity')).toBe(false) + return [text('subagent:identity')] }).sort() + const allRows = logs.flatMap(log => parseJsonl(log.content)) + const messageSources = allRows.flatMap((row) => { + const data = row.data as JsonObject + if (row.type === 'user/message') return [(data.source as JsonObject).kind] + if (row.type === 'agent/inbox/spliced') { + return (data.inserted as JsonObject[]).map(message => (message.source as JsonObject).kind) + } + return [] + }) + expect(messageSources).not.toContain('team-task-change') + const waitIds = new Set(allRows.filter(row => row.type === 'tool/call' + && (row.data as JsonObject).name === 'wait_agent').map(row => (row.data as JsonObject).callId)) + const waitResults = allRows.filter((row) => { + if (row.type !== 'tool/result') return false + const message = (row.data as JsonObject).message as JsonObject + return waitIds.has((message.source as JsonObject).callId) + }) + expect(waitResults).toHaveLength(waitIds.size) + for (const row of waitResults) { + const message = (row.data as JsonObject).message as JsonObject + expect(message.isError).not.toBe(true) + const content = message.content as JsonObject[] + expect(JSON.parse(content.filter(block => block.type === 'text').map(block => block.text).join(''))) + .toEqual({ timedOut: false }) + } projection = { sessions: logs.length, workflowStopReason: (rows.find(row => row.type === 'tool-workflow/run-end')?.data as JsonObject)?.stopReason, - memberEdges: members.length, identities, - activeMembers: members.filter(member => member.phase === 'active').map(member => member.name).sort(), + teammates: [...teammates].sort(), tasks: latestTasks.map(task => ({ subject: task.subject, revision: task.revision, @@ -1203,7 +1233,7 @@ describe('headless stream-json snapshots', () => { deliveredMessages: rows.filter(row => row.type === 'team/message/delivered').length, waited: rows.some(row => row.type === 'tool/call' && (row.data as JsonObject).name === 'wait_agent'), - checkedRoster: rows.some(row => row.type === 'tool/call' + checkedAgents: rows.some(row => row.type === 'tool/call' && (row.data as JsonObject).name === 'list_agents'), steerEvidence: { nextStepInbox: steeredInboxIndex >= 0, @@ -1221,25 +1251,22 @@ describe('headless stream-json snapshots', () => { }) expect(projection).toMatchInlineSnapshot(` { - "activeMembers": [ - "implementer", - "researcher", - ], - "checkedRoster": true, + "checkedAgents": true, "deliveredMessages": 0, "identities": [ - "You are teammate "implementer". - Your Team Lead is named "lead". - To message your Team Lead, use send_message({ target: "lead", message: "..." }). - Use list_agents({}) to find your teammates and their names. - To message another teammate, use send_message({ target: "", message: "..." }).", - "You are teammate "researcher". - Your Team Lead is named "lead". - To message your Team Lead, use send_message({ target: "lead", message: "..." }). - Use list_agents({}) to find your teammates and their names. - To message another teammate, use send_message({ target: "", message: "..." }).", + "You are a subagent delegated by agent "". + Your agent id is "". + The root agent of your collaboration tree is "". + + To message other agents, use send_message({ agent_id: "", message: "..." }). + Use list_agents({}) to find your collaborator agents and their ids.", + "You are a subagent delegated by agent "". + Your agent id is "". + The root agent of your collaboration tree is "". + + To message other agents, use send_message({ agent_id: "", message: "..." }). + Use list_agents({}) to find your collaborator agents and their ids.", ], - "memberEdges": 4, "queuedMessages": 0, "sessions": 4, "steerEvidence": { @@ -1260,6 +1287,10 @@ describe('headless stream-json snapshots', () => { "subject": "Research", }, ], + "teammates": [ + "Own deterministic implementation.", + "Own deterministic research.", + ], "waited": true, "workflowStopReason": "completed", } diff --git a/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts b/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts index 941d95c31d..3aff474038 100644 --- a/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts +++ b/apps/cli/tests/profiles/headless/tests/subagent-diagnostic.expected.e2e.ts @@ -1,6 +1,6 @@ /** * Assembled-app regression: a parent-owned catalog event remains sufficient - * for direct discovery when the persisted child has no descriptor event. + * for descendant discovery when the persisted child has no descriptor event. */ import { readFile, readdir, writeFile } from 'node:fs/promises' @@ -42,7 +42,7 @@ async function expectSession(actual: string, expectedPath: string): Promise { const ctx = new Context() @@ -106,7 +106,7 @@ async function seedCataloguedDescriptorlessChild(root: string, cwd: string): Pro } describe('parent-owned cold child catalog snapshot', () => { - it('discovers a catalogued child without reading its descriptor through the assembled headless app', async () => { + it('discovers a descriptorless catalogued child with its tree position through the assembled headless app', async () => { let cwd = '' const result = await runLoaderSmoke({ label: 'subagent diagnostic headless stream-json snapshot', @@ -131,9 +131,8 @@ describe('parent-owned cold child catalog snapshot', () => { const parent = logs.find(content => content.includes('"subagent-diagnostic-parent"')) if (parent === undefined) throw new Error('missing persisted parent log') - // THE model-visible fact: the parent catalog supplies discovery even - // though consulting the descriptor-less child would classify it corrupt. - expect(parent).toContain(`${childId} [inactive] — descriptorless child`) + // Discovery reads child catalogs without requiring activation descriptors. + expect(parent).toContain(`${childId} [inactive] parent=${parentId} depth=1 — descriptorless child`) expect(parent).not.toContain('[diagnostic: corrupt]') const context: NormalizeContext = { sessionIds: [parentId, childId], cwd } diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index bee0a10775..a232e82874 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -58,11 +58,16 @@ describe('Python SDK dsh profile keyless smoke', () => { { label: 'reports max-token turns with mapping disabled through env', envValue: 'false', editorEnabled: false }, { label: 'allows an explicit patch to enable str_replace_editor', envValue: undefined, editorEnabled: true }, { label: 'uses the PTC executor overlay despite the retired environment selector', envValue: undefined, editorEnabled: false, ptc: true }, + // The shipped sdk profile mounts no observation policy: an edit of a file the model never read lands on disk. + { label: 'edits a file the model never read through the shipped profile', envValue: undefined, editorEnabled: false, unreadEdit: true }, ])('$label', async (scenario) => { const { envValue, editorEnabled } = scenario const ptc = 'ptc' in scenario && scenario.ptc + const unreadEdit = 'unreadEdit' in scenario && scenario.unreadEdit const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-smoke-')) + const unreadFile = join(root, 'notes.txt') + if (unreadEdit) await writeFile(unreadFile, 'alpha\n') const editorPatch = join(root, 'editor.patch.yml') if (editorEnabled) await writeFile(editorPatch, [ '- insert:', @@ -78,7 +83,14 @@ describe('Python SDK dsh profile keyless smoke', () => { request.on('end', () => { modelRequests.push(JSON.parse(body) as Record) response.writeHead(200, { 'content-type': 'text/event-stream' }) - response.end(messagesResponse({ type: 'text', text: 'done' }, 'max_tokens')) + if (unreadEdit && modelRequests.length === 1) { + response.end(messagesResponse({ + type: 'tool_use', id: 'unread-edit', name: 'edit', + input: { file_path: 'notes.txt', old_string: 'alpha', new_string: 'beta' }, + }, 'tool_use')) + return + } + response.end(messagesResponse({ type: 'text', text: 'done' }, unreadEdit ? 'end_turn' : 'max_tokens')) }) }) await new Promise(resolve => modelServer.listen(0, '127.0.0.1', resolve)) @@ -164,21 +176,27 @@ describe('Python SDK dsh profile keyless smoke', () => { sessionId: 'main', event: { type: 'turn/end', - data: { reason: { kind: 'max-tokens' } }, + data: { reason: { kind: unreadEdit ? 'completed' : 'max-tokens' } }, }, }, }) + if (unreadEdit) { + expect(modelRequests).toHaveLength(2) + expect(await readFile(unreadFile, 'utf8')).toBe('beta\n') + } expect(modelRequests[0]?.tools).toEqual(expect.any(Array)) const tools = modelRequests[0]?.tools as { name?: string }[] const toolNames = tools.map(tool => tool.name) expect(modelRequests[0]?.output_config).toEqual({ effort: 'max' }) expect(modelRequests[0]?.max_tokens).toBe(1234) - const expectedTools = ['read', 'write', 'edit', 'web_fetch', 'web_search', 'subagent', 'subagent_fork', - 'present', 'ask_user_question', 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update', 'plugin_manager'] + const expectedTools = ['read', 'write', 'edit', 'apply_patch', 'web_fetch', 'web_search', 'subagent', 'subagent_fork', + 'present', 'ask_user_question', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'plugin_manager'] const requestText = JSON.stringify(modelRequests[0]) if (ptc) { expect(toolNames).toEqual(['run_code']) - for (const tool of expectedTools) expect(requestText.includes(`${tool}:`), tool).toBe(true) + // The PTC overlay keeps the pre-apply_patch tool set, as the Web ptc preset does. + for (const tool of expectedTools.filter(tool => tool !== 'apply_patch')) expect(requestText.includes(`${tool}:`), tool).toBe(true) + expect(requestText.includes('apply_patch:')).toBe(false) } else { expect(toolNames).toEqual(expect.arrayContaining(expectedTools)) expect(toolNames.includes('str_replace_editor')).toBe(editorEnabled) diff --git a/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts b/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts index d031001f95..a4cb88f925 100644 --- a/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts +++ b/apps/cli/tests/profiles/sdk/schedule-resume.e2e.ts @@ -1,4 +1,4 @@ -/** Reminder activation must share SDK ownership and initialized model limits after process restart. */ +/** Schedule authoring and restart delivery must honor the shipped SDK composition. */ import { createServer } from 'node:http' import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' @@ -30,7 +30,8 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t if (restarting) restored.push(request) const content = requests.length === 1 ? { type: 'tool_use', id: 'create-reminder', name: 'schedule_create', - input: { title: 'Check SDK', prompt: 'Report the SDK reminder', after_seconds: 86400 }, + input: { title: 'Check SDK', prompt: 'Report the SDK reminder', + rrule: 'DTSTART:20300102T000000Z\nRRULE:FREQ=DAILY;COUNT=1', target: 'this_session' }, } : { type: 'text', text: 'ready' } response.writeHead(200, { 'content-type': 'text/event-stream' }) response.end(messagesResponse(content, requests.length === 1 ? 'tool_use' : 'end_turn')) @@ -70,3 +71,64 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t const session = await second.resumeSession('saved') expect(await session.run('Continue after the reminder')).toMatchObject({ finalResponse: 'ready' }) }) + +it('refuses new Session destinations before storing tasks in the shipped SDK profile', async () => { + const root = await mkdtemp(join(tmpdir(), 'sdk-schedule-targets-')) + const requests: Record[] = [] + const calls = ['new', 'new_once', 'this_session'].flatMap(target => [ + { type: 'tool_use', id: `create-${target}`, name: 'schedule_create', + input: { title: `SDK ${target}`, prompt: 'Check SDK', + rrule: 'DTSTART:20300102T000000Z\nRRULE:FREQ=DAILY;COUNT=1', target } }, + { type: 'tool_use', id: `list-${target}`, name: 'schedule_list', input: {} }, + ]) + const server = createServer((incoming, response) => { + let body = '' + incoming.setEncoding('utf8') + incoming.on('data', (chunk: string) => { body += chunk }) + incoming.on('end', () => { + const content = calls[requests.length] ?? { type: 'text', text: 'ready' } + requests.push(JSON.parse(body) as Record) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(messagesResponse(content, content.type === 'tool_use' ? 'tool_use' : 'end_turn')) + }) + }) + const clients: DeepSeekHarness[] = [] + onTestFinished(async () => { + try { await Promise.all(clients.map(client => client.close())) } finally { + try { + await new Promise((resolve, reject) => { + server.close((error) => { if (error === undefined) resolve(); else reject(error) }) + }) + } finally { await rm(root, { recursive: true, force: true }) } + } + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('model fixture has no port') + const env = { ...process.env, DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1', + DEEPSEEK_API_KEY: 'keyless-schedule-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${String(address.port)}` } + clearAmbientProxyEnv(env) + const client = new DeepSeekHarness({ cwd: root, dshHome: join(root, '.dsh'), + model: 'deepseek-v4-pro', initializeTimeoutMs: 30_000, env }) + clients.push(client) + expect((await client.session('schedule-owner').run('Check the supported schedule destinations')).finalResponse).toBe('ready') + expect(requests).toHaveLength(calls.length + 1) + const results = calls.map((call, index) => { + const messages = requests[index + 1]?.messages as { + content: { type: string; tool_use_id?: string; content?: { type: string; text?: string }[] }[] + }[] + const result = messages.flatMap(message => message.content) + .find(block => block.type === 'tool_result' && block.tool_use_id === call.id) + const text = result?.content?.find(block => block.type === 'text')?.text + if (text === undefined) throw new Error(`SDK model request has no result for ${call.id}`) + return JSON.parse(text) as Record + }) + for (const index of [0, 2]) { + expect(results[index]).toMatchObject({ + code: 'invalid_rule', message: expect.stringContaining('choose an existing Session target') as string, + }) + expect(results[index + 1]).toMatchObject({ items: [], shown: 0, total: 0 }) + } + expect(results[4]).toMatchObject({ title: 'SDK this_session', target: { kind: 'session', sessionId: 'schedule-owner' } }) + expect(results[5]).toMatchObject({ items: [results[4]], shown: 1, total: 1 }) +}) diff --git a/apps/cli/tests/profiles/web/tests/default-web-process.ts b/apps/cli/tests/profiles/web/tests/default-web-process.ts index 537ac77702..155f8d6670 100644 --- a/apps/cli/tests/profiles/web/tests/default-web-process.ts +++ b/apps/cli/tests/profiles/web/tests/default-web-process.ts @@ -55,7 +55,7 @@ export async function withDefaultWeb( await writeFile(patch, JSON.stringify([{ insert: [{ id: 'runtime-roster-observer', name: pathToFileURL(join(root, 'fixtures/runtime-roster-observer.js')).href, - config: { negativeControl: pathToFileURL(join(repoRoot, 'packages/experimental/client-ui-agent-team/lib/index.js')).href }, + config: { negativeControl: pathToFileURL(join(repoRoot, 'packages/experimental/client-ui-voice-input/lib/index.js')).href }, }] }]) + '\n') const launch = resolveExampleLaunch({ srcBin: join(repoRoot, 'apps/cli/src/bin.ts'), diff --git a/apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts index 063f578de9..b307a9ee8e 100644 --- a/apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts @@ -1,14 +1,18 @@ -/** Built CLI, public Remote requests, and persisted task files; seeded receipts are not delivery evidence. */ +/** + * Built CLI, public Remote requests, and persisted task files; seeded receipts are not delivery evidence. + * Existing rows load without writes; edits keep the envelope and store the current target shape. + */ import { randomUUID } from 'node:crypto' import { mkdir, readFile, writeFile } from 'node:fs/promises' import { join } from 'node:path' -import type { DailyScheduleRecord, ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule' +import type { SessionId } from '@deepseek-ai/dsh-session' +import type { DailyScheduleRecord, ScheduleCatalogEntry, ScheduleTask } from '@deepseek-ai/dsh-schedule' import { expect, it } from 'vitest' import { withDefaultWeb, webGet, webRequest } from './default-web-process.ts' const id = 'retained-remote-task' as DailyScheduleRecord['id'] -const sessionId = 'unloaded-owner' as ScheduleCatalogEntry['sessionId'] +const sessionId = 'unloaded-owner' as SessionId const record: DailyScheduleRecord = { id, kind: 'daily', title: 'Retained instruction', prompt: 'Retained instruction\nwith a second line', time: '09:00:00.125', timeZone: 'Asia/Shanghai', scheduledAt: '2099-01-01T01:00:00.125Z', @@ -20,15 +24,33 @@ const task = { sessionId, record, status: 'active', lastDelivery, deliveryHistory: { earlierRecordsUnavailable: false, records: [{ ...lastDelivery, prompt: record.prompt }] }, } -const taskPath = (root: string) => join(root, 'home', 'storages', 'schedule.json') - -async function seed(root: string, bytes: string): Promise { - await mkdir(join(root, 'home', 'storages'), { recursive: true }) - await writeFile(taskPath(root), bytes) +const source = `${JSON.stringify({ unit: { name: 'schedule', version: 1 }, global: null, tables: { tasks: { [id]: task } } }, null, 2)}\n` +const sourcePath = (root: string) => join(root, 'home', 'storages', 'schedule.json') +const receipt = { ...lastDelivery, targetSessionId: sessionId } +const historyRequest = { request: { id, limit: 20 } } +const expectedHistory = { + ok: true, + value: { + id, records: [{ ...receipt, prompt: record.prompt }], earlierRecordsUnavailable: false, + earlierRecordsPruned: false, retention: { days: 30, records: 200 }, + }, } -function encoded(value: unknown): string { - return `${JSON.stringify({ unit: { name: 'schedule', version: 1 }, global: null, tables: { tasks: { [id]: value } } }, null, 2)}\n` +/** Catalog entry retains the stored daily rule and has no invented creation or change times. */ +const retainedEntry = (title: string) => expect.objectContaining({ + id, title, prompt: record.prompt, scheduledAt: record.scheduledAt, target: { kind: 'session', sessionId }, + involvedSessionIds: [sessionId], status: 'active', lastDelivery: receipt, + kind: 'daily', time: record.time, timeZone: record.timeZone, +}) as object + +/** Seed the existing domain or the exact bytes a preceding Host edited. */ +async function seed(root: string, bytes = source): Promise { + await mkdir(join(root, 'home', 'storages'), { recursive: true }) + await writeFile(sourcePath(root), bytes) +} + +async function readStore(root: string): Promise { + return readFile(sourcePath(root), 'utf8') } async function connect(url: string, signal: AbortSignal) { @@ -48,71 +70,84 @@ async function connect(url: string, signal: AbortSignal) { } } -it('edits a retained task through built Remote bindings and preserves its identity and seeded history after cold startup', async (test) => { - let persisted = encoded(task) - let updated = record - const historyRequest = { request: { sessionId, id, limit: 20 } } - const expectedHistory = { - ok: true, - value: { - id, records: task.deliveryHistory.records, earlierRecordsUnavailable: false, - earlierRecordsPruned: false, retention: { days: 30, records: 200 }, - }, - } +it('edits an existing task through built Remote bindings and keeps its identity and seeded history after cold startup', async (test) => { + let persisted: string | undefined + let renamed: ScheduleCatalogEntry | undefined await withDefaultWeb(test, async ({ root, url }) => { const rpc = await connect(url, test.signal) - expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [{ ...record, sessionId, status: 'active', lastDelivery }] }) + const catalog = await rpc('schedule/catalog', {}) + expect(catalog).toEqual({ ok: true, value: [retainedEntry(record.title)] }) expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) - const target = new Date(Date.now() + 12 * 60 * 60 * 1_000) - target.setUTCMilliseconds(125) - updated = { ...record, time: target.toISOString().slice(11, 23), timeZone: 'UTC', scheduledAt: target.toISOString() } - const change = { kind: 'daily', daily: { time: updated.time, time_zone: 'UTC' } } - expect(await rpc('schedule/update', { request: { sessionId, id, expected: record, change } })) - .toEqual({ ok: true, value: { id, updated: true, record: updated } }) - persisted = await readFile(taskPath(root), 'utf8') - expect(JSON.parse(persisted)).toEqual({ - unit: { name: 'schedule', version: 1 }, - global: null, - tables: { tasks: { [id]: { ...task, record: updated } } }, + const { value: [retained] } = catalog as { value: ScheduleCatalogEntry[] } + const rename = { + request: { id, action: 'update', patch: { title: 'Renamed instruction' }, expectedUpdatedAt: retained?.updatedAt ?? null }, + } + const edited = await rpc('schedule/edit', rename) + expect(edited).toEqual({ ok: true, value: retainedEntry('Renamed instruction') }) + renamed = (edited as { value: ScheduleCatalogEntry }).value + persisted = await readStore(root) + const document = storedUnit(persisted) + expect(document.unit).toEqual({ name: 'schedule', version: 2 }) + expect(document.global).toBeNull() + expect(document.tables.tasks[id]!).toMatchObject({ record: { ...record, title: 'Renamed instruction' }, + target: { kind: 'session', sessionId }, status: 'active', updatedAt: renamed.updatedAt, lastDelivery: receipt }) + expect(document.tables.tasks[id]!).not.toHaveProperty('sessionId') + expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) + + expect(await rpc('schedule/edit', rename)).toEqual({ ok: true, value: { id, code: 'schedule_conflict' } }) + expect(await rpc('schedule/edit', { request: { id: 'missing-task', action: 'delete' } })) + .toEqual({ ok: true, value: { id: 'missing-task', code: 'schedule_not_found' } }) + expect(await readStore(root)).toEqual(persisted) + }, { prepare: root => seed(root) }) + + await withDefaultWeb(test, async ({ root, url }) => { + const rpc = await connect(url, test.signal) + expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [renamed] }) + expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) + expect(await readStore(root)).toEqual(persisted) + await rpc('session/create', { request: { sessionId, cwd: root } }) + const rrule = 'DTSTART;TZID=Asia/Shanghai:20990101T090000\nRRULE:FREQ=DAILY' + const replaced = await rpc('schedule/edit', { + request: { id, action: 'update', patch: { timing: { kind: 'rrule', rrule } }, expectedUpdatedAt: renamed?.updatedAt }, }) + expect(replaced).toEqual({ + ok: true, value: expect.objectContaining({ id, title: 'Renamed instruction', scheduledAt: '2099-01-01T01:00:00.000Z' }) as object, + }) + const stored = storedUnit(await readStore(root)).tables.tasks[id]! + expect(stored.record).toMatchObject({ kind: 'rrule', rrule }) + expect(stored).not.toHaveProperty('sessionId') + expect(stored).toMatchObject({ target: { kind: 'session', sessionId }, lastDelivery: receipt }) expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) - - expect(await rpc('schedule/update', { request: { sessionId, id, expected: record, change } })) - .toEqual({ ok: true, value: { id, updated: false, code: 'schedule_conflict' } }) - expect(await rpc('schedule/update', { request: { sessionId: 'other-owner', id, expected: updated, change } })) - .toEqual({ ok: true, value: { id, updated: false, code: 'schedule_not_found' } }) - expect(await readFile(taskPath(root), 'utf8')).toBe(persisted) - }, { prepare: root => seed(root, persisted) }) - - await withDefaultWeb(test, async ({ root, url }) => { - const rpc = await connect(url, test.signal) - expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [{ ...updated, sessionId, status: 'active', lastDelivery }] }) - expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) - expect(await rpc('schedule/update', { request: { - sessionId, id, expected: updated, change: { kind: 'daily', daily: { time: updated.time, time_zone: 'Etc/UTC' } }, - } })).toEqual({ ok: true, value: { id, updated: false, record: updated } }) - expect(await readFile(taskPath(root), 'utf8')).toBe(persisted) }, { prepare: root => seed(root, persisted) }) }) -it('creates and idempotently adopts the explicit Session id bound to seeded task data without touching its task file', async (test) => { - const persisted = encoded(task) - const expectedList = { ok: true, value: [record] } - const expectedHistory = { - ok: true, - value: { - id, records: task.deliveryHistory.records, earlierRecordsUnavailable: false, - earlierRecordsPruned: false, retention: { days: 30, records: 200 }, - }, - } +it('creates and idempotently adopts the explicit Session id bound to existing task data without touching its task files', async (test) => { await withDefaultWeb(test, async ({ root, url }) => { const rpc = await connect(url, test.signal) + // A Schedule request waits for startup to validate the task store. + const view = await rpc('schedule/view', { request: { id } }) + expect(view).toEqual({ ok: true, value: retainedEntry(record.title) }) + const retained = await readStore(root) const create = { request: { sessionId, cwd: root } } const expectedCreate = { ok: true, value: { sessionId, agentPreset: 'standard' } } expect(await rpc('session/create', create)).toEqual(expectedCreate) expect(await rpc('session/create', create)).toEqual(expectedCreate) - expect(await rpc('schedule/list', { request: { sessionId } })).toEqual(expectedList) - expect(await rpc('schedule/history', { request: { sessionId, id, limit: 20 } })).toEqual(expectedHistory) - expect(await readFile(taskPath(root), 'utf8')).toBe(persisted) - }, { prepare: root => seed(root, persisted) }) + expect(await rpc('schedule/view', { request: { id } })).toEqual(view) + expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory) + expect(await readStore(root)).toEqual(retained) + expect(await readFile(sourcePath(root), 'utf8')).toBe(source) + }, { prepare: root => seed(root) }) }) + +/** Read test-owned output without normalizing away the fields asserted below. */ +function storedUnit(text: string): { + readonly unit: unknown + readonly global: unknown + readonly tables: { readonly tasks: Record } +} { + return JSON.parse(text) as { + unit: unknown + global: unknown + tables: { tasks: Record } + } +} diff --git a/apps/cli/tests/profiles/web/tests/web-default-isolation.expected.e2e.ts b/apps/cli/tests/profiles/web/tests/web-default-isolation.expected.e2e.ts index 7563a323aa..687afcb6d8 100644 --- a/apps/cli/tests/profiles/web/tests/web-default-isolation.expected.e2e.ts +++ b/apps/cli/tests/profiles/web/tests/web-default-isolation.expected.e2e.ts @@ -7,7 +7,7 @@ import { modulePackage } from './runtime-roster.ts' import { experimentalRuntimeReferences } from './runtime-roster-isolation.ts' import { withDefaultWeb, webGet } from './default-web-process.ts' -const experimentalName = '@deepseek-ai/dsh-experimental-client-ui-agent-team' +const experimentalName = '@deepseek-ai/dsh-experimental-client-ui-voice-input' it('boots default Web with the shipped Schedule rows, without experimental modules, time context, or an active built-in Browser', async (test) => { await withDefaultWeb(test, async ({ url, request }) => { @@ -37,6 +37,9 @@ it('boots default Web with the shipped Schedule rows, without experimental modul // The shipped composition mounts the Host Schedule service and its task // page; the clock stays preset-level, so neither plane carries a row for it. expect(roster.entries).toEqual(expect.arrayContaining([ + expect.objectContaining({ name: '@deepseek-ai/dsh-agent-team', state: FiberState.ACTIVE }), + expect.objectContaining({ name: '@deepseek-ai/dsh-tool-agent-team', state: FiberState.ACTIVE }), + expect.objectContaining({ name: '@deepseek-ai/dsh-client-ui-agent-team', state: FiberState.ACTIVE }), expect.objectContaining({ name: '@deepseek-ai/dsh-schedule', state: FiberState.ACTIVE }), expect.objectContaining({ name: '@deepseek-ai/dsh-client-ui-schedule', state: FiberState.ACTIVE }), ])) @@ -50,7 +53,7 @@ it('boots default Web with the shipped Schedule rows, without experimental modul const mounted = contaminated.plugins.filter(plugin => plugin.modules.some(url => modulePackage(url) === experimentalName)) expect(mounted).toEqual([expect.objectContaining({ state: FiberState.ACTIVE })]) expect(experimentalRuntimeReferences(contaminated)).toEqual(expect.arrayContaining([ - expect.stringContaining('/packages/experimental/client-ui-agent-team/'), + expect.stringContaining('/packages/experimental/client-ui-voice-input/'), ])) }) }) diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index baac502987..792187acae 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -248,9 +248,9 @@ beforeAll(async () => { }, 120_000) describe('the shipped Web composition', () => { - it('exposes only the directory tool in the global layer', () => { - // Directory selection is global; action tools belong to their Agent presets. - expect(toolNames(ctx)).toEqual(['working_directory']) + it('registers the directory and conditional Team tools in the global layer', () => { + // Team registrations are shared; session mode controls their step-time availability. + expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) }) it('keeps the token meter and its context-meter projections on the host plane', async () => { @@ -300,11 +300,11 @@ describe('the shipped Web composition', () => { // excluded for the reason the TUI composition e2e excludes them — they // depend on ripgrep being present on the machine. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([ - 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', + 'apply_patch', 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', 'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'plugin_manager', 'present', 'read', 'read_image', - 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update', + 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'skill', - 'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search', + 'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search', 'workflow', 'working_directory', 'write', ]) expect(ctx.commands.find(handle.agent, 'goal')).toBeDefined() @@ -408,7 +408,7 @@ describe('the shipped Web composition', () => { expect(assembly.sections).toEqual([ { name: 'deployment:persona-prefix', text: MINIMAL_PROMPT }, ]) - expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'working_directory']) + expect(assembly.tools.map(tool => tool.name)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) expect(assembly.tools.find(tool => tool.name === 'bash')?.description).toBe(MINIMAL_BASH_DESCRIPTION) expect(ctx.commands.find(handle.agent, 'goal')).toBeUndefined() // serviceFor reports preset-owned providers; unisolated consumers inherit the host fs. @@ -485,7 +485,7 @@ describe('the shipped Web composition', () => { const last = adapter.requests.at(-1) expect(last?.messages.flatMap(message => message.content) .some(block => block.type === 'text' && block.text.includes('Preserve the requested project task.'))).toBe(true) - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) } finally { await handle.dispose() } @@ -529,7 +529,7 @@ describe('the shipped Web composition', () => { setup: agentCtx => ctx.agentPresets.mount(agentCtx, 'minimal').then(() => undefined), }) try { - expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'read_image', 'working_directory']) + expect(toolNames(ctx, minimal.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) expect(ctx.agentPresets.serviceFor(minimal.agent, 'compaction')) .not.toBe(ctx.agentPresets.serviceFor(full.agent, 'compaction')) @@ -538,7 +538,7 @@ describe('the shipped Web composition', () => { // Tearing the minimal session down leaves the full one whole. expect(toolNames(ctx, full.agent).length).toBeGreaterThan(10) - expect(toolNames(ctx)).toEqual(['working_directory']) + expect(toolNames(ctx)).toEqual(['team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) } finally { await full.dispose() } @@ -697,7 +697,7 @@ describe('the shipped Web composition', () => { // stays the preset's choice — minimal mounts no `tool-skill`, so its // tool table has no loader even though the global layer is readable. expect((await ctx.skills.list({ scope: handle.agent })).map(skill => skill.name)).toContain('dsh-badge') - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) } finally { await handle.dispose() } @@ -790,7 +790,7 @@ describe.each(['web', 'desktop'] as const)('%s native subagent bundles', (surfac const productCtx = await bootSelected(installed) const spawn = vi.spyOn(productCtx.subprocess, 'spawn') try { - expect(productCtx.subagents.list().filter(name => (products as readonly string[]).includes(name)).sort()) + expect(products.filter(name => productCtx.subagents.getProvider(name) !== undefined).sort()) .toEqual([...installed].sort()) const expected = installed.map(toolName).sort() for (const preset of ['standard', 'cordis', 'ptc', 'minimal']) { @@ -881,6 +881,8 @@ describe('a user preset declared from the shipped cordis rows', () => { // The `Tool` provider is the one built over the host context: it // answers with the shared registry's view of the REQUESTING agent, // so the copy sees its own preset's tools, not the host's empty set. + const spills = vi.spyOn(copyCtx.spillStore, 'saveText') + onTestFinished(() => { spills.mockRestore() }) const queried = await executeToolFixture(copyCtx, { callId: ToolCallId('copied-preset-inspect-tools'), name: 'cordis_inspect_query', @@ -889,11 +891,8 @@ describe('a user preset declared from the shipped cordis rows', () => { agent: copied.agent, }) expect(queried.isError).toBe(false) - // The whole-table answer can pass the inline token budget once the - // preset's tool table grows, and the spill policy then replaces its - // middle with a gap plus a spill footer. What this case proves is the - // provider's answer, so assert the names it must carry. - const queriedText = resultText(queried) + // The tool catalog may exceed the inline budget; assert its complete stored text. + const queriedText = spills.mock.calls.at(-1)?.[0].content ?? resultText(queried) for (const toolName of ['bash', 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager']) { expect(queriedText).toContain(`"name": "${toolName}"`) } @@ -1004,7 +1003,7 @@ describe('a forked session', () => { }) describe('a delegated child', () => { - it.each([false, true])('inherits preset tools with seeded=%s and refuses child reminders', async (seeded) => { + it.each([false, true])('inherits preset tools with seeded=%s and refuses child scheduled tasks', async (seeded) => { const parent = await ctx.agents.create({ sessionId: SessionId(`preset-child-parent-${seeded}`), meta: { agentPreset: 'standard' }, @@ -1026,10 +1025,12 @@ describe('a delegated child', () => { expect(toolNames(ctx, child.agent)).toContain('bash') expect(ctx.tools.schemas(child.agent)).toEqual(ctx.tools.schemas(parent.agent)) const calls = [ - ['schedule_create', { prompt: 'Check', after_seconds: 60, title: 'Check' }], + ['schedule_create', { + title: 'Check', prompt: 'Check', rrule: 'DTSTART:20990101T010000Z\nRRULE:FREQ=DAILY;COUNT=1', target: 'this_session', + }], ['schedule_list', {}], - ['schedule_delete', { id: 'task-1' }], - ['schedule_update', { id: 'task-1', title: 'Check' }], + ['schedule_view', { id: 'task-1' }], + ['schedule_edit', { id: 'task-1', action: 'update', title: 'Check' }], ] as const for (const [name, args] of calls) { expect(toolNames(ctx, child.agent)).toContain(name) @@ -1037,7 +1038,7 @@ describe('a delegated child', () => { callId: ToolCallId(`child-${name}`), signal: new AbortController().signal, name, arguments: args, agent: child.agent, }) - expect(result.value).toEqual({ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }) + expect(result.value).toEqual({ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' }) } expect(child.agent.session.header.agentPreset).toBe('standard') } finally { @@ -1086,7 +1087,7 @@ describe('the default preset as a user setting', () => { }) try { // An omitted preset id resolves the stored default instead of the composed default. - expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) + expect(toolNames(ctx, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) } finally { await handle.dispose() } @@ -1132,7 +1133,7 @@ describe('a profile patch stored before Developer tools owned preset selection', setup: agentCtx => legacy.agentPresets.mount(agentCtx).then(() => undefined), }) try { - expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'read_image', 'working_directory']) + expect(toolNames(legacy, handle.agent)).toEqual(['bash', 'read_image', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'working_directory']) } finally { await handle.dispose() } diff --git a/apps/web/package.json b/apps/web/package.json index 51ecc68787..b011aa916d 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -43,7 +43,7 @@ "@deepseek-ai/dsh-client-web": "workspace:*", "@deepseek-ai/dsh-cmdline": "workspace:*", "@deepseek-ai/dsh-pwsh-local": "workspace:*", - "@deepseek-ai/dsh-experimental-agent-team": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-experimental-webworker-packer": "workspace:*", "@deepseek-ai/dsh-experimental-webworker-runtime": "workspace:*", "@deepseek-ai/dsh-remote-mock": "workspace:*", diff --git a/apps/web/tests/access-confirmation.e2e.ts b/apps/web/tests/access-confirmation.e2e.ts index f97978d346..bb9b3d2065 100644 --- a/apps/web/tests/access-confirmation.e2e.ts +++ b/apps/web/tests/access-confirmation.e2e.ts @@ -14,7 +14,7 @@ import { launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { - ZH_BROWSER_LOCALE, connectFreshWorkspaceZh, saveFailureShot, writeComposerDraft, + ZH_BROWSER_LOCALE, assertWarningDialogLayout, connectFreshWorkspaceZh, saveFailureShot, writeComposerDraft, } from './support.ts' import { AUTO_REVIEW_FIXTURE, captureAutoReviewState } from './auto-review-fixture.ts' @@ -154,6 +154,7 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { await page.getByRole('menuitem', { name: '完全权限' }).click() const dialog = page.getByRole('dialog', { name: '确认启用完全权限?' }) await dialog.waitFor({ timeout: 10_000 }) + await assertWarningDialogLayout(dialog) const enable = dialog.getByRole('button', { name: '启用完全权限' }) expect(await enable.isDisabled()).toBe(true) @@ -163,7 +164,18 @@ describe('web e2e: experimental Auto and Full access confirmation', () => { const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) - await dialog.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }).check() + const acknowledgement = dialog.getByRole('checkbox', { name: '我已了解风险,并愿意继续' }) + expect(await acknowledgement.evaluate((input) => { + const label = input.closest('label')! + const textStyle = getComputedStyle(label) + const inputStyle = getComputedStyle(input) + return { + focused: document.activeElement === input, + fontSize: textStyle.fontSize, lineHeight: textStyle.lineHeight, weight: textStyle.fontWeight, + gap: textStyle.gap, width: inputStyle.width, height: inputStyle.height, + } + })).toEqual({ focused: true, fontSize: '14px', lineHeight: '20px', weight: '400', gap: '6px', width: '14px', height: '14px' }) + await dialog.getByText('我已了解风险,并愿意继续', { exact: true }).click() expect(await enable.isEnabled()).toBe(true) await enable.click() await expect.poll(() => access.getAttribute('aria-label'), { timeout: 10_000 }) diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index d5f699a288..6da971cf03 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -1,79 +1,112 @@ -// Keyless assembled-browser coverage for the opt-in Agent Teams bundle +// Keyless assembled-browser coverage for per-Session agent teamwork // over the real Host projection frame flow. import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import { readFileSync } from 'node:fs' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest' -import * as yaml from 'js-yaml' -import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' -import type {} from '@deepseek-ai/dsh-experimental-agent-team' +import type {} from '@deepseek-ai/dsh-agent-team' +import { SessionId } from '@deepseek-ai/dsh-session' +import { CommandId } from '@deepseek-ai/dsh-commands/brand' import { createMessage, createUserMessage } from '@deepseek-ai/dsh-llm' import { - assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' +import { assertWarningDialogLayout, connectFreshWorkspace, connectFreshWorkspaceZh, newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/agent-team-panel', import.meta.url)) const PANEL_EXPECTED = join(SNAPSHOT_DIR, 'task.expected.md') const RESIZE_EXPECTED = join(SNAPSHOT_DIR, 'resize.expected.md') -const OVERLAY = fileURLToPath(new URL('./agent-team-panel.overlay.yml', import.meta.url)) -const TEAM_PATCH = fileURLToPath(new URL('../../../packages/experimental/agent-team-profile/cordis.patch.yml', import.meta.url)) -const INSTALL_ANCHORS = [ - fileURLToPath(new URL('../../../packages/experimental/agent-team-profile/package.json', import.meta.url)), -] const MODE = webSnapshotMode() +const RESEARCHER_DESCRIPTION = 'Researcher: investigate the construction and verify every bound before reporting the result. '.repeat(8).trim() +const RECEIPT_LOCALES = [ + { + language: 'English', code: 'en', browserLocale: 'en-US', connect: connectFreshWorkspace, + modelButton: /^Select model/u, toggle: 'Enable agent teamwork', title: 'Agent teamwork', + enabled: 'Enabled', disabled: 'Disabled', + suggestions: 'Trigger suggestions', commandLabel: 'Team', + failure: 'Failed: Use /team on or /team off.', + }, + { + language: 'Chinese', code: 'zh', browserLocale: 'zh-CN', connect: connectFreshWorkspaceZh, + modelButton: /^选择模型/u, toggle: '启用智能体团队协作', title: '智能体团队协作', + enabled: '已开启', disabled: '已停用', + suggestions: '触发候选建议', commandLabel: '智能体团队协作', + failure: '执行失败:Use /team on or /team off.', + }, +] as const -function profileEntries(path: string): unknown[] { - const parsed = yaml.load(readFileSync(path, 'utf8'), { schema: entryListSchema }) - if (!Array.isArray(parsed)) throw new Error(`profile layer at ${path} must be a list`) - return parsed +type ReceiptLocale = typeof RECEIPT_LOCALES[number] + +async function seedTeamConversation(page: Page, scaffold: WebScaffold): Promise { + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') + agent.session.append('turn/start', { turn: 1 }) + agent.session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'Open the task board.' }], + source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + agent.session.append('step/start', { turn: 1, step: 1 }) + agent.session.append('assistant/message', { + stream: [], + turn: 1, + step: 1, + message: createMessage({ + role: 'assistant', + content: [{ type: 'text', text: 'Ready.' }], + source: { kind: 'model', provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + agent.session.append('step/end', { turn: 1, step: 1 }) + agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + await scaffold.ctx.sessions.flush(agent.session) + await page.getByText('Ready.').waitFor({ timeout: 10_000 }) } -describe('Agent Teams panel overlay', () => { - it('matches the shipped Agent Teams bundle', () => { - expect(profileEntries(OVERLAY)).toEqual(profileEntries(TEAM_PATCH)) - }) -}) +async function withTeamReceiptPage( + locale: ReceiptLocale, + run: (page: Page, scaffold: WebScaffold, tripwire: ReturnType) => Promise, +): Promise { + const scaffold = await launchWebScaffold() + let browser: Browser | undefined + try { + browser = await chromium.launch() + const page = await browser.newPage({ + viewport: { width: 1680, height: 1000 }, locale: locale.browserLocale, timezoneId: 'Asia/Shanghai', + }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await locale.connect(page, scaffold.workspaceCwd) + try { + await seedTeamConversation(page, scaffold) + await run(page, scaffold, tripwire) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(page, `web-e2e-team-command-${locale.code}`) + throw error + } + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +} -describe('web e2e: Agent Teams panel', () => { +describe('web e2e: agent teamwork panel', () => { let scaffold: WebScaffold let browser: Browser let page: Page let tripwire: ReturnType beforeAll(async () => { - scaffold = await launchWebScaffold({ extraOverlayPath: OVERLAY, extraInstallAnchors: INSTALL_ANCHORS }) + scaffold = await launchWebScaffold() browser = await chromium.launch() page = await newEnglishPage(browser) tripwire = watchConsole(page) await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) - const agent = scaffold.ctx.agents.list()[0] - if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') - agent.session.append('turn/start', { turn: 1 }) - agent.session.append('user/message', createUserMessage({ - content: [{ type: 'text', text: 'Open the Agent Team controls.' }], - source: { kind: 'user' }, - }), { surfaceOp: 'append' }) - agent.session.append('step/start', { turn: 1, step: 1 }) - agent.session.append('assistant/message', { - stream: [], - turn: 1, - step: 1, - message: createMessage({ - role: 'assistant', - content: [{ type: 'text', text: 'Ready.' }], - source: { kind: 'model', provider: 'fixture', model: 'fixture' }, - }), - }, { surfaceOp: 'append' }) - agent.session.append('step/end', { turn: 1, step: 1 }) - agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - await scaffold.ctx.sessions.flush(agent.session) - await page.getByText('Ready.').waitFor({ timeout: 10_000 }) + await seedTeamConversation(page, scaffold) }, 120_000) afterAll(async () => { @@ -81,35 +114,318 @@ describe('web e2e: Agent Teams panel', () => { await scaffold?.close() }) - it('displays agent-owned task changes through a read-only board without a refresh action', async () => { + it('explains agent teamwork on hover and focus without changing the Session selection', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-info')) + await page.getByRole('button', { name: /^Select model/u }).click() + const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + const tooltip = page.getByRole('tooltip') + await info.hover() + await tooltip.waitFor({ state: 'visible' }) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'info.expected.md'), await captureStableAria(page, '[role="tooltip"]', scaffold.workspaceCwd), MODE) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await page.getByRole('button', { name: /^Select model/u }).hover() + await tooltip.waitFor({ state: 'hidden' }) + await page.keyboard.press('Shift') + await info.focus() + await tooltip.waitFor({ state: 'visible' }) + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await toggle.isVisible()).toBe(true) + await info.click() + await tooltip.waitFor({ state: 'visible' }) + expect(await info.getAttribute('aria-describedby')).toBe(await tooltip.getAttribute('id')) + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + await page.keyboard.press('Escape') + expect(tripwire.pageErrors).toEqual([]) + }) + + it('toggles from the row label and empty space while keeping the information button independent', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-row')) + await page.getByRole('button', { name: /^Select model/u }).click() + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + const info = page.getByRole('button', { name: 'About agent teamwork', exact: true }) + const label = page.getByText('Enable agent teamwork', { exact: true }) + const labelBounds = await label.boundingBox() + if (labelBounds === null) throw new Error('Team label is not visible') + const labelPoint = { x: labelBounds.x + labelBounds.width / 2, y: labelBounds.y + labelBounds.height / 2 } + await page.mouse.move(labelPoint.x, labelPoint.y) + expect(await toggle.evaluate((element) => { + const row = element.parentElement! + return getComputedStyle(row).backgroundColor !== 'rgba(0, 0, 0, 0)' + })).toBe(true) + await page.mouse.click(labelPoint.x, labelPoint.y) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await info.click() + await page.getByRole('tooltip').waitFor({ state: 'visible' }) + expect(await toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + const gap = await toggle.evaluate((element) => { + const control = element.getBoundingClientRect() + const help = element.parentElement!.querySelector('button:not([role="switch"])')!.getBoundingClientRect() + return { x: (help.right + control.left) / 2, y: control.top + control.height / 2 } + }) + await page.mouse.click(gap.x, gap.y) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + expect(await page.getByRole('tooltip').count()).toBe(0) + await page.keyboard.press('Escape') + expect(tripwire.pageErrors).toEqual([]) + }) + + it('defaults off and saves a Session selection in the model menu', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-mode')) + expect(await page.locator('[data-subagent-action]').count()).toBe(0) + await page.getByRole('button', { name: /^Select model/u }).click() + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.waitFor() + expect(await toggle.getAttribute('aria-checked')).toBe('false') + await toggle.focus() + await page.keyboard.press('ArrowUp') + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(false) + await page.keyboard.press('ArrowDown') + expect(await toggle.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Space') + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + expect(await page.locator('[data-subagent-action]').count()).toBe(0) + const agent = scaffold.ctx.agents.list()[0]! + expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) + expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([]) + const other = await scaffold.ctx.agents.create({ sessionId: SessionId('other-team-mode'), agentOptions: agent.options }) + expect(scaffold.ctx.agentTeams.isEnabled(other.agent)).toBe(false) + await other.dispose() + const beforeReload = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await page.getByRole('button', { name: /^Select model/u }).click() + expect(await page.locator('[data-subagent-action]').count()).toBe(0) + expect(await toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + acknowledgeReloadConnectionLoss(tripwire, beforeReload) + }, 60_000) + + it('toggles from the model menu and keeps text editing usable after refocusing', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-command-input')) + const input = page.locator('[data-composer-input]').first() + const agent = scaffold.ctx.agents.list()[0]! + for (const enabled of [false, true]) { + await page.getByRole('button', { name: /^Select model/u }).click() + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) + await page.keyboard.press('Escape') + await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) + await expect.poll(() => input.textContent()).toBe('') + await page.getByRole('button', { name: 'Account menu', exact: true }).focus() + await input.click() + await page.keyboard.insertText('asdas') + await expect.poll(() => input.textContent()).toBe('asdas') + expect(await input.evaluate((element) => { + const selection = window.getSelection() + return document.activeElement === element && selection?.isCollapsed === true + && selection.anchorNode?.textContent === 'asdas' && selection.anchorOffset === 5 + })).toBe(true) + await input.press('Backspace') + await expect.poll(() => input.textContent()).toBe('asda') + await writeComposerDraft(page, input, '') + } + expect(tripwire.pageErrors).toEqual([]) + }) + + it('shows tasks without children or a divider and hides the entry after the last task is deleted', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-task-only')) + const agent = scaffold.ctx.agents.list()[0]! + expect(await page.locator('[data-subagent-action]').count()).toBe(0) + const task = await scaffold.ctx.agentTeams.createTask(agent, { + subject: 'Plan before delegation', description: 'Prepare shared work before creating subagents', + }) + await page.getByRole('button', { name: '0 subagents', exact: true }).click() + const board = page.locator('[data-team-panel]') + await board.getByText(task.subject, { exact: true }).waitFor() + const panel = page.locator('[data-subagent-panel]') + expect(await panel.getByRole('treeitem').count()).toBe(0) + await panel.getByText('No subagents', { exact: true }).waitFor() + expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('Subagents') + expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + expect(await board.locator('[data-team-task-details]').count()).toBe(0) + expect(await board.getByRole('button', { expanded: false }).count()).toBe(1) + expect(await board.evaluate((element) => { + const style = getComputedStyle(element) + return { border: style.borderTopWidth, margin: style.marginTop } + })).toEqual({ border: '0px', margin: '0px' }) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'task-only.expected.md'), + await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE) + await scaffold.ctx.agentTeams.updateTask(agent, { taskId: task.id, expectedRevision: task.revision, action: 'delete' }) + await page.locator('[data-subagent-action]').waitFor({ state: 'hidden' }) + await page.locator('[data-subagent-panel]').waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('opens the member tree and live read-only tasks in one panel', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel')) const projectionReads = vi.spyOn(scaffold.ctx.sessionController, 'projections') onTestFinished(() => { projectionReads.mockRestore() }) - await page.locator('[data-team-action]').getByRole('button', { name: 'Agent team', exact: true }).click() - const action = page.getByRole('dialog', { name: 'Agent team', exact: true }) - await action.getByText('No shared tasks yet. Create them through the conversation.').waitFor() - await action.getByText('lead').waitFor() + const agent = scaffold.ctx.agents.list()[0]! + const memberId = SessionId('team-panel-researcher') + agent.session.append('subagent/catalog', { + version: 2, childId: memberId, childCreatedAt: Date.now(), mode: 'external', + label: RESEARCHER_DESCRIPTION, + }) + const countAction = page.locator('[data-subagent-action]') + await countAction.waitFor() + await page.mouse.move(2, 2) + expect(await countAction.evaluate((element) => { + const header = element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement! + const preset = header.querySelector('[data-icon="dsw-icon-agent-preset-outline-regular"]')! + const users = element.querySelector('[data-icon="dsw-icon-users-outline-regular"]')! + return { + display: getComputedStyle(header).display, gap: getComputedStyle(header).gap, + presetOpacity: getComputedStyle(preset).opacity, + presetParentOpacity: getComputedStyle(preset.parentElement!).opacity, + sameColor: getComputedStyle(preset).color === getComputedStyle(users).color, + } + })).toEqual({ display: 'flex', gap: '10px', presetOpacity: '1', presetParentOpacity: '1', sameColor: true }) + const countTrigger = countAction.getByRole('button', { name: /subagents?$/u }) + await countTrigger.click() + await countTrigger.click() + await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' }) + expect(await countTrigger.evaluate(element => element === document.activeElement)).toBe(true) + await countTrigger.click() + const action = page.locator('[data-subagent-panel]') + await action.getByRole('treeitem', { name: /Researcher/u }).waitFor() + expect(await action.locator('[data-team-panel], [data-subagent-section-header]').count()).toBe(0) + expect(await action.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0) + expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0) + expect(await action.getByRole('heading', { name: 'Members', exact: true }).count()).toBe(0) expect(projectionReads).not.toHaveBeenCalled() expect(await action.getByRole('button', { name: 'New task' }).count()).toBe(0) expect(await action.getByRole('button', { name: /Refresh/u }).count()).toBe(0) - // Host-side Team mutations reach the open panel through projection frames only. - const agent = scaffold.ctx.agents.list()[0]! + await action.getByRole('treeitem', { name: /Researcher/u }).waitFor() + expect(await page.locator('[data-subagent-panel]').count()).toBe(1) + expect(await page.getByRole('button', { name: 'Task board', exact: true }).count()).toBe(0) const task = await scaffold.ctx.agentTeams.createTask(agent, { - subject: 'Agent task', description: 'Created by the Team Lead', writeScopes: ['src/web'], + subject: 'Agent task', description: 'Created by the root agent', writeScopes: ['src/web'], }) - await action.getByText('Agent task', { exact: true }).waitFor() - await action.getByText('Owner: Unowned', { exact: true }).waitFor() + const row = action.locator(`[data-team-task="${task.id}"]`) + await row.getByRole('button', { name: 'Pending Agent task', exact: true, expanded: false }).waitFor() + expect(await action.locator('[data-subagent-section-header]').textContent()).toBe('Subagents1 external') + expect(await action.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0) + expect(await action.locator('[data-team-panel]').evaluate((element) => { + const style = getComputedStyle(element) + return { border: style.borderTopWidth, margin: style.marginTop } + })).toEqual({ border: '0px', margin: '4px' }) + expect(await action.evaluate((element) => { + const tree = element.querySelector('[role="tree"]')! + const board = element.querySelector('[data-team-panel]')! + return Boolean(tree.compareDocumentPosition(board) & Node.DOCUMENT_POSITION_FOLLOWING) + })).toBe(true) + expect(await row.evaluate(element => ({ tag: element.tagName, parent: element.parentElement?.tagName }))) + .toEqual({ tag: 'LI', parent: 'UL' }) + expect(await action.locator('[data-team-task-details], article').count()).toBe(0) + expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + await action.getByRole('heading', { name: 'Shared tasks 1 pending', exact: true }).waitFor() + expect(await action.evaluate(element => getComputedStyle(element).padding)).toBe('6px') + expect(await action.locator('[data-subagent-section-header]').evaluate((element) => { + const style = getComputedStyle(element) + return { padding: style.padding, gap: style.gap } + })).toEqual({ padding: '4px 7px 8px', gap: '7px' }) + expect(await action.locator('[data-team-panel]').getByRole('heading') + .evaluate(element => getComputedStyle(element).columnGap)).toBe('7px') + for (const [title, progress] of [ + [action.locator('[data-subagent-section-header]').getByRole('heading'), action.getByText('1 external', { exact: true })], + [action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }), action.getByText('1 pending', { exact: true })], + ] as const) { + expect(await progress.evaluate(element => getComputedStyle(element).marginInlineStart)).toBe('4px') + const titleRight = await title.evaluate(element => element.getBoundingClientRect().right) + const progressLeft = await progress.evaluate(element => element.getBoundingClientRect().left) + expect(Math.abs(progressLeft - titleRight - 11)).toBeLessThanOrEqual(1) + } + const member = action.getByRole('treeitem', { name: /Researcher/u }) + const memberTitle = member.getByText(RESEARCHER_DESCRIPTION, { exact: true }) + const taskTitle = row.getByText('Agent task', { exact: true }) + const titleLefts = await Promise.all([ + memberTitle, + action.locator('[data-subagent-section-header]').getByRole('heading'), + action.locator('[data-team-panel]').getByText('Shared tasks', { exact: true }), + taskTitle, + ].map(locator => locator.evaluate(element => element.getBoundingClientRect().left))) + expect(Math.max(...titleLefts) - Math.min(...titleLefts)).toBeLessThanOrEqual(1) + const primaryStyles = await Promise.all([memberTitle, taskTitle].map(locator => locator.evaluate((element) => { + const style = getComputedStyle(element) + return { fontSize: style.fontSize, color: style.color } + }))) + expect(primaryStyles.map(style => style.fontSize)).toEqual(['13px', '13px']) + expect(primaryStyles[1]).toEqual(primaryStyles[0]) + expect(await member.getByText('team-panel-researcher', { exact: true }) + .evaluate(element => getComputedStyle(element).fontSize)).toBe('12px') + const memberHover = member.locator(':scope > div') + for (const target of [member, memberHover]) { + expect(await target.evaluate((element) => { + const style = getComputedStyle(element) + return [style.paddingTop, style.paddingBottom] + })).toEqual(['4px', '4px']) + } + expect(await member.evaluate(element => getComputedStyle(element).minHeight)).toBe('40px') + expect(await member.evaluate((element) => { + const style = getComputedStyle(element) + return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap } + })).toEqual({ left: '9px', right: '6px', gap: '7px' }) + expect(await memberHover.evaluate((element) => { + const style = getComputedStyle(element) + return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin } + })).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '-4px -6px' }) + const taskHover = row.getByRole('button') + expect(await taskHover.evaluate((element) => { + const style = getComputedStyle(element) + return [style.paddingTop, style.paddingBottom] + })).toEqual(['7px', '7px']) + expect(await taskHover.evaluate(element => element.getBoundingClientRect().height)).toBe(31) + expect(await taskHover.evaluate((element) => { + const style = getComputedStyle(element) + return { left: style.paddingLeft, right: style.paddingRight, gap: style.gap, margin: style.margin } + })).toEqual({ left: '6px', right: '6px', gap: '7px', margin: '0px -6px' }) + expect(await taskHover.evaluate(element => element.getBoundingClientRect().width + - element.parentElement!.getBoundingClientRect().width)).toBe(12) + const hoverStyles = [] + for (const target of [memberHover, taskHover]) { + await target.hover() + hoverStyles.push(await target.evaluate((element) => { + const bounds = element.getBoundingClientRect() + const style = getComputedStyle(element) + return { left: bounds.left, right: bounds.right, radius: style.borderRadius, background: style.backgroundColor } + })) + } + expect(Math.abs(hoverStyles[0]!.left - hoverStyles[1]!.left)).toBeLessThanOrEqual(1) + expect(Math.abs(hoverStyles[0]!.right - hoverStyles[1]!.right)).toBeLessThanOrEqual(1) + expect(hoverStyles[1]!.radius).toBe(hoverStyles[0]!.radius) + expect(hoverStyles[1]!.background).toBe(hoverStyles[0]!.background) + expect(hoverStyles[1]!.background).not.toBe('rgba(0, 0, 0, 0)') + await row.getByRole('button').click() + await row.locator('[data-team-task-owner]').filter({ hasText: 'Unowned' }).waitFor() + await row.getByText('Created by the root agent', { exact: true }).waitFor() + expect(await row.locator('[data-team-task-details]').evaluate((element) => { + const style = getComputedStyle(element) + return { fontSize: style.fontSize, indent: style.paddingLeft } + })).toEqual({ fontSize: '12px', indent: '21px' }) + expect(await row.locator('[data-team-task-details] p, [data-team-task-owner]') + .evaluateAll(elements => elements.every(element => getComputedStyle(element).fontSize === '12px'))).toBe(true) + expect(await row.getByRole('button').getAttribute('aria-expanded')).toBe('true') + expect(await action.evaluate(element => element.getBoundingClientRect().width)).toBe(360) await scaffold.ctx.agentTeams.updateTask(agent, { taskId: task.id, expectedRevision: task.revision, action: 'claim', }) - await action.getByText('In progress', { exact: true }).waitFor() - await action.getByText('Owner: lead', { exact: true }).waitFor() + await row.getByRole('img', { name: 'In progress', exact: true }).waitFor() + await row.locator('[data-team-task-owner]').filter({ hasText: agent.id }).waitFor() + await action.getByRole('heading', { name: 'Shared tasks 1 in progress', exact: true }).waitFor() expect(await action.getByRole('button', { name: /^(New task|Edit|Complete|Reopen|Delete)$/u }).count()).toBe(0) expect(await action.locator('input, select, textarea').count()).toBe(0) - const snapshot = await captureStableAria(page, '[data-team-panel]', scaffold.workspaceCwd) + const snapshot = await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd) await compareOrRefreshGolden(PANEL_EXPECTED, snapshot, MODE) expect(projectionReads).not.toHaveBeenCalled() expect(tripwire.pageErrors).toEqual([]) @@ -117,15 +433,113 @@ describe('web e2e: Agent Teams panel', () => { await page.keyboard.press('Escape') }, 60_000) + it('hides the board while disabled and restores its tasks when re-enabled', async () => { + await page.getByRole('button', { name: /^Select model/u }).click() + const toggle = page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }) + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('false') + expect(await page.locator('[data-subagent-action]').count()).toBe(1) + await page.keyboard.press('Escape') + await page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }).click() + await page.getByRole('treeitem', { name: /Researcher/u }).waitFor() + expect(await page.locator('[data-team-panel]').count()).toBe(0) + expect(await page.locator('[data-subagent-panel]').evaluate(element => element.getBoundingClientRect().width)).toBe(360) + expect(await page.locator('[data-subagent-section-header]').count()).toBe(0) + await page.keyboard.press('Escape') + await page.getByRole('button', { name: /^Select model/u }).click() + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await page.keyboard.press('Escape') + await page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }).click() + await page.locator('[data-subagent-panel]').getByText('Agent task', { exact: true }).waitFor() + await page.keyboard.press('Escape') + }) + + it('keeps the narrow Users trigger focused and opens its catalog only on explicit activation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-narrow-trigger')) + const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: '1 subagent', exact: true }) + const panel = page.locator('[data-subagent-panel]') + const count = trigger.locator('[data-subagent-count]') + const viewport = page.viewportSize()! + expect(await count.isVisible()).toBe(true) + expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').count()).toBe(1) + expect(await trigger.locator('[data-icon="dsw-icon-users-outline-regular"]').evaluate((element) => { + const bounds = element.getBoundingClientRect() + return { width: bounds.width, height: bounds.height } + })).toEqual({ width: 14, height: 14 }) + expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0) + expect(await trigger.locator('svg').count()).toBe(1) + await trigger.focus() + const original = await trigger.elementHandle() + if (original === null) throw new Error('Subagent trigger is missing') + try { + await page.setViewportSize({ width: 390, height: 700 }) + await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none') + expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true) + const expandSidebar = page.locator('[data-sidebar-right-expand]') + const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => { + const bounds = element.getBoundingClientRect() + const icon = element.querySelector('svg')!.getBoundingClientRect() + const style = getComputedStyle(element) + return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius, + color: style.color, iconWidth: icon.width, iconHeight: icon.height } + }))) + expect(compactStyles[0]).toEqual(compactStyles[1]) + expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 }) + expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px') + await expandSidebar.hover() + const expandHover = await expandSidebar.evaluate((element) => { + const style = getComputedStyle(element) + return { background: style.backgroundColor, color: style.color } + }) + await page.mouse.move(1, 1) + await page.keyboard.press('Tab') + const countTooltip = page.getByRole('tooltip', { name: '1 subagent', exact: true }) + await countTooltip.waitFor({ state: 'hidden' }) + await trigger.hover() + expect(await trigger.evaluate((element) => { + const style = getComputedStyle(element) + return { background: style.backgroundColor, color: style.color } + })).toEqual(expandHover) + expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)') + // Observe beyond the wide trigger's 150ms hover-open deadline. + await page.waitForTimeout(200) + expect(await panel.count()).toBe(0) + await countTooltip.waitFor({ state: 'visible' }) + expect(await panel.count()).toBe(0) + await trigger.click() + await panel.waitFor() + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + expect(await page.getByRole('tooltip', { name: '1 subagent', exact: true }).count()).toBe(0) + await panel.getByRole('treeitem', { name: /Researcher/u }).waitFor() + await panel.locator('[data-team-task]').getByRole('button', { expanded: false }).waitFor() + await trigger.click() + await panel.waitFor({ state: 'detached' }) + expect(await trigger.getAttribute('aria-expanded')).toBe('false') + await trigger.press('ArrowDown') + await panel.waitFor() + await page.mouse.move(1, 1) + // Keyboard activation stays pinned beyond the 120ms pointer-leave grace. + await page.waitForTimeout(180) + expect(await panel.count()).toBe(1) + await page.keyboard.press('Escape') + await panel.waitFor({ state: 'detached' }) + } finally { + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + await original.dispose() + } + }) + it('keeps the panel inside the viewport and closes on outside click or Escape', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-agent-team-panel-keyboard')) - const panel = page.getByRole('dialog', { name: 'Agent team', exact: true }) - const trigger = page.locator('[data-team-action]').getByRole('button', { name: 'Agent team', exact: true }) + const panel = page.locator('[data-subagent-panel]') + const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }) const viewport = page.viewportSize()! await trigger.click() - await panel.getByText('lead', { exact: true }).waitFor() + await panel.getByRole('heading', { name: /Shared tasks/u }).waitFor() try { - for (const size of [{ width: 760, height: 540 }, { width: 600, height: 420 }]) { + for (const size of [{ width: 760, height: 540 }, { width: 600, height: 420 }, { width: 390, height: 700 }]) { await page.setViewportSize(size) await expect.poll(() => panel.evaluate((element) => { const rect = element.getBoundingClientRect() @@ -136,6 +550,30 @@ describe('web e2e: Agent Teams panel', () => { .every(([x, y]) => element.contains(document.elementFromPoint(x!, y!))) })).toBe(true) } + const row = panel.getByRole('treeitem', { name: /Researcher/u }) + const primary = row.getByText(RESEARCHER_DESCRIPTION, { exact: true }) + const secondary = row.getByText('team-panel-researcher', { exact: true }) + expect(await row.getByRole('button').count()).toBe(0) + expect(await primary.evaluate((element) => { + const style = getComputedStyle(element) + return { + tag: element.tagName, clipped: element.scrollWidth > element.clientWidth || element.scrollHeight > element.clientHeight, + whiteSpace: style.whiteSpace, overflowWrap: style.overflowWrap, + } + })).toEqual({ tag: 'SPAN', clipped: false, whiteSpace: 'normal', overflowWrap: 'anywhere' }) + const primaryBounds = await primary.boundingBox() + const secondaryBounds = await secondary.boundingBox() + expect(primaryBounds).not.toBeNull() + expect(secondaryBounds).not.toBeNull() + expect(primaryBounds!.y + primaryBounds!.height).toBeLessThanOrEqual(secondaryBounds!.y) + const beforeClick = page.url() + await primary.click() + expect(page.url()).toBe(beforeClick) + expect(await page.getByRole('tooltip', { name: RESEARCHER_DESCRIPTION, exact: true }).count()).toBe(0) + expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + expect(await secondary.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await secondary.hover() + expect(await page.getByRole('tooltip').count()).toBe(0) await panel.getByRole('heading', { name: /Shared tasks/u }).click() expect(await panel.count()).toBe(1) await page.mouse.click(2, 2) @@ -162,8 +600,12 @@ describe('web e2e: Agent Teams panel', () => { }) it('keeps the hovered panel open when the pointer returns directly to its trigger', async () => { - const trigger = page.locator('[data-team-action]').getByRole('button', { name: 'Agent team', exact: true }) - const panel = page.getByRole('dialog', { name: 'Agent team', exact: true }) + onTestFailed(async () => { + await saveFailureShot(page, 'web-e2e-agent-team-hover') + console.error('Agent Team hover diagnostics', JSON.stringify({ errors: tripwire.pageErrors, warnings: tripwire.warnings })) + }) + const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }) + const panel = page.locator('[data-subagent-panel]') await trigger.hover() await panel.waitFor() await panel.hover() @@ -174,37 +616,412 @@ describe('web e2e: Agent Teams panel', () => { await page.keyboard.press('Escape') }) - it('offers expansion when resizing makes a task description exceed two lines', async () => { + it('keeps compact tasks ordered, opens one full detail at a time, and scrolls only the fixed-width menu', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-compact-details')) const agent = scaffold.ctx.agents.list()[0]! - await scaffold.ctx.agentTeams.createTask(agent, { - subject: 'Responsive task', - description: 'Check the task description before you start work. '.repeat(3), - writeScopes: [], + const completed = await scaffold.ctx.agentTeams.createTask(agent, { + subject: 'Completed preparation', description: 'Preparation is complete.', writeScopes: [], + }) + const claimed = await scaffold.ctx.agentTeams.updateTask(agent, { + taskId: completed.id, expectedRevision: completed.revision, action: 'claim', + }) + await scaffold.ctx.agentTeams.updateTask(agent, { + taskId: completed.id, expectedRevision: claimed.revision, action: 'complete', + }) + const blocker = await scaffold.ctx.agentTeams.createTask(agent, { + subject: 'Dependency task', description: 'Finish this prerequisite first.', writeScopes: [], + }) + const subject = 'Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport' + const description = 'Check every dependency and write scope before you start work.\n'.repeat(16).trim() + const task = await scaffold.ctx.agentTeams.createTask(agent, { + subject, description, blockedBy: [blocker.id], writeScopes: ['src/web/components'], }) const viewport = page.viewportSize()! - const trigger = page.locator('[data-team-action]').getByRole('button', { name: 'Agent team', exact: true }) - const panel = page.getByRole('dialog', { name: 'Agent team', exact: true }) - const card = panel.locator('article').filter({ hasText: 'Responsive task' }) + const trigger = page.locator('[data-subagent-action]').getByRole('button', { name: /subagents?$/u }) + const panel = page.locator('[data-subagent-panel]') + const board = panel.locator('[data-team-panel]') + const row = board.locator(`[data-team-task="${task.id}"]`) + const emptyRow = board.locator(`[data-team-task="${completed.id}"]`) + onTestFinished(() => page.setViewportSize(viewport)) + // Constrain the menu so closed and expanded task rows both exercise its scrollbar. + await page.setViewportSize({ width: viewport.width, height: 540 }) await trigger.click() - await card.waitFor() - expect(await card.getByRole('button', { name: 'Show more' }).count()).toBe(0) + await row.waitFor() + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + expect(await board.locator('[data-team-task-details], article').count()).toBe(0) + expect(await board.getByRole('button', { expanded: false }).count()).toBe(4) + expect(await board.locator('[data-team-task]').evaluateAll(elements => elements.map(element => element.getAttribute('data-status')))) + .toEqual(['in_progress', 'completed', 'pending', 'pending']) + const counts = board.getByText('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending', { exact: true }) + await counts.waitFor() + expect(await counts.textContent()).toBe('1 completed\u2002·\u20021 in progress\u2002·\u20022 pending') + expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0) + expect(await panel.getByRole('button', { name: /^Show (more|less)$/u }).count()).toBe(0) + await row.getByRole('img', { name: 'Blocked by dependencies', exact: true }).waitFor() + const measureScroll = async () => panel.evaluate((element) => { + const style = getComputedStyle(element) + const bounds = element.getBoundingClientRect() + const scroller = element.querySelector('[role="tree"]')!.parentElement! + const scrollStyle = getComputedStyle(scroller) + const scrollBounds = scroller.getBoundingClientRect() + const taskBounds = element.querySelector('[data-team-task] button')!.getBoundingClientRect() + const scrollbarWidth = Number.parseFloat(getComputedStyle(scroller, '::-webkit-scrollbar').width) + return { + innerWidth: bounds.width - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight) + - Number.parseFloat(style.borderLeftWidth) - Number.parseFloat(style.borderRightWidth), + clientWidth: scroller.clientWidth, clientHeight: scroller.clientHeight, scrollHeight: scroller.scrollHeight, + overflowing: scroller.scrollHeight > scroller.clientHeight, + gutter: scrollStyle.scrollbarGutter, marginRight: scrollStyle.marginRight, + trackMargin: scrollStyle.getPropertyValue('--dsh-scrollbar-track-margin').trim(), + taskLeft: taskBounds.left, taskRight: taskBounds.right, + trackLeft: scrollBounds.right - scrollbarWidth, trackRight: scrollBounds.right, panelRight: bounds.right, + arrowsBeforeTrack: [...element.querySelectorAll('[data-team-task] button svg')] + .every(arrow => arrow.getBoundingClientRect().right <= scrollBounds.right - scrollbarWidth), + } + }) + const closedScroll = await measureScroll() + expect(closedScroll.overflowing, JSON.stringify(closedScroll)).toBe(true) + expect(Math.abs(closedScroll.clientWidth - closedScroll.innerWidth), JSON.stringify(closedScroll)).toBeLessThanOrEqual(1) + expect(closedScroll.gutter).toBe('stable') + expect(closedScroll.marginRight).toBe('-5px') + expect(closedScroll.trackMargin).toBe('6px') + await row.getByRole('button').click() + const expandedScroll = await measureScroll() + expect(expandedScroll.overflowing).toBe(true) + expect(expandedScroll.clientWidth).toBe(closedScroll.clientWidth) + expect(expandedScroll.taskLeft).toBe(closedScroll.taskLeft) + expect(expandedScroll.taskRight).toBe(closedScroll.taskRight) + expect(expandedScroll.arrowsBeforeTrack).toBe(true) + expect(expandedScroll.trackLeft).toBeGreaterThanOrEqual(expandedScroll.panelRight - 6) + expect(expandedScroll.trackRight).toBeLessThanOrEqual(expandedScroll.panelRight - 1) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + const details = row.locator('[data-team-task-details]') + expect(await details.locator('p:not([data-team-task-owner])').textContent()).toBe(description) + expect(await details.locator('[data-team-task-owner]').textContent()).toBe('Owner: Unowned') + expect(await details.locator(':scope > *').evaluateAll(elements => elements.map(element => + element.hasAttribute('data-team-task-owner') ? 'owner' : element.tagName))).toEqual(['P', 'owner']) + expect(await details.locator('dl, dt, dd').count()).toBe(0) + for (const omitted of [task.id, blocker.subject, 'Readiness', 'Write scopes', 'Write scope warnings', 'src/web/components']) { + expect(await details.textContent()).not.toContain(omitted) + } + expect(await row.getByRole('button').getAttribute('aria-controls')).toBe(await details.getAttribute('id')) try { - await page.setViewportSize({ width: 360, height: 700 }) - await card.getByRole('button', { name: 'Show more' }).waitFor() - expect(await card.locator('p').evaluate(p => p.scrollHeight > p.clientHeight)).toBe(true) - await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, '[data-team-panel]', scaffold.workspaceCwd), MODE) - await card.getByRole('button', { name: 'Show more' }).click() - expect(await card.locator('p').evaluate(p => p.scrollHeight === p.clientHeight)).toBe(true) - await card.getByRole('button', { name: 'Show less' }).click() + await page.setViewportSize({ width: 390, height: 700 }) + await expect.poll(() => panel.evaluate((element) => { + const rect = element.getBoundingClientRect() + return rect.width === Math.min(360, innerWidth - 32) && rect.left >= 16 && rect.right <= innerWidth - 16 + && rect.top >= 16 && rect.bottom <= innerHeight - 16 + && element.scrollWidth <= element.clientWidth + })).toBe(true) + expect(await panel.locator('*').evaluateAll((elements) => { + const scrollers = elements.filter(element => + ['auto', 'scroll'].includes(getComputedStyle(element).overflowY) + && element.scrollHeight > element.clientHeight) + return scrollers.map(element => ({ + hasHeader: element.querySelector('[data-subagent-section-header]') !== null, + hasTree: element.querySelector('[role="tree"]') !== null, + hasBoard: element.querySelector('[data-team-panel]') !== null, + fitsWidth: element.scrollWidth <= element.clientWidth, + })) + })).toEqual([{ hasHeader: true, hasTree: true, hasBoard: true, fitsWidth: true }]) + const narrowScroll = await measureScroll() + expect(Math.abs(narrowScroll.clientWidth - narrowScroll.innerWidth), JSON.stringify(narrowScroll)).toBeLessThanOrEqual(1) + expect(narrowScroll.arrowsBeforeTrack).toBe(true) + const scroller = panel.getByRole('tree').locator('..') + await scroller.hover({ position: { x: 20, y: 20 } }) + await Promise.all([ + scroller.evaluate(element => new Promise((resolve) => { + element.addEventListener('scrollend', () => { resolve() }, { once: true }) + })), + page.mouse.wheel(0, 180), + ]) + await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBeGreaterThan(0) + await scroller.evaluate((element) => { element.scrollTo({ top: 0 }) }) + await expect.poll(() => scroller.evaluate(element => element.scrollTop)).toBe(0) + expect(await row.getByText(subject, { exact: true }).evaluate(element => + element.scrollWidth <= element.clientWidth && getComputedStyle(element).whiteSpace === 'pre-wrap')).toBe(true) + expect(await details.locator('p:not([data-team-task-owner])').evaluate(element => element.scrollHeight === element.clientHeight)).toBe(true) + const ownerBounds = await details.locator('[data-team-task-owner]').boundingBox() + const descriptionBounds = await details.locator('p:not([data-team-task-owner])').boundingBox() + expect(ownerBounds).not.toBeNull() + expect(descriptionBounds).not.toBeNull() + expect(ownerBounds!.height).toBeLessThanOrEqual(18) + expect(ownerBounds!.y).toBeGreaterThanOrEqual(descriptionBounds!.y + descriptionBounds!.height) + const detailColor = await details.evaluate(element => getComputedStyle(element).color) + expect(await details.locator('[data-team-task-owner], [data-team-task-owner] span') + .evaluateAll(elements => elements.map(element => getComputedStyle(element).color))) + .toEqual([detailColor, detailColor, detailColor]) + expect(await counts.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const titleBounds = await board.getByText('Shared tasks', { exact: true }).boundingBox() + const countBounds = await counts.boundingBox() + expect(titleBounds).not.toBeNull() + expect(countBounds).not.toBeNull() + expect(countBounds!.y).toBeGreaterThanOrEqual(titleBounds!.y + titleBounds!.height) + await compareOrRefreshGolden(RESIZE_EXPECTED, await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE) + await emptyRow.getByRole('button').click() + expect(await row.getAttribute('data-expanded')).toBe('false') + expect(await row.locator('[data-team-task-details]').count()).toBe(0) + expect(await board.locator('[data-team-task-details]').count()).toBe(1) + expect(await emptyRow.locator('[data-team-task-owner]').textContent()).toBe(`Owner: ${agent.id}`) + expect(await emptyRow.locator('[data-team-task-details] p:not([data-team-task-owner])').textContent()).toBe(completed.description) + expect(await emptyRow.locator('dl, dt, dd').count()).toBe(0) + expect(await emptyRow.locator('[data-team-task-details]').textContent()).not.toContain(completed.id) + await emptyRow.getByRole('button').click() + expect(await board.locator('[data-team-task-details]').count()).toBe(0) await page.setViewportSize(viewport) - await expect.poll(() => card.getByRole('button', { name: 'Show more' }).count()).toBe(0) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) } finally { await page.keyboard.press('Escape') await page.setViewportSize(viewport) } }) + it('confirms disabling after a recorded model request and keeps cancellation side-effect free', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-team-disable-confirmation')) + const agent = scaffold.ctx.agents.list()[0]! + const selection = agent.model.current() + if (selection === undefined) throw new Error('Team fixture has no selected model') + agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) + await scaffold.ctx.sessions.flush(agent.session) + const openConfirmation = async (): Promise => { + await page.getByRole('button', { name: /^Select model/u }).click() + await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() + await page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }).waitFor() + } + await openConfirmation() + const dialog = page.getByRole('dialog', { name: 'Disable agent teamwork?', exact: true }) + await assertWarningDialogLayout(dialog) + expect(await page.getByRole('menu', { name: 'Model and reasoning effort', exact: true }).count()).toBe(0) + expect(await dialog.getByRole('checkbox').count()).toBe(0) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'disable-confirmation.expected.md'), + await captureStableAria(page, '[aria-modal="true"]', scaffold.workspaceCwd), MODE) + await dialog.getByRole('button', { name: 'Cancel', exact: true }).click() + await dialog.waitFor({ state: 'hidden' }) + await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) + await openConfirmation() + await page.keyboard.press('Escape') + await dialog.waitFor({ state: 'hidden' }) + await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) + await openConfirmation() + await dialog.getByRole('button', { name: 'Disable', exact: true }).click() + await dialog.waitFor({ state: 'hidden' }) + await expect.poll(() => page.getByRole('button', { name: /^Select model/u }).evaluate(element => element === document.activeElement)).toBe(true) + await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) + await page.getByRole('button', { name: /^Select model/u }).click() + await page.getByRole('switch', { name: 'Enable agent teamwork', exact: true }).click() + await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) + expect(await dialog.count()).toBe(0) + await page.keyboard.press('Escape') + expect(agent.session.ownEvents().filter(event => event.type === 'command/run' || event.type === 'command/done')).toEqual([]) + expect(tripwire.pageErrors).toEqual([]) + }) + + it('removes both section headings and the board divider when the last shared task is deleted', async () => { + const agent = scaffold.ctx.agents.list()[0]! + await page.getByRole('button', { name: '1 subagent', exact: true }).click() + const panel = page.locator('[data-subagent-panel]') + await panel.locator('[data-team-panel]').waitFor() + for (const task of scaffold.ctx.agentTeams.listTasks(agent).toReversed()) { + if (task.status === 'deleted') continue + await scaffold.ctx.agentTeams.updateTask(agent, { + taskId: task.id, expectedRevision: task.revision, action: 'delete', + }) + } + await panel.locator('[data-team-panel]').waitFor({ state: 'detached' }) + expect(await panel.locator('[data-subagent-section-header]').count()).toBe(0) + expect(await panel.getByRole('heading').count()).toBe(0) + expect(await panel.getByText('No shared tasks yet. Create them through the conversation.').count()).toBe(0) + expect(await panel.getByRole('treeitem', { name: /Researcher/u }).count()).toBe(1) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + await page.keyboard.press('Escape') + }) + it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { - await assertFixtureInventory(SNAPSHOT_DIR, ['task.expected.md', 'resize.expected.md']) + await assertFixtureInventory(SNAPSHOT_DIR, [ + 'task.expected.md', 'resize.expected.md', 'info.expected.md', 'task-only.expected.md', + 'disable-confirmation.expected.md', 'collaboration.zh.expected.md', + 'command-error.en.expected.md', 'command-error.zh.expected.md', + ]) }) }) + +it.each(RECEIPT_LOCALES)('toggles teamwork in $language without command records or Chat changes after reload', async (locale) => { + await withTeamReceiptPage(locale, async (page, scaffold, tripwire) => { + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('Team receipt fixture has no Agent') + const chat = page.locator('[data-chat-flow]').first() + const recordedReady = await captureStableAria(page, '[data-chat-flow]', scaffold.workspaceCwd) + expect(recordedReady).toContain('Ready.') + expect(recordedReady).toContain('Open the task board.') + const captureLayout = () => chat.evaluate((element) => { + const flow = element.getBoundingClientRect() + return { + height: flow.height, + rows: [...element.querySelectorAll('[data-chat-flow-key]')].map((row) => { + const bounds = row.getBoundingClientRect() + return { kind: row.getAttribute('data-chat-flow-kind'), top: bounds.top - flow.top, height: bounds.height } + }), + } + }) + const recordedLayout = await captureLayout() + const commandEvents = () => agent.session.snapshotEvents() + .filter(event => event.type === 'command/run' || event.type === 'command/done') + expect(commandEvents()).toEqual([]) + const input = page.locator('[data-composer-input]').first() + await writeComposerDraft(page, input, '/') + const suggestions = page.getByRole('listbox', { name: locale.suggestions, exact: true }) + await suggestions.getByRole('option').first().waitFor() + const candidate = suggestions.getByRole('option').filter({ hasText: locale.commandLabel }) + expect(await candidate.count()).toBe(0) + await writeComposerDraft(page, input, '/tea') + await expect.poll(() => suggestions.getByRole('option').count()).toBe(0) + expect(await candidate.count()).toBe(0) + await input.press('Escape') + await suggestions.waitFor({ state: 'hidden' }) + await writeComposerDraft(page, input, '') + expect(commandEvents()).toEqual([]) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) + const assertChatUnchanged = async (): Promise => { + await chat.getByText('Ready.', { exact: true }).waitFor() + expect(await page.locator('[data-team-command], [data-chat-flow-kind="command"], [data-command-input]').count()).toBe(0) + expect(await captureStableAria(page, '[data-chat-flow]', scaffold.workspaceCwd)).toBe(recordedReady) + await expect.poll(captureLayout).toEqual(recordedLayout) + } + for (const enabled of [true, false]) { + await page.getByRole('button', { name: locale.modelButton }).click() + const toggle = page.getByRole('switch', { name: locale.toggle, exact: true }) + await toggle.click() + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe(String(enabled)) + await expect.poll(() => scaffold.ctx.agentTeams.isEnabled(agent)).toBe(enabled) + expect(scaffold.ctx.commands.list(agent).some(command => command.name === 'team')).toBe(false) + expect(commandEvents()).toEqual([]) + await page.keyboard.press('Escape') + await assertChatUnchanged() + } + await scaffold.ctx.sessions.flush(agent.session) + const recordedCommands = commandEvents() + expect(recordedCommands).toEqual([]) + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await assertChatUnchanged() + expect(commandEvents()).toEqual(recordedCommands) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) + acknowledgeReloadConnectionLoss(tripwire, warningStart) + + // Historical receipts are read-only fixtures, not invocations of a registered command. + for (const args of [' on', ' off']) { + const commandId = CommandId(`historical-team-${args.trim()}`) + agent.session.append('command/run', { commandId, name: 'team', args, source: { kind: 'user' } }) + agent.session.append('command/done', { commandId, kind: 'success', text: 'Team mode saved.' }) + } + agent.session.append('command/run', { + commandId: CommandId('historical-team-pending'), name: 'team', args: ' on', source: { kind: 'user' }, + }) + await scaffold.ctx.sessions.flush(agent.session) + const historicalCommands = commandEvents() + expect(historicalCommands.map(event => event.type)).toEqual([ + 'command/run', 'command/done', 'command/run', 'command/done', 'command/run', + ]) + const historicalWarningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await assertChatUnchanged() + expect(commandEvents()).toEqual(historicalCommands) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) + acknowledgeReloadConnectionLoss(tripwire, historicalWarningStart) + }) +}) + +it.each(RECEIPT_LOCALES)('renders historical Team failures in $language without a success receipt after reload', async (locale) => { + await withTeamReceiptPage(locale, async (page, scaffold, tripwire) => { + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('Team failure fixture has no Agent') + const commandId = CommandId('historical-team-error') + agent.session.append('command/run', { commandId, name: 'team', args: ' invalid', source: { kind: 'user' } }) + agent.session.append('command/done', { commandId, kind: 'error', text: 'Use /team on or /team off.' }) + await scaffold.ctx.sessions.flush(agent.session) + const row = page.locator('[data-team-command]') + const captureFailure = async (): Promise => { + await row.getByText(locale.failure, { exact: true }).waitFor() + expect(await row.count()).toBe(1) + expect(await row.getAttribute('data-state')).toBe('error') + expect(await row.getByText(locale.title, { exact: true }).count()).toBe(1) + expect(await row.getByText(locale.enabled, { exact: true }).count()).toBe(0) + expect(await row.getByText(locale.disabled, { exact: true }).count()).toBe(0) + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(false) + const collapsed = await captureStableAria(page, '[data-team-command]', scaffold.workspaceCwd) + const disclosure = row.getByRole('button', { expanded: false }) + await disclosure.click() + await row.getByRole('button', { expanded: true }).waitFor() + await row.getByText('Use /team on or /team off.', { exact: true }).waitFor() + const expanded = await captureStableAria(page, '[data-team-command]', scaffold.workspaceCwd) + return `## Failed receipt\n\n${collapsed}\n\n## Raw error\n\n${expanded}` + } + const failure = await captureFailure() + await compareOrRefreshGolden(join(SNAPSHOT_DIR, `command-error.${locale.code}.expected.md`), failure, MODE) + await scaffold.ctx.sessions.flush(agent.session) + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + expect(await captureFailure()).toBe(failure) + acknowledgeReloadConnectionLoss(tripwire, warningStart) + }) +}) + +it('shows the Chinese empty subagent section above compact shared tasks', async () => { + await withTeamReceiptPage(RECEIPT_LOCALES[1], async (page, scaffold) => { + const agent = scaffold.ctx.agents.list()[0]! + await scaffold.ctx.agentTeams.setEnabled(agent, true) + await scaffold.ctx.agentTeams.createTask(agent, { + subject: '准备协作', description: '先准备共享任务,再创建子智能体。', + }) + await page.getByRole('button', { name: '0 个子智能体', exact: true }).click() + const panel = page.locator('[data-subagent-panel]') + await panel.getByText('暂无子智能体', { exact: true }).waitFor() + expect(await panel.locator('[data-subagent-section-header]').textContent()).toBe('子智能体') + expect(await panel.locator('[data-subagent-section-header] button, h3 button').count()).toBe(0) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + await panel.getByRole('heading', { name: '共享任务 1 待处理', exact: true }).waitFor() + expect(await panel.locator('[data-team-task-details]').count()).toBe(0) + }) +}) + +it('uses the Chinese collaboration name in the switch and disable confirmation', async () => { + const scaffold = await launchWebScaffold() + let browser: Browser | undefined + try { + browser = await chromium.launch() + const page = await browser.newPage({ locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await connectFreshWorkspaceZh(page, scaffold.workspaceCwd) + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('Chinese Team fixture has no Agent') + await scaffold.ctx.agentTeams.setEnabled(agent, true) + const selection = agent.model.current() + if (selection === undefined) throw new Error('Chinese Team fixture has no model') + agent.session.append('request/header', { header: { config: selection }, reason: 'initial' }) + await scaffold.ctx.sessions.flush(agent.session) + await page.getByRole('button', { name: /^选择模型/u }).click() + const toggle = page.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await expect.poll(() => toggle.getAttribute('aria-checked')).toBe('true') + await page.getByRole('button', { name: '关于智能体团队协作', exact: true }).waitFor() + expect(await toggle.evaluate(element => element.parentElement!.scrollWidth <= element.parentElement!.clientWidth)).toBe(true) + const menu = await captureStableAria(page, '[role="menu"]', scaffold.workspaceCwd) + await toggle.click() + const dialog = page.getByRole('dialog', { name: '确认停用智能体团队协作?', exact: true }) + await dialog.waitFor() + await dialog.getByText('对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', { exact: true }).waitFor() + await assertWarningDialogLayout(dialog) + const confirmation = await captureStableAria(page, '[aria-modal="true"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'collaboration.zh.expected.md'), + `## Menu\n\n${menu}\n\n## Confirmation\n\n${confirmation}`, MODE) + await dialog.getByRole('button', { name: '取消', exact: true }).click() + expect(scaffold.ctx.agentTeams.isEnabled(agent)).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) diff --git a/apps/web/tests/agent-team-panel.overlay.yml b/apps/web/tests/agent-team-panel.overlay.yml deleted file mode 100644 index bdcf49e256..0000000000 --- a/apps/web/tests/agent-team-panel.overlay.yml +++ /dev/null @@ -1,27 +0,0 @@ -# Equivalent to the Agent Teams bundle over the stable base and Web bundles. -- id: tool-subagent-control - disabled: true - -- id: tool-subagent - disabled: true - -- id: tool-subagent-fork - disabled: true - -- insert: - - id: agent-team - name: '@deepseek-ai/dsh-experimental-agent-team' - config: - maxMembers: 8 - maxTasks: 256 - maxMessageBytes: 65536 - disposalTimeoutMs: 5000 - - - id: tool-agent-team - name: '@deepseek-ai/dsh-experimental-tool-agent-team' - config: - freshProvider: spawn - forkProvider: fork - - - id: ui-agent-team - name: '@deepseek-ai/dsh-experimental-client-ui-agent-team' diff --git a/apps/web/tests/assembled-remote.ts b/apps/web/tests/assembled-remote.ts index 87f9288d42..08a226a835 100644 --- a/apps/web/tests/assembled-remote.ts +++ b/apps/web/tests/assembled-remote.ts @@ -158,7 +158,6 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass 'agentPresets/list': structuredClone(fixture.agentPresets), 'commands/list': structuredClone(fixture.commands), 'settings/openSettingsDocument': ok({ opened: true }), - 'subagents/list': ok({ entries: [], parentAvailable: true }), 'terminal/list': ok([]), 'skills/list': ok({ skills: [] }), 'session/canOpenWorkspacePath': ok(true), @@ -228,9 +227,8 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass }) mock.unary('session/list', () => ok({ items: structuredClone(sessions) })) // The shipped composition mounts the `ui-schedule` row, so the Schedule - // client reads the catalog and the per-Session list over this mock. + // client reads the catalog over this mock. mock.unary('schedule/catalog', () => ok([])) - mock.unary('schedule/list', () => ok([])) mock.unary('session/projections', (request: unknown) => { const sessionId = recordString(recordValue(request, 'request'), 'sessionId') const summary = sessions.find(candidate => candidate.sessionId === sessionId) diff --git a/apps/web/tests/auto-review-denial.e2e.ts b/apps/web/tests/auto-review-denial.e2e.ts index 58371631a9..d967b4cb9b 100644 --- a/apps/web/tests/auto-review-denial.e2e.ts +++ b/apps/web/tests/auto-review-denial.e2e.ts @@ -119,13 +119,16 @@ describe.skipIf(MODE === 'record')('web e2e: cold Auto-review denial', () => { await ledger.locator('table[data-scroll-ready="true"]').waitFor({ timeout: 15_000 }) const nativeRecord = ledger.locator('tr[data-kind="tool"]').filter({ hasText: 'mystery' }) const innerRecord = ledger.locator('tr[data-kind="subtool"]').filter({ hasText: 'bash' }) - await expect.poll(() => nativeRecord.textContent()).toContain('AUTO_REVIEW_DENIED') - await expect.poll(() => innerRecord.textContent()).toContain('AUTO_REVIEW_DENIED') + await expect.poll(() => nativeRecord.textContent()).toContain('Error: Auto review rejected tool "mystery"; its body was not executed') + await expect.poll(() => innerRecord.textContent()).toContain('Error: Auto review rejected tool "bash"; its body was not executed') await innerRecord.click() - await page.getByRole('tab', { name: 'Result', exact: true }).click() - await page.getByRole('tabpanel', { name: 'Result' }) - .getByText('AutoReviewDeniedError: AUTO_REVIEW_DENIED', { exact: true }) - .waitFor({ state: 'visible' }) + for (const tab of ['Summary', 'Result']) { + await page.getByRole('tab', { name: tab, exact: true }).click() + const panel = page.getByRole('tabpanel', { name: tab }) + await panel.getByText('Error: Auto review rejected tool "bash"; its body was not executed', { exact: true }) + .waitFor({ state: 'visible' }) + expect(await panel.getByText('AutoReviewDeniedError: AUTO_REVIEW_DENIED', { exact: true }).count()).toBe(0) + } await captureAutoReviewState(page, 'deny-trajectory') const trajectory = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) .split(SEED_ID).join('{{seededId}}') diff --git a/apps/web/tests/background-job-list.e2e.ts b/apps/web/tests/background-job-list.e2e.ts index fab978232b..899cda61c4 100644 --- a/apps/web/tests/background-job-list.e2e.ts +++ b/apps/web/tests/background-job-list.e2e.ts @@ -85,7 +85,7 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { let phase = 'running' onTestFailed(() => saveFailureShot(page, `web-e2e-background-job-${phase}`)) // Polling for zero would pass at t=0 before delivery and prove nothing. - const trigger = page.getByRole('button', { name: '1 background job running' }) + const trigger = page.getByRole('button', { name: '1 background job', exact: true }) expect(await trigger.count()).toBe(0) const started = await executeToolFixture(scaffold.ctx, { @@ -101,10 +101,28 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { const jobId = JobId(matched[0]) await trigger.waitFor({ timeout: 15_000 }) - await trigger.click() - const row = page.getByRole('list', { name: 'Background jobs' }).getByRole('listitem').first() + expect(await trigger.locator('[data-state="ongoing"]').count()).toBe(1) + expect(await trigger.locator('[data-icon="dsw-icon-chevron-down-outline-regular"]').count()).toBe(0) + await trigger.hover() + const list = page.getByRole('list', { name: 'Background jobs' }) + const row = list.getByRole('listitem').first() await row.waitFor({ timeout: 10_000 }) await expect.poll(() => row.textContent()).toContain(COMMAND) + expect(await trigger.getAttribute('aria-expanded')).toBe('true') + await row.hover() + await row.getByRole('button', { name: /Show live output/ }).focus() + await page.mouse.move(2, 2) + // Focusing a menu control pins it beyond the 120ms hover-leave deadline. + await page.waitForTimeout(180) + expect(await list.count()).toBe(1) + await trigger.click() + await list.waitFor({ state: 'detached' }) + await trigger.click() + await list.waitFor() + await page.mouse.move(2, 2) + await page.waitForTimeout(180) + expect(await list.count()).toBe(1) + expect(await trigger.getAttribute('aria-label')).toBe('1 background job') const running = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd, { runningJobs: 'keep' }) await compareOrRefreshGolden(RUNNING_EXPECTED, running, MODE) @@ -120,9 +138,7 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { await expect.poll(() => stop.getAttribute('data-kill-state')).toBe('armed') await stop.click() - // Exact: the running trigger's name ('1 background job running') contains this label. - const idle = page.getByRole('button', { name: '1 background job', exact: true }) - await idle.waitFor({ timeout: 20_000 }) + expect(await trigger.getAttribute('aria-label')).toBe('1 background job') // The unclaimed report's reason lands in the settled row's detail. await expect.poll( () => page.getByRole('list', { name: 'Background jobs' }).textContent(), @@ -185,6 +201,82 @@ describe.skipIf(MODE === 'record')('web e2e: background job list', () => { expect(await trigger.evaluate(node => node === document.activeElement)).toBe(true) }, 60_000) + it('keeps the compact Layers trigger focused and opens jobs only on click or keyboard', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-background-job-compact-trigger')) + const trigger = page.getByRole('button', { name: '1 background job', exact: true }) + const list = page.getByRole('list', { name: 'Background jobs' }) + const count = trigger.locator('[data-job-count]') + const viewport = page.viewportSize()! + await page.getByRole('button', { name: 'Collapse right sidebar', exact: true }).click() + await expect.poll(() => page.locator('[data-rightbar-col]') + .evaluate(column => column.parentElement?.hasAttribute('data-animating'))).toBe(false) + await page.getByRole('button', { name: 'Open right sidebar', exact: true }).waitFor() + await page.mouse.move(2, 2) + expect(await count.isVisible()).toBe(true) + expect(await trigger.locator('[data-icon="dsw-icon-layers-outline-regular"]').count()).toBe(1) + expect(await trigger.locator('svg').count()).toBe(1) + expect(await trigger.locator('svg').evaluate((element) => { + const bounds = element.getBoundingClientRect() + return [bounds.width, bounds.height] + })).toEqual([14, 14]) + await trigger.focus() + const original = await trigger.elementHandle() + if (original === null) throw new Error('Background jobs trigger is missing') + try { + await page.setViewportSize({ width: 390, height: 700 }) + await expect.poll(() => count.evaluate(element => getComputedStyle(element).display)).toBe('none') + expect(await original.evaluate(element => element.isConnected && element === document.activeElement)).toBe(true) + const expandSidebar = page.locator('[data-sidebar-right-expand]') + const compactStyles = await Promise.all([trigger, expandSidebar].map(control => control.evaluate((element) => { + const style = getComputedStyle(element) + const bounds = element.getBoundingClientRect() + const icon = element.querySelector('svg')!.getBoundingClientRect() + return { width: bounds.width, height: bounds.height, padding: style.padding, radius: style.borderRadius, + color: style.color, iconWidth: icon.width, iconHeight: icon.height } + }))) + expect(compactStyles[0]).toEqual(compactStyles[1]) + expect(compactStyles[0]).toMatchObject({ width: 28, height: 28, padding: '0px', iconWidth: 15, iconHeight: 15 }) + expect(await trigger.evaluate(element => getComputedStyle(element.closest('[data-slot="conversation.session.header.actions"]')!.parentElement!).gap)).toBe('8px') + await expandSidebar.hover() + const expandHover = await expandSidebar.evaluate((element) => { + const style = getComputedStyle(element) + return { background: style.backgroundColor, color: style.color } + }) + await expect.poll(() => trigger.evaluate((element) => { + const bounds = element.getBoundingClientRect() + return element.contains(document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2)) + })).toBe(true) + await trigger.hover() + expect(await trigger.evaluate((element) => { + const style = getComputedStyle(element) + return { background: style.backgroundColor, color: style.color } + })).toEqual(expandHover) + expect(expandHover.background).not.toBe('rgba(0, 0, 0, 0)') + // Compact hover stays closed beyond the wide trigger's 150ms open deadline. + await page.waitForTimeout(200) + expect(await list.count()).toBe(0) + await trigger.click() + await list.waitFor() + await list.getByRole('button', { name: 'Finished 1', exact: true }).waitFor() + await trigger.click() + await list.waitFor({ state: 'detached' }) + await trigger.press('ArrowDown') + await list.waitFor() + expect(await list.getByRole('button').first().evaluate(element => element === document.activeElement)).toBe(true) + await page.mouse.move(2, 2) + // Keyboard activation remains pinned after leaving both trigger and menu. + await page.waitForTimeout(180) + expect(await list.count()).toBe(1) + await page.mouse.click(2, 2) + await list.waitFor({ state: 'detached' }) + expect(await trigger.getAttribute('aria-expanded')).toBe('false') + } finally { + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + await original.dispose() + } + }) + it('keeps its snapshot inventory closed', async () => { await assertFixtureInventory(SNAPSHOT_DIR, ['running.expected.md', 'settled.expected.md']) }) diff --git a/apps/web/tests/composer-tab-geometry.e2e.ts b/apps/web/tests/composer-tab-geometry.e2e.ts index 9eda0bb603..41c57548a8 100644 --- a/apps/web/tests/composer-tab-geometry.e2e.ts +++ b/apps/web/tests/composer-tab-geometry.e2e.ts @@ -1,6 +1,7 @@ -// Browser geometry for the input card across Chat and Trajectory. The browser -// must expose layout-consuming scrollbars, and an uncompensated control keeps -// equal rectangles from passing vacuously. +// Browser geometry for the input card across Chat and Trajectory, plus the +// docked seat's stacking rank, fixed overlays, floor position, and statistics +// row. The browser must expose layout-consuming scrollbars, and an +// uncompensated control keeps equal rectangles from passing vacuously. import { fileURLToPath } from 'node:url' import { join } from 'node:path' import type { Browser, Page } from 'playwright' @@ -11,7 +12,7 @@ import { assertFixtureInventory, compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' -import { newEnglishPage, saveFailureShot } from './support.ts' +import { newEnglishPage, saveFailureShot, writeComposerDraft } from './support.ts' const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/composer-tab-geometry', import.meta.url)) /** Records platform-neutral distances between the two tabs' card rectangles. */ @@ -158,6 +159,28 @@ async function compareTabs(page: Page): Promise { } } +/** + * Run one measurement with an extra stylesheet in the page, then remove it. + * @param page - the page under test. + * @param id - the stylesheet element id, unique per rule set. + * @param css - rules applied only for the measurement. + * @param measure - the measurement taken while the rules apply. + * @returns the measurement's result. + */ +async function withPageStyle(page: Page, id: string, css: string, measure: () => Promise): Promise { + await page.evaluate(({ styleId, text }) => { + const style = document.createElement('style') + style.id = styleId + style.textContent = text + document.head.append(style) + }, { styleId: id, text: css }) + try { + return await measure() + } finally { + await page.evaluate((styleId) => { document.getElementById(styleId)?.remove() }, id) + } +} + /** * Run the uncompensated cascade in the page for one measurement, then lift it: * the overlay seat's `right` compensation dropped to 0, so it measures the @@ -166,17 +189,7 @@ async function compareTabs(page: Page): Promise { * @returns the comparison as the column lays out without the compensation. */ async function compareTabsWithoutCompensation(page: Page): Promise { - await page.evaluate(({ id, css }) => { - const style = document.createElement('style') - style.id = id - style.textContent = css - document.head.append(style) - }, { id: CONTROL_STYLE_ID, css: CONTROL_CSS }) - try { - return await compareTabs(page) - } finally { - await page.evaluate((id) => { document.getElementById(id)?.remove() }, CONTROL_STYLE_ID) - } + return await withPageStyle(page, CONTROL_STYLE_ID, CONTROL_CSS, () => compareTabs(page)) } /** @@ -345,6 +358,110 @@ describe('web e2e: input card position across view tabs', () => { expect(tripwire.pageErrors).toEqual([]) }, 60_000) + it('keeps the docked composer at one stacking rank while its command menu opens', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-seat-rank')) + await setMeasuredViewport(page, WIDE_VIEWPORT, false) + const host = page.locator('[data-conversation-scroll]') + const seat = page.locator('[data-conversation-scroll] > [data-composer-seat]') + const rank = (): Promise => seat.evaluate(element => Number(getComputedStyle(element).zIndex)) + // Scroll anchoring never selects composer content. + expect(await seat.evaluate(element => getComputedStyle(element).overflowAnchor)).toBe('none') + await host.evaluate((element) => { element.scrollTop = 0 }) + const backToBottom = page.getByRole('button', { name: 'Back to bottom', exact: true }) + await backToBottom.waitFor({ timeout: 10_000 }) + const controlRank = await backToBottom.evaluate((element) => { + for (let node: Element | null = element; node !== null; node = node.parentElement) { + const zIndex = getComputedStyle(node).zIndex + if (zIndex !== 'auto') return Number(zIndex) + } + throw new Error('back-to-bottom control has no stacking rank') + }) + const resting = await rank() + expect(resting).toBeGreaterThan(controlRank) + const input = page.locator('[data-composer-input]').last() + await writeComposerDraft(page, input, '/') + await page.locator('[data-trigger-menu]').waitFor({ timeout: 10_000 }) + expect(await rank()).toBe(resting) + await page.keyboard.press('Escape') + await writeComposerDraft(page, input, '') + await page.locator('[data-trigger-menu]').waitFor({ state: 'detached', timeout: 10_000 }) + expect(await rank()).toBe(resting) + await host.evaluate((element) => { element.scrollTop = element.scrollHeight }) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('keeps fixed-position overlays out of the docked composer', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-seat-fixed-overlays')) + await setMeasuredViewport(page, WIDE_VIEWPORT, false) + const seat = page.locator('[data-conversation-scroll] > [data-composer-seat]') + // The transform hint makes the seat the containing block for fixed descendants. + expect(await seat.evaluate(element => getComputedStyle(element).willChange)).toBe('transform') + const fixedInside = (): Promise => seat.evaluate(element => [...element.querySelectorAll('*')] + .filter(node => getComputedStyle(node).position === 'fixed').length) + const commands = seat.getByRole('button', { name: 'Add files or run commands', exact: true }) + await commands.hover() + const tooltip = page.getByRole('tooltip').filter({ hasText: 'Add files or run commands' }) + await tooltip.waitFor({ timeout: 10_000 }) + expect(await tooltip.evaluate(node => node.closest('[data-composer-seat]') === null)).toBe(true) + expect(await fixedInside()).toBe(0) + // Viewport coordinates still place the bubble above its button. + const [bubbleBox, buttonBox] = await Promise.all([tooltip.boundingBox(), commands.boundingBox()]) + expect(bubbleBox).not.toBeNull() + expect(buttonBox).not.toBeNull() + if (bubbleBox !== null && buttonBox !== null) { + expect(bubbleBox.y + bubbleBox.height).toBeLessThanOrEqual(buttonBox.y + 0.5) + expect(bubbleBox.x).toBeLessThan(buttonBox.x + buttonBox.width) + expect(bubbleBox.x + bubbleBox.width).toBeGreaterThan(buttonBox.x) + } + await page.mouse.move(0, 0) + const input = page.locator('[data-composer-input]').last() + await writeComposerDraft(page, input, '/') + await page.locator('[data-trigger-menu]').waitFor({ timeout: 10_000 }) + expect(await fixedInside()).toBe(0) + await page.keyboard.press('Escape') + await writeComposerDraft(page, input, '') + await page.locator('[data-trigger-menu]').waitFor({ state: 'detached', timeout: 10_000 }) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('rests the docked composer at the floor when no View fills the column', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-seat-floor')) + await setMeasuredViewport(page, WIDE_VIEWPORT, false) + // Hides the View subtree, which normally stretches to push the seat down. + const gap = await withPageStyle( + page, + 'composer-seat-floor-probe', + '[data-conversation-scroll] > :not([data-composer-seat]) { display: none !important; }', + () => page.locator('[data-conversation-scroll]').evaluate((element) => { + const seat = element.querySelector(':scope > [data-composer-seat]') + if (seat === null) throw new Error('no composer seat in the scroll body') + const box = element.getBoundingClientRect() + return box.top + element.clientTop + element.clientHeight - seat.getBoundingClientRect().bottom + }), + ) + expect(Math.abs(gap)).toBeLessThanOrEqual(0.5) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + + it('keeps the statistics row height whether or not its readings are present', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-seat-stats-row')) + await setMeasuredViewport(page, WIDE_VIEWPORT, false) + const dock = page.locator('[data-conversation-scroll] > [data-composer-seat] [data-composer-dock]') + // Vacuity guard: the seeded usage must produce at least one reading. + await expect.poll(() => dock.locator('[data-composer-stat], button[aria-haspopup="dialog"]').count(), { timeout: 10_000 }) + .toBeGreaterThan(0) + const height = (): Promise => dock.evaluate(element => element.getBoundingClientRect().height) + const withReadings = await height() + const withoutReadings = await withPageStyle( + page, + 'composer-seat-stats-row-probe', + '[data-composer-dock] > * { display: none !important; }', + height, + ) + expect(Math.abs(withReadings - withoutReadings)).toBeLessThanOrEqual(0.5) + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + it('matches the committed tab geometry golden', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-composer-tab-geometry-golden')) await setMeasuredViewport(page, WIDE_VIEWPORT, false) diff --git a/apps/web/tests/context-menus.e2e.ts b/apps/web/tests/context-menus.e2e.ts index 0cc7a7abf8..4d797fe340 100644 --- a/apps/web/tests/context-menus.e2e.ts +++ b/apps/web/tests/context-menus.e2e.ts @@ -330,6 +330,35 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s', expect(await page.locator('[data-document-preview]').getByText('SECOND FILE', { exact: true }).count()).toBe(1) expect(tripwire.pageErrors).toEqual([]) }) + it('keeps context-menu rows reachable after browser zoom', async () => { + const cdp = await page.context().newCDPSession(page) + try { + await page.setViewportSize({ width: 1291, height: 480 }) + await page.locator('[data-row-key="session:context-menu-first"]').click({ button: 'right' }) + const menu = page.getByRole('menu') + await menu.waitFor() + // Desktop Chromium caps page scale at three; the short window makes the rows overflow at that scale. + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 3 }) + await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(3) + await expect.poll(() => menu.evaluate((node) => { + const view = window.visualViewport! + const box = node.getBoundingClientRect() + return Math.min(box.left - view.offsetLeft, box.top - view.offsetTop, + view.offsetLeft + view.width - box.right, view.offsetTop + view.height - box.bottom) + })).toBeGreaterThanOrEqual(11.5) + const rows = menu.locator('[role="presentation"]').first() + expect(await rows.evaluate((node) => { + node.scrollTop = node.scrollHeight + return node.scrollTop > 0 + })).toBe(true) + } finally { + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) + await cdp.detach() + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1291, height: 768 }) + } + }) + it('keeps original preview open when dismissing its menu and fits both themes at the viewport edge', async () => { onTestFailed(() => saveFailureShot(page, 'context-menus-preview')) await page.getByRole('button', { name: 'View full image: Original', exact: true }).click() diff --git a/apps/web/tests/context-meter.e2e.ts b/apps/web/tests/context-meter.e2e.ts index 8eab8e868e..9adaf5babe 100644 --- a/apps/web/tests/context-meter.e2e.ts +++ b/apps/web/tests/context-meter.e2e.ts @@ -1,7 +1,7 @@ /** Context details stay inside the viewport with and without Chat's statistics contribution. */ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' -import { chromium } from 'playwright' +import { chromium, webkit } from 'playwright' import { describe, expect, it } from 'vitest' import { fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage } from './support.ts' @@ -9,8 +9,11 @@ import { connectFreshWorkspace, newEnglishPage } from './support.ts' const FIXTURE = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/session.v3.jsonl', import.meta.url)) const NO_CHAT = fileURLToPath(new URL('./fixtures/context-meter-no-chat.patch.yml', import.meta.url)) -describe.skipIf(webSnapshotMode() === 'record')('web e2e: context details placement', () => { - it.each([true, false])('keeps details visible across viewport changes (Chat statistics: %s)', async (withStats) => { +describe.skipIf(webSnapshotMode() === 'record').each([ + { name: 'Chromium', engine: chromium }, + { name: 'WebKit', engine: webkit }, +])('web e2e: context details placement ($name)', ({ engine }) => { + it.each([true, false])('keeps details visible while resizing the window (Chat statistics: %s)', async (withStats) => { const fixture = await selectedSessionFixture(FIXTURE, false) const scaffold = await launchWebScaffold({ replayFixture: fixture, @@ -19,7 +22,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: context details placem ...withStats ? {} : { extraOverlayPath: NO_CHAT }, }) try { - const browser = await chromium.launch() + const browser = await engine.launch() try { const page = await newEnglishPage(browser) const tripwire = watchConsole(page) @@ -74,6 +77,31 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: context details placem await panel.waitFor() await page.mouse.click(1260, 400) await panel.waitFor({ state: 'hidden' }) + const panels = [ + { trigger, name: 'of context used' }, + ...withStats ? [ + { trigger: page.locator('[data-composer-stat="activity"] button'), name: 'Session statistics' }, + { trigger: page.locator('[data-composer-stat="usage"] button'), name: 'Token usage' }, + ] : [], + ] + for (const details of panels) { + await details.trigger.click() + const dialog = page.getByRole('dialog', { name: details.name, exact: true }) + await dialog.waitFor() + for (const width of [1280, 800, 390]) { + await page.setViewportSize({ width, height: 900 }) + await expect.poll(async () => { + const rect = await dialog.boundingBox() + const anchor = await details.trigger.boundingBox() + return rect !== null && anchor !== null + && rect.x >= 11 && rect.x + rect.width <= width - 11 + && rect.y >= 11 && rect.y + rect.height <= 889 + && Math.abs(anchor.y - rect.y - rect.height - 8) <= 1 + }).toBe(true) + } + await page.keyboard.press('Escape') + await dialog.waitFor({ state: 'hidden' }) + } expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) } finally { diff --git a/apps/web/tests/cua-optin.e2e.ts b/apps/web/tests/cua-optin.e2e.ts index c5900519c6..d1962da38b 100644 --- a/apps/web/tests/cua-optin.e2e.ts +++ b/apps/web/tests/cua-optin.e2e.ts @@ -145,7 +145,7 @@ it.skipIf(process.platform !== 'darwin').each([ expect(scaffold.ctx.tools.schemas(originalAgent).some(tool => tool.name === 'cua')).toBe(preset === 'ptc') } const child = await scaffold.ctx.agents.create({ - sessionId: SessionId('cua-child'), parentAgent: ptcAgent, + sessionId: SessionId('cua-child'), setup: (ctx) => { scaffold.ctx.agentPresets.composeFrom(ctx, ptcAgent.ctx) }, }) expect(scaffold.ctx.tools.schemas(child.agent).some(tool => tool.name === 'cua')).toBe(true) diff --git a/apps/web/tests/cua-permissions.e2e.ts b/apps/web/tests/cua-permissions.e2e.ts index 72afb6648d..68925fc144 100644 --- a/apps/web/tests/cua-permissions.e2e.ts +++ b/apps/web/tests/cua-permissions.e2e.ts @@ -129,7 +129,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false') expect(await accessibility.getByRole('button', { name: 'Request permission', exact: true }).count()).toBe(1) await writeFile(state, JSON.stringify({ accessibility: true, screenRecording: false, launchApplication })) - // Headless pages retain document focus; model returning from System Settings at the window-event boundary. + // Returning from System Settings refreshes the page's native permission observation. await page.evaluate(() => { window.dispatchEvent(new Event('focus')) }) await accessibility.getByText('Allowed', { exact: true }).waitFor() const screen = panel.getByRole('group', { name: 'Screen Recording', exact: true }) @@ -149,9 +149,14 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr expect((await scaffold.ctx.cuaAccess.applications()).allowedApps).toEqual([]) const events = (await readFile(audit, 'utf8')).trim().split('\n').map(line => JSON.parse(line) as { event: string; method: string; params: object }) .filter(record => record.event === 'call').map(({ method, params }) => ({ method, params })) - expect(events).toContainEqual({ method: 'requestPermission', params: { permission: 'accessibility' } }) + expect(events).toContainEqual({ method: 'requestPermission', params: { permission: 'accessibility', + instruction: 'Drag {application} to the list above to allow Accessibility', + backLabel: 'Back', finderLabel: 'Show in Finder', + unavailableMessage: 'Application unavailable. Enable Computer Use again and retry.', + settingsMessage: 'Open System Settings > Privacy & Security > Accessibility manually.', pollIntervalMs: 1000 } }) expect(events.filter(event => event.method === 'openPermissionSettings')).toEqual([ - { method: 'openPermissionSettings', params: { permission: 'accessibility' } }, + { method: 'openPermissionSettings', params: { permission: 'accessibility', + settingsMessage: 'Open System Settings > Privacy & Security > Accessibility manually.' } }, ]) expect(events.every(event => ['permissionStatus', 'requestPermission', 'openPermissionSettings', 'applicationIcons', 'getApp'].includes(event.method))).toBe(true) const preview = plugins.locator('[data-detail-document] img') diff --git a/apps/web/tests/deepseek-messages-chat.e2e.ts b/apps/web/tests/deepseek-messages-chat.e2e.ts index d6bbf88260..b02a65ba69 100644 --- a/apps/web/tests/deepseek-messages-chat.e2e.ts +++ b/apps/web/tests/deepseek-messages-chat.e2e.ts @@ -54,7 +54,7 @@ describe.skipIf(MODE === 'record')('web e2e: DeepSeek Messages conversation', () expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'deepseek-messages', model: 'deepseek-v4-flash' }) await page.getByRole('button', { name: /^选择模型/ }).click() await page.getByRole('menuitem', { name: /模型/ }).click() - await page.getByText('DeepSeek', { exact: true }).waitFor() + await page.getByRole('group', { name: 'DeepSeek', exact: true }).waitFor() await page.getByRole('button', { name: /^选择模型/ }).click() const input = page.locator('[data-composer-input]').first() const settled = scaffold.whenTurnSettled() diff --git a/apps/web/tests/default-model.e2e.ts b/apps/web/tests/default-model.e2e.ts index fa6c518add..afd89b3c77 100644 --- a/apps/web/tests/default-model.e2e.ts +++ b/apps/web/tests/default-model.e2e.ts @@ -170,7 +170,8 @@ describe('web e2e: the composer model switch is the default for later sessions', expect(popupBounds!.width).toBeCloseTo(commandMenuBounds!.width) expect(popupBounds!.x).toBeCloseTo(commandMenuBounds!.x) expect(await search.getAttribute('placeholder')).toBe('搜索模型…') - await page.getByRole('option').first().waitFor() + // Command menu height changes where the pointer lands in the model popup. + await page.getByRole('option', { name: 'Acme Large', exact: true }).hover() await compareOrRefreshGolden( fileURLToPath(new URL('./expected/default-model/command-picker.expected.md', import.meta.url)), await captureStableAria(page, '[aria-label="/model 选项"]', scaffold.workspaceCwd), @@ -272,6 +273,7 @@ describe('web e2e: the composer model switch is the default for later sessions', await observeFocus('Enter model pane') await devicePage.keyboard.press('ArrowDown') const search = devicePage.getByRole('searchbox', { name: '搜索模型…' }) + expect(await search.evaluate(input => getComputedStyle(input).fontSize)).toBe('16px') await expect.poll(() => search.evaluate(element => document.activeElement === element)).toBe(true) await observeFocus('Navigate models') await devicePage.keyboard.press('Escape') diff --git a/apps/web/tests/default-product-isolation.e2e.ts b/apps/web/tests/default-product-isolation.e2e.ts index 4b535448e1..603a35753b 100644 --- a/apps/web/tests/default-product-isolation.e2e.ts +++ b/apps/web/tests/default-product-isolation.e2e.ts @@ -94,7 +94,7 @@ it('activates the actual default Client registry without experimental packages', expect(roster.plugins.some(plugin => plugin.modules.includes('@deepseek-ai/dsh-client-ui-layout'))).toBe(true) expect(experimentalClientReferences(roster)).toEqual([]) const contaminatedHost = await request('mount-experimental-entry') - const experimentalName = '@deepseek-ai/dsh-experimental-client-ui-agent-team' + const experimentalName = '@deepseek-ai/dsh-experimental-client-ui-voice-input' expect(contaminatedHost.client.entries.map(entry => entry.id)).toContain(experimentalName) await page.reload() await expect.poll(async () => { diff --git a/apps/web/tests/expected/cua-permissions/missing.expected.md b/apps/web/tests/expected/cua-permissions/missing.expected.md index 3b32eb2418..26ea6c5bd4 100644 --- a/apps/web/tests/expected/cua-permissions/missing.expected.md +++ b/apps/web/tests/expected/cua-permissions/missing.expected.md @@ -16,7 +16,7 @@ - strong: Screen Recording - paragraph: In System Settings, allow DSH Computer Use.app to capture application windows. - button "Request permission" - - paragraph: Manage permissions in System Settings for the application named by macOS. + - paragraph: Manage Accessibility and Screen Recording permissions in System Settings. - region "Manage applications computer use can access": - heading "Manage applications computer use can access" [level=3] - heading "Always-allowed applications" [level=4] diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md index b6c825a833..b4f0445c07 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -9,6 +9,13 @@ - button "左右对比" [pressed] - button "自动换行" [pressed] - region "全部 2 个文件": + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 - button "panel.ts 的更多操作" @@ -62,10 +69,3 @@ - button "选择第 R18 行": "18" - text: export const n18 = 18 - button "其余未变更的行" - - button "收起 panel.md" [expanded] - - text: docs/panel.md 新文件 +2 −0 - - button "panel.md 的更多操作" - - button "选择第 R1 行": "1" - - text: "+ # Panel" - - button "选择第 R2 行": "2" - - text: + Shows the change requests of a Session. diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md index 5873dec5ae..72d7382c18 100644 --- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -10,6 +10,13 @@ - button "自动换行" [pressed] - button "将文件树移到右侧" [expanded] - region "全部 2 个文件": + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 - button "panel.ts 的更多操作" @@ -63,13 +70,6 @@ - button "选择第 R18 行": "18" - text: export const n18 = 18 - button "其余未变更的行" - - button "收起 panel.md" [expanded] - - text: docs/panel.md 新文件 +2 −0 - - button "panel.md 的更多操作" - - button "选择第 R1 行": "1" - - text: "+ # Panel" - - button "选择第 R2 行": "2" - - text: + Shows the change requests of a Session. - separator "调整文件树宽度" - navigation "全部 2 个文件": - textbox "筛选文件…": src diff --git a/apps/web/tests/expected/forge-panel/local-and-pr.expected.md b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md new file mode 100644 index 0000000000..e19aec25eb --- /dev/null +++ b/apps/web/tests/expected/forge-panel/local-and-pr.expected.md @@ -0,0 +1,20 @@ +- text: feat 项目目录 +- button "复制项目目录路径" +- button "本地变更" +- text: HEAD → origin/main +- button "查看本会话的变更:4 个文件,新增 4 行,删除 1 行": +4 −1 4 个文件 +- heading "本会话的变更请求 · 1" [level=3] +- button "刷新状态" +- list: + - listitem: + - img "变更请求状态:需要处理" + - link "Add the pull request panel": + - /url: https://github.com/octo/demo/pull/7 + - text: "#7 feat → main" + - button "在浏览器中打开" + - button "复制变更请求链接" + - 'button "从本会话移除 #7"' + - 'button "收起 #7" [expanded]' + - button "检查 已加载 1 项检查,仍有更多" + - text: 评审 等待评审 · 1 条未解决讨论 合并 无冲突 + - 'button "查看 #7 的变更:新增 128 行,删除 14 行"': 变更 +128 −14 diff --git a/apps/web/tests/expected/math-rendering/ui.expected.md b/apps/web/tests/expected/math-rendering/ui.expected.md index f80e94775d..82c51f246e 100644 --- a/apps/web/tests/expected/math-rendering/ui.expected.md +++ b/apps/web/tests/expected/math-rendering/ui.expected.md @@ -19,7 +19,6 @@ - text: . - math: π 4 < θ < π 2 - math: θ ∈ ( π 4 , π 2 ) . (1) -- math: α + β γ - table: - rowgroup: - row "Symbol Value": diff --git a/apps/web/tests/expected/plugin-config/official.expected.md b/apps/web/tests/expected/plugin-config/official.expected.md index 1060826d8a..bdf3d7033a 100644 --- a/apps/web/tests/expected/plugin-config/official.expected.md +++ b/apps/web/tests/expected/plugin-config/official.expected.md @@ -22,11 +22,6 @@ - heading "实验性插件" [level=3] - button "更多" - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - - status - - switch "启用 智能体团队" - listitem: - button "查看 语音输入": 语音输入 - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 diff --git a/apps/web/tests/expected/plugin-manager/icons.expected.md b/apps/web/tests/expected/plugin-manager/icons.expected.md index 4510accc6c..f42be11885 100644 --- a/apps/web/tests/expected/plugin-manager/icons.expected.md +++ b/apps/web/tests/expected/plugin-manager/icons.expected.md @@ -1,6 +1,6 @@ Third-party bundle card: image, 36×36, decoded -Disabled Agent Teams card: image, 36×36, decoded -Agent Teams detail: image, 36×36, decoded +Disabled Voice Input card: image, 36×36, decoded +Voice Input detail: image, 36×36, decoded Third-party bundle detail: image, 36×36, decoded Independent search row: image, 30×30, decoded Independent review row: generic artwork diff --git a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md index 561ee7ae23..8a7e68999a 100644 --- a/apps/web/tests/expected/plugin-manager/live-enabled.expected.md +++ b/apps/web/tests/expected/plugin-manager/live-enabled.expected.md @@ -22,11 +22,6 @@ - heading "实验性插件" [level=3] - button "更多" - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - - status - - switch "启用 智能体团队" - listitem: - button "查看 语音输入": 语音输入 - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 diff --git a/apps/web/tests/expected/plugin-manager/manager.expected.md b/apps/web/tests/expected/plugin-manager/manager.expected.md index 88dd772e51..1053a94651 100644 --- a/apps/web/tests/expected/plugin-manager/manager.expected.md +++ b/apps/web/tests/expected/plugin-manager/manager.expected.md @@ -22,11 +22,6 @@ - heading "实验性插件" [level=3] - button "更多" - list: - - listitem: - - button "查看 智能体团队": 智能体团队 - - text: 实验性 让与你对话的智能体把工作分给有名字的队友,在共享任务看板上跟踪进度,并汇总队友的结果向你汇报。 - - status - - switch "启用 智能体团队" - listitem: - button "查看 语音输入": 语音输入 - text: 实验性 在本机使用 SenseVoice 转写录音,首次使用需安装依赖。 diff --git a/apps/web/tests/expected/plugin-manager/refresh.expected.md b/apps/web/tests/expected/plugin-manager/refresh.expected.md index 85d666fd3e..75dda78845 100644 --- a/apps/web/tests/expected/plugin-manager/refresh.expected.md +++ b/apps/web/tests/expected/plugin-manager/refresh.expected.md @@ -6,7 +6,7 @@ Focus at 500ms: - tooltip "刷新" failure: pending - button "刷新" [disabled] -{"busy":"true","spinners":1,"cards":12,"skeletons":0,"alerts":[],"retry":0,"toasts":[]} +{"busy":"true","spinners":1,"cards":11,"skeletons":0,"alerts":[],"retry":0,"toasts":[]} failure: settled - button "刷新" -{"busy":"false","spinners":0,"cards":12,"skeletons":0,"alerts":[],"retry":0,"toasts":["刷新失败,请重试"]} +{"busy":"false","spinners":0,"cards":11,"skeletons":0,"alerts":[],"retry":0,"toasts":["刷新失败,请重试"]} diff --git a/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md new file mode 100644 index 0000000000..7a26f1bae7 --- /dev/null +++ b/apps/web/tests/expected/sidebar-subagent-activity/compact-running.expected.md @@ -0,0 +1,10 @@ +- banner: + - navigation "Session hierarchy": Delegate a background job. + - button "1 subagent" + - button "1 background job" + - button "More actions" + - button "Open right sidebar" + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" + - button "More conversation views" diff --git a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md index 0e4f8f018b..b60114ef0f 100644 --- a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md +++ b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md @@ -1,13 +1,13 @@ # Before opening the child - tree "Subagent sessions": - - treeitem "historical researcher Migration required · not running" [level=1]: - - text: historical researcher Migration required · not running + - treeitem "historical researcher migration-catalog-child · Migration required · not running" [level=1]: + - text: historical researcher migration-catalog-child Migration required - button "Open historical researcher in sidebar" # After opening the child - tree "Subagent sessions": - - treeitem "historical editor Migration required · not running" [level=1]: - - text: historical editor Migration required · not running + - treeitem "historical editor migration-catalog-grandchild · Migration required · not running" [level=1]: + - text: historical editor migration-catalog-grandchild Migration required - button "Open historical editor in sidebar" diff --git a/apps/web/tests/expected/subagent-conversation/navigation-only.expected.md b/apps/web/tests/expected/subagent-conversation/navigation-only.expected.md new file mode 100644 index 0000000000..76df6f6c57 --- /dev/null +++ b/apps/web/tests/expected/subagent-conversation/navigation-only.expected.md @@ -0,0 +1,8 @@ +- dialog "Subagent sessions": + - tree "Subagent sessions": + - treeitem "event-sourcing researcher {{uuid}} · continuable · not running 15.7K tok · {{duration}}" [level=1]: + - button "Expand event-sourcing researcher descendants" + - text: event-sourcing researcher {{uuid}} 15.7K tok {{duration}} + - treeitem "event-sourcing reviewer recorded-one-shot · one-shot · completed 0 tok · {{duration}}" [level=1]: + - text: event-sourcing reviewer recorded-one-shot 0 tok ~6mo 12d + - button "Open event-sourcing reviewer in sidebar" diff --git a/apps/web/tests/expected/subagent-result-notice/en.expected.md b/apps/web/tests/expected/subagent-result-notice/en.expected.md new file mode 100644 index 0000000000..a44d176b78 --- /dev/null +++ b/apps/web/tests/expected/subagent-result-notice/en.expected.md @@ -0,0 +1,41 @@ +- button "Subagent run completed {{clock}}" [expanded]: + - text: Subagent run completed + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child finished and will do no further work unless you send it more.Its closing message:## Research result The original child reply stays available. + +- button "Subagent run stopped {{clock}}" [expanded]: + - text: Subagent run stopped + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child was stopped before it finished.Its closing message:## Research result The original child reply stays available. + +- button "Subagent run failed {{clock}}" [expanded]: + - text: Subagent run failed + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child failed before it finished.Its closing message:## Research result The original child reply stays available. + +- button "Subagent reached the token limit {{clock}}" [expanded]: + - text: Subagent reached the token limit + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child ran out of room before it finished.Its closing message:## Research result The original child reply stays available. + +- button "Subagent declined the task {{clock}}" [expanded]: + - text: Subagent declined the task + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child declined the task.Its closing message:## Research result The original child reply stays available. + +- button "Subagent run completed {{clock}}" [expanded]: + - text: Subagent run completed + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent notice-result-child finished and will do no further work unless you send it more.It left no closing message. + +- button "Subtask status updated {{clock}}" [expanded]: + - text: Subtask status updated + - time: {{clock}} +- paragraph: This notification triggered this response. +- text: Background subagent finished. diff --git a/apps/web/tests/expected/subagent-result-notice/zh.expected.md b/apps/web/tests/expected/subagent-result-notice/zh.expected.md new file mode 100644 index 0000000000..d26df1f590 --- /dev/null +++ b/apps/web/tests/expected/subagent-result-notice/zh.expected.md @@ -0,0 +1,41 @@ +- button "子智能体已完成任务 {{clock}}" [expanded]: + - text: 子智能体已完成任务 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child finished and will do no further work unless you send it more.Its closing message:## Research result The original child reply stays available. + +- button "子智能体任务已停止 {{clock}}" [expanded]: + - text: 子智能体任务已停止 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child was stopped before it finished.Its closing message:## Research result The original child reply stays available. + +- button "子智能体执行失败 {{clock}}" [expanded]: + - text: 子智能体执行失败 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child failed before it finished.Its closing message:## Research result The original child reply stays available. + +- button "子智能体已达 token 上限 {{clock}}" [expanded]: + - text: 子智能体已达 token 上限 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child ran out of room before it finished.Its closing message:## Research result The original child reply stays available. + +- button "子智能体拒绝执行 {{clock}}" [expanded]: + - text: 子智能体拒绝执行 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child declined the task.Its closing message:## Research result The original child reply stays available. + +- button "子智能体已完成任务 {{clock}}" [expanded]: + - text: 子智能体已完成任务 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent notice-result-child finished and will do no further work unless you send it more.It left no closing message. + +- button "子任务状态更新 {{clock}}" [expanded]: + - text: 子任务状态更新 + - time: {{clock}} +- paragraph: 这条通知触发了本轮回复。 +- text: Background subagent finished. diff --git a/apps/web/tests/fold-blank-matrix.e2e.ts b/apps/web/tests/fold-blank-matrix.e2e.ts index c46a62c711..920534b6ca 100644 --- a/apps/web/tests/fold-blank-matrix.e2e.ts +++ b/apps/web/tests/fold-blank-matrix.e2e.ts @@ -623,8 +623,10 @@ async function prepareWorld(browser: Browser, scenario: Case, scaffold: WebScaff const trigger = page.getByRole('button', { name: '1 subagent', exact: true }) await trigger.waitFor({ timeout: 15_000 }) await trigger.hover() - await page.getByRole('treeitem', { name: new RegExp(CHILD_LABEL) }) - .getByRole('button', { name: `Open ${CHILD_LABEL} in sidebar`, exact: true }).click() + const openAside = page.getByRole('treeitem', { name: new RegExp(CHILD_LABEL) }) + .getByRole('button', { name: /^Open .+ in sidebar$/u }) + await expect.poll(() => openAside.count()).toBe(1) + await openAside.click() await page.locator(SIDE_ROOT).getByText('FOLDMX_BODY', { exact: false }).last().waitFor({ timeout: 30_000 }) await page.mouse.move(0, 0) return { diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 6be6b70c39..76da6c115e 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -685,7 +685,7 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and }) it.skipIf(MODE === 'record')('shows the local changes of the Session by scope and the changes of its change requests, expanding unchanged lines', async () => { - const { scaffold, page, root, project, tripwire } = await launchPanel('web-e2e-forge-panel-changes', 'follow-up') + const { scaffold, page, root, project, tripwire } = await launchPanel('web-e2e-forge-panel-changes', 'follow-up', { branch: 'feat' }) // origin/main stops at the twelve-line README; the branch adds a commit, a staged file, an edit, and an untracked file. await writeFile(join(project, 'README.md'), Array.from({ length: 12 }, (_, index) => `line ${index + 1}\n`).join('')) await git(project, 'commit', '--quiet', '-am', 'readme') @@ -722,7 +722,7 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await local.getByText('与 origin/main 比较,包含未提交的修改', { exact: true }).waitFor({ timeout: 20_000 }) const files = local.locator('[data-forge-diff-file]') await expect.poll(() => files.evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))), { timeout: 20_000 }) - .toEqual(['README.md', 'src/app.ts', 'src/extra.ts', 'notes.md']) + .toEqual(['src/app.ts', 'src/extra.ts', 'README.md', 'notes.md']) await local.locator('[data-forge-diff-file="notes.md"]').getByText('新文件 · 未提交', { exact: true }).waitFor() const readme = local.locator('[data-forge-diff-file="README.md"]') await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) @@ -778,6 +778,14 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await header.click() const change = page.locator(`[data-forge-change="${PULL}"]`) await change.getByRole('link', { name: 'Add the pull request panel', exact: true }).waitFor({ timeout: 20_000 }) + await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).waitFor() + expect(await card.getByRole('button', { name: '创建变更请求', exact: true }).count()).toBe(0) + await compareOrRefreshGolden(join(EXPECTED, 'local-and-pr.expected.md'), + await captureStableAria(page, '[data-forge-panel]', scaffold.workspaceCwd), MODE) + await card.getByRole('button', { name: '查看本会话的变更:4 个文件,新增 4 行,删除 1 行', exact: true }).click() + await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor() + await expect.poll(() => header.getAttribute('aria-pressed')).toBe('false') + await header.click() await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() const view = page.locator('[data-forge-changes="change"]') const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]') @@ -1075,8 +1083,9 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-file-keys') await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') - for (const path of ['a.txt', 'b.txt', 'c.txt']) { - await writeFile(join(project, path), Array.from({ length: path === 'c.txt' ? 1 : 80 }, (_, line) => `line ${line + 1}\n`).join('')) + await mkdir(join(project, 'src')) + for (const path of ['src/a.txt', 'src/b.txt', 'README.md']) { + await writeFile(join(project, path), Array.from({ length: path === 'README.md' ? 1 : 80 }, (_, line) => `line ${line + 1}\n`).join('')) } const { settled } = await sendPrompt(page, scaffold) await settled @@ -1089,9 +1098,13 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre await page.getByRole('button', { name: '全屏', exact: true }).click() await page.setViewportSize({ width: 1280, height: 500 }) const tree = view.getByRole('navigation') - const a = view.locator('[data-forge-diff-file="a.txt"]') - const b = view.locator('[data-forge-diff-file="b.txt"]') - const c = view.locator('[data-forge-diff-file="c.txt"]') + const files = view.locator('[data-forge-diff-file]') + const paths = await files.evaluateAll(elements => elements.map(element => element.getAttribute('data-forge-diff-file'))) + expect(paths).toEqual(['src/a.txt', 'src/b.txt', 'README.md']) + expect(await tree.locator('button:not([aria-expanded])').evaluateAll(elements => elements.map(element => element.getAttribute('aria-label')))).toEqual(paths) + const a = view.locator('[data-forge-diff-file="src/a.txt"]') + const b = view.locator('[data-forge-diff-file="src/b.txt"]') + const c = view.locator('[data-forge-diff-file="README.md"]') await b.getByRole('button', { name: '收起 b.txt', exact: true }).click() await scroll.evaluate((element) => { element.scrollTop = 0 }) await scroll.focus() @@ -1102,11 +1115,11 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre await expect.poll(() => scroll.evaluate(element => element.scrollTop)).toBeGreaterThan(0) await scroll.evaluate((element) => { element.scrollTop = 0 }) await page.keyboard.press('ArrowRight') - await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await expect.poll(() => tree.getByRole('button', { name: 'src/b.txt', exact: true }).getAttribute('aria-current')).toBe('true') expect(await b.getAttribute('data-expanded')).toBe('') expect(await scroll.evaluate(element => document.activeElement === element)).toBe(true) await page.keyboard.press('ArrowRight') - await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await expect.poll(() => tree.getByRole('button', { name: 'README.md', exact: true }).getAttribute('aria-current')).toBe('true') const lastPosition = await scroll.evaluate(element => element.scrollTop) const lastBox = await c.boundingBox(), viewport = await scroll.boundingBox() if (lastBox === null || viewport === null) throw new Error('The last file and scroll viewport must be rendered') @@ -1115,16 +1128,16 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre await page.keyboard.press('ArrowRight') expect(await scroll.evaluate(element => element.scrollTop)).toBe(lastPosition) await page.keyboard.press('ArrowLeft') - await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await expect.poll(() => tree.getByRole('button', { name: 'src/b.txt', exact: true }).getAttribute('aria-current')).toBe('true') await page.keyboard.press('ArrowLeft') - await expect.poll(() => tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await expect.poll(() => tree.getByRole('button', { name: 'src/a.txt', exact: true }).getAttribute('aria-current')).toBe('true') await b.evaluate((element) => { const viewport = element.closest('[data-forge-changes-scroll]')! viewport.scrollTop += element.getBoundingClientRect().top - viewport.getBoundingClientRect().top + 100 }) await page.keyboard.press('ArrowRight') - await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') - await tree.getByRole('button', { name: 'a.txt', exact: true }).click() + await expect.poll(() => tree.getByRole('button', { name: 'README.md', exact: true }).getAttribute('aria-current')).toBe('true') + await tree.getByRole('button', { name: 'src/a.txt', exact: true }).click() await a.getByRole('button', { name: '选择第 R1 行', exact: true }).click() await a.getByRole('button', { name: '添加评论', exact: true }).click() const input = a.getByRole('textbox', { name: '留下评论…', exact: true }) @@ -1133,7 +1146,7 @@ it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while pre expect(await input.evaluate(element => (element as HTMLTextAreaElement).selectionStart)).toBe(11) await input.press('ArrowRight') expect(await input.inputValue()).toBe('keep editing') - expect(await tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + expect(await tree.getByRole('button', { name: 'src/a.txt', exact: true }).getAttribute('aria-current')).toBe('true') expect(await input.evaluate(element => document.activeElement === element)).toBe(true) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) diff --git a/apps/web/tests/idle-submission-handoff.e2e.ts b/apps/web/tests/idle-submission-handoff.e2e.ts index 958c1f5e30..98f8b25f90 100644 --- a/apps/web/tests/idle-submission-handoff.e2e.ts +++ b/apps/web/tests/idle-submission-handoff.e2e.ts @@ -45,9 +45,9 @@ class HistoryDeliveryGate { return } const control = endpoint === 'session/control' && frame.type === 'item' - ? frame.value as { type: string; sessionId?: string; key?: string; value?: InboxState } : undefined - const inbox = control?.type === 'projection' && control.sessionId === SESSION_ID && control.key === 'inbox' - ? control.value : undefined + ? frame.value as { type: string; sessionId?: string; changes?: readonly { key: string; val: unknown }[] } : undefined + const inbox = control?.type === 'projection' && control.sessionId === SESSION_ID + ? control.changes?.find(change => change.key === 'inbox')?.val as InboxState | undefined : undefined const follow = endpoint === 'session/follow' && frame.type === 'item' ? frame.value as { type: string; event?: SessionEvent } : undefined this.buffered.push({ stream: frame.streamId, send: () => { socket.send(message) }, diff --git a/apps/web/tests/jobs-menu-layering.e2e.ts b/apps/web/tests/jobs-menu-layering.e2e.ts index 7388c9f4b3..ca2f53e227 100644 --- a/apps/web/tests/jobs-menu-layering.e2e.ts +++ b/apps/web/tests/jobs-menu-layering.e2e.ts @@ -28,7 +28,7 @@ const COMMAND = `printf 'jobs-menu-%s\\n' output; for _ in $(seq 1 3000); do [ - function placement(page: Page) { return page.evaluate(() => { const list = document.querySelector('ul[aria-label="Background jobs"]') - const anchor = document.querySelector('button[aria-label="1 background job running"]') + const anchor = document.querySelector('button[aria-label="1 background job"]') const frame = document.querySelector('[data-sidebar-browser-frame]') const dock = document.querySelector('[data-sidebar-right-panel][data-sidebar-right-open]') if (list === null || anchor === null || frame === null || dock === null) { @@ -105,6 +105,7 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => { it('keeps the list and live output above the Browser dock while anchored and dismissable', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-jobs-menu-layering')) + const initialViewport = page.viewportSize()! const session = page.locator(`[data-row-key="session:${SEED_ID}"]`) await expect.poll(async () => { if (await session.isVisible()) return true @@ -148,7 +149,7 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => { await page.frameLocator('[data-sidebar-browser-frame]') .getByRole('heading', { name: 'Jobs menu browser fixture' }).waitFor() - const trigger = page.getByRole('button', { name: '1 background job running', exact: true }) + const trigger = page.getByRole('button', { name: '1 background job', exact: true }) await trigger.waitFor({ timeout: 15_000 }) await trigger.focus() await page.keyboard.press('Enter') @@ -184,6 +185,13 @@ describe.skipIf(MODE === 'record')('web e2e: jobs menu layering', () => { await list.waitFor({ state: 'detached' }) const outsideDismisses = await trigger.getAttribute('aria-expanded') === 'false' expect(outsideDismisses).toBe(true) + await page.setViewportSize(initialViewport) + await trigger.hover() + await list.waitFor() + expect(await address.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Escape') + await list.waitFor({ state: 'detached' }) + expect(await address.evaluate(element => element === document.activeElement)).toBe(true) expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('running') expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) diff --git a/apps/web/tests/live-job-stream.e2e.ts b/apps/web/tests/live-job-stream.e2e.ts index 4bffdb8a62..b51d55ba99 100644 --- a/apps/web/tests/live-job-stream.e2e.ts +++ b/apps/web/tests/live-job-stream.e2e.ts @@ -85,7 +85,7 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => { it('streams a running job\'s real output into the expanded panel, then settles it in place on kill', async () => { let phase = 'streaming' onTestFailed(() => saveFailureShot(page, `web-e2e-live-job-${phase}`)) - const trigger = page.getByRole('button', { name: '1 background job running' }) + const trigger = page.getByRole('button', { name: '1 background job', exact: true }) expect(await trigger.count()).toBe(0) const started = await executeToolFixture(scaffold.ctx, { @@ -99,6 +99,14 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => { const matched = /\bbash-[0-9a-f]{16}\b/.exec(reported) if (matched === null) throw new Error(`background bash reported no job id: ${reported}`) const jobId = JobId(matched[0]) + await expect.poll(() => { + const job = scaffold.ctx.jobs.get(jobId, agent.id) + const output = scaffold.ctx.jobs.readAt(jobId, 0, agent.id).chunks.map(chunk => chunk.text).join('') + return job.status !== 'running' || output.includes('streamed-marker-line') + }, { timeout: 15_000 }).toBe(true) + const readyJob = scaffold.ctx.jobs.get(jobId, agent.id) + const readyOutput = scaffold.ctx.jobs.readAt(jobId, 0, agent.id).chunks.map(chunk => chunk.text).join('') + expect(readyJob.status, `${readyJob.detail ?? ''}\n${readyOutput}`).toBe('running') // The job row reaches the header over the job roster stream. await trigger.waitFor({ timeout: 15_000 }) @@ -116,13 +124,24 @@ describe.skipIf(MODE === 'record')('web e2e: live job stream', () => { expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) + await trigger.click() + await page.getByRole('list', { name: 'Background jobs' }).waitFor({ state: 'detached' }) + expect(await page.getByText('streamed-marker-line', { exact: true }).count()).toBe(0) + await page.mouse.move(2, 2) + await trigger.hover() + await page.getByRole('list', { name: 'Background jobs' }).waitFor() + await page.getByRole('button', { name: /Hide live output/ }).waitFor() + await page.getByText('streamed-marker-line', { exact: true }).waitFor() + expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('running') + phase = 'settled' expect(scaffold.ctx.jobs.kill(jobId, agent.id, 'web e2e cancellation')).toBe('requested') - // Settlement arrives on the observation stream itself, so the open panel - // flips without any further interaction; the roster trigger follows. - const idle = page.getByRole('button', { name: '1 background job', exact: true }) - await idle.waitFor({ timeout: 20_000 }) + // The unchanged count label is not a settlement signal; the output row owns that state. + await page.getByRole('button', { name: 'Finished 1', exact: true }).waitFor({ timeout: 20_000 }) + await expect.poll(() => page.getByRole('list', { name: 'Background jobs' }).textContent()).toContain('web e2e cancellation') + expect(await trigger.getAttribute('aria-label')).toBe('1 background job') + expect(scaffold.ctx.jobs.get(jobId, agent.id).status).toBe('killed') await page.getByText('streamed-marker-line').waitFor({ timeout: 10_000 }) const settled = await captureStableAria(page, '[class*="menu"]', scaffold.workspaceCwd) diff --git a/apps/web/tests/math-rendering.e2e.ts b/apps/web/tests/math-rendering.e2e.ts index 8612498522..d7fa2b8873 100644 --- a/apps/web/tests/math-rendering.e2e.ts +++ b/apps/web/tests/math-rendering.e2e.ts @@ -56,9 +56,6 @@ function mathFixture(): string { '', '$$\\theta \\in \\left(\\frac{\\pi}{4}, \\frac{\\pi}{2}\\right). \\tag{1}$$', '', - '$$\\alpha+\\beta', - '\\gamma$$', - '', '| Symbol | Value |', '| --- | --- |', '| $\\theta$ | \\(\\frac{1}{5}\\) |', @@ -122,8 +119,8 @@ describe('web e2e: settled Markdown math rendering', () => { await sessionRow.click() await expect.poll(() => page.getByText(DONE, { exact: true }).count(), { timeout: 15_000 }).toBe(1) - await expect.poll(() => page.locator('.katex').count(), { timeout: 10_000 }).toBe(7) - await expect.poll(() => page.locator('.katex-display').count(), { timeout: 10_000 }).toBe(3) + await expect.poll(() => page.locator('.katex').count(), { timeout: 10_000 }).toBe(6) + await expect.poll(() => page.locator('.katex-display').count(), { timeout: 10_000 }).toBe(2) expect(await page.locator('.katex-error').count()).toBe(0) const fonts = await page.evaluate(async () => { const faces = [...document.fonts].filter(face => face.family.includes('KaTeX_')) diff --git a/apps/web/tests/menu-material.e2e.ts b/apps/web/tests/menu-material.e2e.ts index 4f65a889a8..37ce2afb17 100644 --- a/apps/web/tests/menu-material.e2e.ts +++ b/apps/web/tests/menu-material.e2e.ts @@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import { chromium, type Locator } from 'playwright' +import { chromium, webkit, type Locator } from 'playwright' import sharp from 'sharp' import { expect, it, onTestFinished } from 'vitest' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSession, webSnapshotMode } from './scaffold.ts' @@ -10,6 +10,44 @@ import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, seedSessi const expected = fileURLToPath(new URL('./expected/menu-material', import.meta.url)) const seed = new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url) +it('keeps the view options menu anchored and dismissible through WebKit window resizing', async () => { + const scaffold = await launchWebScaffold({}) + onTestFinished(() => scaffold.close()) + const browser = await webkit.launch() + onTestFinished(() => browser.close()) + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 }, locale: 'en-US' }) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const anchor = page.getByRole('button', { name: 'View options', exact: true }) + await anchor.click() + const menu = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Workspace Tree', exact: true }) }) + await menu.waitFor() + for (const viewport of [{ width: 1440, height: 1000 }, { width: 1200, height: 700 }]) { + await page.setViewportSize(viewport) + await expect.poll(async () => { + const trigger = await anchor.boundingBox() + const panel = await menu.boundingBox() + if (trigger === null || panel === null) return null + return { + // The menu can be wider than the sidebar, so its left margin takes precedence over end alignment. + horizontalOffset: Math.round(panel.x - Math.max(12, trigger.x + trigger.width - panel.width)), + topGap: Math.round(panel.y - trigger.y - trigger.height), + insideViewport: panel.x >= 12 && panel.y >= 12 + && panel.x + panel.width <= viewport.width - 12 + && panel.y + panel.height <= viewport.height - 12, + } + }).toEqual({ horizontalOffset: 0, topGap: 4, insideViewport: true }) + } + await page.keyboard.press('Escape') + await menu.waitFor({ state: 'hidden' }) + await anchor.click() + await menu.waitFor() + await page.mouse.click(800, 500) + await menu.waitFor({ state: 'hidden' }) + await anchor.click() + await page.getByRole('menuitem', { name: 'In one list', exact: true }).click() + await menu.waitFor({ state: 'hidden' }) +}) + async function material(menu: Locator) { return menu.evaluate((node) => { const style = getComputedStyle(node) diff --git a/apps/web/tests/minimal-preset.snapshot.ts b/apps/web/tests/minimal-preset.snapshot.ts index ee65497459..8a131ed29b 100644 --- a/apps/web/tests/minimal-preset.snapshot.ts +++ b/apps/web/tests/minimal-preset.snapshot.ts @@ -142,8 +142,11 @@ describe('minimal agent preset', () => { ], } `) + const requestedTools = new Set(requestHeader.tools?.map(tool => tool.name)) expect(requestHeader.tools?.toSorted((left, right) => left.name.localeCompare(right.name))) - .toEqual(scaffold.ctx.tools.schemas(agentHandle.agent).toSorted((left, right) => left.name.localeCompare(right.name))) + .toEqual(scaffold.ctx.tools.schemas(agentHandle.agent) + .filter(tool => requestedTools.has(tool.name)) + .toSorted((left, right) => left.name.localeCompare(right.name))) }) it.skipIf(MODE === 'record')('expands the completed persistent Bash call in the Web conversation', async () => { diff --git a/apps/web/tests/model-menu-observer.e2e.ts b/apps/web/tests/model-menu-observer.e2e.ts index 4c58bc9db9..3ec0b7dd45 100644 --- a/apps/web/tests/model-menu-observer.e2e.ts +++ b/apps/web/tests/model-menu-observer.e2e.ts @@ -22,7 +22,9 @@ const PROVIDERS = [ ].map((provider, providerIndex) => ({ ...provider, models: Array.from({ length: 7 }, (_, index) => providerIndex === 0 && index === 0 - ? { id: 'origin-large', name: 'Origin Large' } + ? { id: 'origin-large', name: 'Origin Large', reasoningEfforts: { + off: null, minimal: 'minimal', low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh', max: 'max', + } } : { id: `${provider.prefix.toLowerCase()}-model-${index + 1}`, name: `${provider.prefix} Model ${index + 1}` }), })) const EXPECTED_GROUPS = [ @@ -287,4 +289,141 @@ describe.skipIf(webSnapshotMode() === 'record').each([ expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'origin-gateway', model: 'origin-large' }) expect(tripwire.pageErrors).toEqual([]) }) + it.runIf(engine === chromium)('keeps the complete model card inside the zoomed visual viewport', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-model-menu-zoom')) + const cdp = await page.context().newCDPSession(page) + try { + await page.setViewportSize({ width: 402, height: 874 }) + await page.getByRole('button', { name: /^选择模型/ }).click() + await page.getByRole('menuitem', { name: /^模型/ }).click() + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) + for (const height of [874, 500]) { + await page.setViewportSize({ width: 402, height }) + await expect.poll(() => page.getByRole('group', { name: '模型与推理等级', exact: true }).evaluate((panel) => { + const viewport = window.visualViewport! + const rect = panel.getBoundingClientRect() + return Math.min(rect.left - viewport.offsetLeft, rect.top - viewport.offsetTop, + viewport.offsetLeft + viewport.width - rect.right, viewport.offsetTop + viewport.height - rect.bottom) + })).toBeGreaterThanOrEqual(11.5) + expect(await page.evaluate(() => window.visualViewport!.scale)).toBeGreaterThan(2) + const models = page.getByRole('menu', { name: '模型', exact: true }) + const names = models.locator('[data-model-id]').locator('..') + expect(await names.evaluateAll(labels => labels.every(label => + getComputedStyle(label).textOverflow === 'ellipsis'))).toBe(true) + expect(await names.evaluateAll(labels => labels.some(label => + label.scrollWidth > label.clientWidth))).toBe(true) + expect(await models.evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true) + const widths = await models.locator('[role="menuitemradio"]').evaluateAll(rows => rows.map(row => ({ + right: row.lastElementChild!.getBoundingClientRect().right, + width: row.getBoundingClientRect().width, + }))) + expect(Math.max(...widths.map(row => row.right)) - Math.min(...widths.map(row => row.right))).toBeLessThan(1) + expect(Math.max(...widths.map(row => row.width)) - Math.min(...widths.map(row => row.width))).toBeLessThan(1) + await scrollToGroup(models, 1, 10) + await expect.poll(() => models.locator('[data-menu-group-heading]').nth(1).getAttribute('data-stuck')).not.toBeNull() + const coversViewport = await models.evaluate((node) => { + const viewport = node.getBoundingClientRect() + const heading = node.querySelector('[data-menu-group-heading][data-stuck]')!.getBoundingClientRect() + return heading.left <= viewport.left + 1 && heading.right >= viewport.right - 1 + }) + expect(coversViewport).toBe(true) + } + } finally { + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) + await cdp.detach() + await page.keyboard.press('Escape') + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1680, height: 1000 }) + } + }) + + it.runIf(engine === chromium)('aligns the menu with its anchor after zooming and panning both viewport axes', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-model-menu-pan')) + const cdp = await page.context().newCDPSession(page) + try { + await page.setViewportSize({ width: 1440, height: 1000 }) + const trigger = page.getByRole('button', { name: /^选择模型/ }) + await trigger.click() + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1.5 }) + await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(1.5) + await frames(page) + const target = await menu.evaluate((panel) => { + const viewport = window.visualViewport! + const anchor = document.querySelector(`[aria-controls="${panel.id}"]`)!.getBoundingClientRect() + const rect = panel.getBoundingClientRect() + // Keep the preferred placement away from clamps so adding an offset twice cannot pass. + const left = Math.max(1, anchor.right - viewport.width + 12) + const right = Math.min(window.innerWidth - viewport.width, anchor.right - rect.width - 12) + const top = Math.max(1, anchor.top - 8 + 12 - viewport.height) + const bottom = Math.min(window.innerHeight - viewport.height, anchor.top - 8 - rect.height - 12) + const dx = (left + right) / 2 - viewport.offsetLeft + const dy = (top + bottom) / 2 - viewport.offsetTop + return { left, right, top, bottom, dx, dy, + x: viewport.width / 2, y: viewport.height / 2 } + }) + expect(target.right).toBeGreaterThan(target.left) + expect(target.bottom).toBeGreaterThan(target.top) + // Use native wheel scrolling; Linux headless synthetic touch can deliver events without scrolling. + await cdp.send('Input.synthesizeScrollGesture', { + x: target.x, y: target.y, xDistance: -target.dx, yDistance: 0, gestureSourceType: 'mouse', speed: 800, + }) + await expect.poll(() => page.evaluate(() => window.visualViewport!.offsetLeft)).toBeGreaterThan(0) + await frames(page) + await cdp.send('Input.synthesizeScrollGesture', { + x: target.x, y: target.y, yDistance: -target.dy, gestureSourceType: 'mouse', speed: 800, + }) + await expect.poll(() => page.evaluate(() => Math.min(window.visualViewport!.offsetLeft, + window.visualViewport!.offsetTop))).toBeGreaterThan(0) + await expect.poll(() => menu.evaluate((panel) => { + const anchor = document.querySelector(`[aria-controls="${panel.id}"]`)!.getBoundingClientRect() + const rect = panel.getBoundingClientRect() + return Math.max(Math.abs(rect.right - anchor.right), Math.abs(anchor.top - rect.bottom - 8)) + })).toBeLessThan(1) + } finally { + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) + await cdp.detach() + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1680, height: 1000 }) + } + }) + + it.runIf(engine === chromium)('scrolls to and selects the last reasoning effort after zooming', async () => { + const cdp = await page.context().newCDPSession(page) + try { + await page.setViewportSize({ width: 402, height: 500 }) + await page.getByRole('button', { name: /^选择模型/ }).click() + await page.getByRole('menuitem', { name: /^推理等级/ }).click() + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 2.5 }) + const menu = page.getByRole('menu', { name: '模型与推理等级', exact: true }) + const last = menu.getByRole('menuitemradio').last() + expect(await menu.getByRole('menuitemradio').count()).toBeGreaterThanOrEqual(7) + await expect.poll(() => last.evaluate((row) => { + const scroller = row.parentElement! + scroller.scrollTop = scroller.scrollHeight + return { overflow: getComputedStyle(scroller).overflowY, moved: scroller.scrollTop > 0 } + })).toEqual({ overflow: 'auto', moved: true }) + await expect.poll(() => last.evaluate((row) => { + const rect = row.getBoundingClientRect() + const viewport = row.parentElement!.getBoundingClientRect() + return rect.top >= viewport.top - 1 && rect.bottom <= viewport.bottom + 1 + })).toBe(true) + // Dispatch the touch at the now-visible row; locator.click would auto-scroll even hidden overflow. + const point = await last.evaluate((row) => { + const rect = row.getBoundingClientRect() + const viewport = window.visualViewport! + return { x: rect.left + rect.width / 2 - viewport.offsetLeft, + y: rect.top + rect.height / 2 - viewport.offsetTop } + }) + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [point] }) + await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }) + await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection()).toMatchObject({ reasoningEffort: 'max' }) + } finally { + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 1 }) + await cdp.detach() + await page.keyboard.press('Escape') + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1680, height: 1000 }) + } + }) }) diff --git a/apps/web/tests/navigation-panes.e2e.ts b/apps/web/tests/navigation-panes.e2e.ts index 9632042b34..afc484f543 100644 --- a/apps/web/tests/navigation-panes.e2e.ts +++ b/apps/web/tests/navigation-panes.e2e.ts @@ -319,6 +319,44 @@ describe('web e2e: navigation & panes over a rich seeded session', () => { await details.getByRole('button', { name: 'Close details' }).click() }, 60_000) + it.skipIf(MODE === 'record')('keeps trajectory folding and search usable at 390px in every locale', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-trajectory-toolbar-narrow')) + await ensureSeedOpen(page) + await page.getByRole('tab', { name: 'Trajectory' }).click() + const toolbar = page.getByRole('toolbar') + const search = toolbar.getByRole('searchbox') + try { + for (const locale of ['en', 'zh', 'ja', 'es', 'fr', 'de', 'ru', 'pt']) { + await scaffold.ctx.settings.update('locale', { preference: locale }) + await expect.poll(() => page.evaluate(() => document.documentElement.lang)) + .toBe(locale === 'zh' ? 'zh-CN' : locale) + await search.fill('NAVIGATION_OK') + await page.setViewportSize({ width: 390, height: 844 }) + await expect.poll(() => toolbar.evaluate((element) => { + const bounds = element.getBoundingClientRect() + return { + fits: element.scrollWidth <= element.clientWidth + 1, + controlsFit: [...element.querySelectorAll('button:not([hidden]), input')].every((control) => { + const rect = control.getBoundingClientRect() + return rect.width > 0 && rect.height > 0 + && rect.left >= bounds.left && rect.right <= bounds.right + && rect.top >= bounds.top && rect.bottom <= bounds.bottom + }), + } + }), { message: `${locale} toolbar at 390px` }).toEqual({ fits: true, controlsFit: true }) + expect(await search.evaluate(element => element === document.activeElement)).toBe(true) + expect(await search.inputValue()).toBe('NAVIGATION_OK') + await search.fill('') + const subcalls = toolbar.getByRole('button').last() + await subcalls.click() + expect(await subcalls.isVisible()).toBe(true) + await page.setViewportSize({ width: 1680, height: 1_000 }) + } + } finally { + await scaffold.ctx.settings.update('locale', { preference: 'en' }) + } + }, 90_000) + it.skipIf(MODE === 'record')('restores Assistant timing from recorded history', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-timing')) await ensureSeedOpen(page) diff --git a/apps/web/tests/notice-wake-tail.e2e.ts b/apps/web/tests/notice-wake-tail.e2e.ts index 884adcb9d3..a45a5b85d7 100644 --- a/apps/web/tests/notice-wake-tail.e2e.ts +++ b/apps/web/tests/notice-wake-tail.e2e.ts @@ -170,6 +170,7 @@ describe('web e2e: notice Turn after a long Detailed Turn', () => { kind: 'subagent-settled', form: 'notice', summary: 'Background subagent finished.', + stopReason: 'completed', senderSessionId: SessionId('notice-wake-child'), } const notice = createUserMessage({ diff --git a/apps/web/tests/official-subagent-bundle.e2e.ts b/apps/web/tests/official-subagent-bundle.e2e.ts index 8a21671b29..ef6268cd42 100644 --- a/apps/web/tests/official-subagent-bundle.e2e.ts +++ b/apps/web/tests/official-subagent-bundle.e2e.ts @@ -7,12 +7,13 @@ import { fileURLToPath } from 'node:url' import { chromium, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { startMockLlmServer, type MockLlmServer } from '@deepseek-ai/dsh-llm-mock-server' +import { parseSessionHeader } from '@deepseek-ai/dsh-llm-replay' import type {} from '@deepseek-ai/dsh-plugin-manager' import type {} from '@deepseek-ai/dsh-tools' import type {} from '@deepseek-ai/dsh-subagent' import { assertFinalWorkspaceSnapshot, assertFixtureInventory, captureExpandedTurnProcessAria, compareOrRefreshGolden, - fixtureUserPrompts, launchWebScaffold, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, + fixtureUserPrompts, launchWebScaffold, seedSession, selectedSessionFixture, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { connectFreshWorkspace, newEnglishPage, saveFailureShot } from './support.ts' @@ -137,6 +138,14 @@ describe.skipIf(MODE === 'record')('web snapshot: Official native subagent bundl const sessionId = await settled const agent = scaffold.ctx.agents.get(sessionId) if (agent === undefined) throw new Error('Native delegation Session has no live Agent') + const firstTurnEvents = agent.session.snapshotEvents() + const toolResults = firstTurnEvents.filter(event => event.type === 'tool/result').map(event => event.data) + expect(toolResults, `PTC execution must start the native child before waiting for its result: ${JSON.stringify(toolResults)}`) + .toMatchObject([{ message: { isError: false } }]) + const dispatches = firstTurnEvents.filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data) + expect(dispatches).toMatchObject([{ name: 'subagent_claude_code', isError: false }]) + const catalog = firstTurnEvents.filter(event => event.type === 'subagent/catalog').map(event => event.data) + expect(catalog).toMatchObject([{ mode: 'external', label: 'Read the fixture response' }]) expect(server.requests).toHaveLength(0) const completed = scaffold.whenTurnSettled(120_000) nativeEndpoint.release() @@ -148,10 +157,6 @@ describe.skipIf(MODE === 'record')('web snapshot: Official native subagent bundl expect(system).toContain('subagent_claude_code') const events = agent.session.snapshotEvents() expect(events.filter(event => event.type === 'tool/call').map(event => event.data.name)).toEqual(['run_code']) - const dispatches = events.filter(event => event.type === 'tool/ptc-dispatch').map(event => event.data) - expect(dispatches).toMatchObject([{ name: 'subagent_claude_code', isError: false }]) - const catalog = events.filter(event => event.type === 'subagent/catalog').map(event => event.data) - expect(catalog).toMatchObject([{ mode: 'external', label: 'Read the fixture response' }]) const notice = events.filter(event => event.type === 'user/message').find(event => event.data.source.kind === 'subagent-settled') if (notice?.data.source.kind !== 'subagent-settled') throw new Error('Native completion was not delivered to the parent') expect(notice.data.source.senderSessionId).toBe(catalog[0]?.childId) @@ -178,3 +183,31 @@ describe.skipIf(MODE === 'record')('web snapshot: Official native subagent bundl ]) }) }) + +it.skipIf(MODE === 'record')('renders recorded official notice titles after reopening the Session', async () => { + const scaffold = await launchWebScaffold({ developerTools: true }) + let browser: Browser | undefined + try { + const fixture = await readFile(await selectedSessionFixture(FIXTURE), 'utf8') + await seedSession(scaffold, fixture, 'official-subagent-recorded-ui') + browser = await chromium.launch() + const page = await newEnglishPage(browser) + await page.clock.setFixedTime(parseSessionHeader(fixture).createdAt) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + const workspace = page.locator('[role="treeitem"]').first() + await workspace.waitFor() + await workspace.click() + const session = page.locator('[role="treeitem"]').nth(1) + await session.waitFor() + await session.click() + const heading = page.locator('[data-turn-trigger] > button > span').nth(1) + await expect.poll(() => heading.textContent()).toBe('Subagent run completed') + await compareOrRefreshGolden(join(DIR, 'ui.expected.md'), + await captureExpandedTurnProcessAria(page, '[data-chat-flow]', scaffold.workspaceCwd), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 333accd0aa..8706a7a4de 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -305,6 +305,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await picker.getByText('暂无可用模型', { exact: true }).waitFor() expect(await picker.getByRole('menuitemradio').count()).toBe(0) expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual(selection) + expect(await picker.getByRole('menu', { name: '模型', exact: true }).count()).toBe(0) await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'empty.expected.md'), await picker.ariaSnapshot(), MODE) await seat.press('Escape') await picker.waitFor({ state: 'hidden' }) diff --git a/apps/web/tests/plugin-config.e2e.ts b/apps/web/tests/plugin-config.e2e.ts index 8e78f856eb..8bba474e11 100644 --- a/apps/web/tests/plugin-config.e2e.ts +++ b/apps/web/tests/plugin-config.e2e.ts @@ -23,6 +23,7 @@ const ROW_EXPECTED = join(SNAPSHOT_DIR, 'row.expected.md') const BUNDLE_EXPECTED = join(SNAPSHOT_DIR, 'bundle.expected.md') const FIXTURE_PLUGINS = fileURLToPath(new URL('./fixtures/plugins', import.meta.url)) const MODE = webSnapshotMode() +const UNUSED_KEY_ENV = 'DSH_PLUGIN_CONFIG_E2E_UNUSED_KEY' describe('web e2e: plugin configuration pages', () => { let scaffold: WebScaffold @@ -35,7 +36,8 @@ describe('web e2e: plugin configuration pages', () => { // below, that half registers its row's configuration into the page. scaffold = await launchWebScaffold({ extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), - deepSeekSearch: { apiKeyEnv: 'DSH_PLUGIN_CONFIG_E2E_UNUSED_KEY' }, + deepSeekSearch: { apiKeyEnv: UNUSED_KEY_ENV }, + deepSeekWebApi: { apiKeyEnv: UNUSED_KEY_ENV }, profile: { packages: [{ dir: join(FIXTURE_PLUGINS, 'fixture-live-client') }] }, }) browser = await chromium.launch() diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 7963b22779..2787a31f3a 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -9,7 +9,6 @@ import type { Browser, Locator, Page } from 'playwright' import { chromium } from 'playwright' import { FiberState } from '@deepseek-ai/cordis' import { readProfileManifest } from '@deepseek-ai/dsh-app-boot' -import { createUserMessage } from '@deepseek-ai/dsh-llm' import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest' import { join } from 'node:path' import { @@ -869,7 +868,6 @@ describe('web e2e: plugin manager', () => { await card.getAttribute('data-plugin-package'), await card.getByText('实验性', { exact: true }).count(), ]))).toEqual([ - ['@deepseek-ai/dsh-experimental-agent-team-profile', 1], ['@deepseek-ai/dsh-experimental-voice-input-bundle', 1], ['@deepseek-ai/dsh-experimental-plugin-market-bundle', 1], ['@deepseek-ai/dsh-experimental-auto-review', 1], @@ -973,7 +971,7 @@ describe('web e2e: plugin manager', () => { onTestFinished(closeSettings) const fixtureIcon = `data:image/svg+xml;base64,${(await readFile(join(FIXTURE_PLUGINS, 'fixture-bundle/icon.svg'))).toString('base64')}` const fallbackIcon = `data:image/svg+xml;base64,${(await readFile(join(FIXTURE_PLUGINS, 'fixture-bundle/fallback-icon.svg'))).toString('base64')}` - const teamIcon = `data:image/svg+xml;base64,${(await readFile(fileURLToPath(new URL('../../../packages/experimental/agent-team-profile/icon.svg', import.meta.url)))).toString('base64')}` + const voiceIcon = `data:image/svg+xml;base64,${(await readFile(fileURLToPath(new URL('../../../packages/experimental/voice-input-bundle/icon.svg', import.meta.url)))).toString('base64')}` const images: string[] = [] const checkImage = async (selector: string, source: string, label: string) => { const image = panel.locator(`${selector} img`).first() @@ -987,9 +985,9 @@ describe('web e2e: plugin manager', () => { images.push(`${label}: image, ${size.width}×${size.height}, decoded`) } await checkImage('[data-plugin-package="@fixture/bundle"]', fixtureIcon, 'Third-party bundle card') - const team = panel.locator('[data-plugin-package="@deepseek-ai/dsh-experimental-agent-team-profile"]') + const team = panel.locator('[data-plugin-package="@deepseek-ai/dsh-experimental-voice-input-bundle"]') expect(await team.getByRole('switch').getAttribute('aria-checked')).toBe('false') - await checkImage('[data-plugin-package="@deepseek-ai/dsh-experimental-agent-team-profile"]', teamIcon, 'Disabled Agent Teams card') + await checkImage('[data-plugin-package="@deepseek-ai/dsh-experimental-voice-input-bundle"]', voiceIcon, 'Disabled Voice Input card') try { for (const colorScheme of ['light', 'dark'] as const) { await page.emulateMedia({ colorScheme }) @@ -1003,8 +1001,8 @@ describe('web e2e: plugin manager', () => { } finally { await page.emulateMedia({ colorScheme: null }) } - await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click() - await checkImage('[data-plugin-detail]', teamIcon, 'Agent Teams detail') + await panel.getByRole('button', { name: '查看 语音输入', exact: true }).click() + await checkImage('[data-plugin-detail]', voiceIcon, 'Voice Input detail') await panel.getByRole('button', { name: '返回插件' }).click() await panel.getByRole('button', { name: '查看 @fixture/bundle', exact: true }).click() await checkImage('[data-plugin-detail]', fixtureIcon, 'Third-party bundle detail') @@ -1104,23 +1102,18 @@ describe('web e2e: plugin manager', () => { onTestFinished(closeSettings) onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-manager-locale')) const panel = await openPluginsPanel() - await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click() + await panel.getByRole('button', { name: '查看 语音输入', exact: true }).click() const packageName = panel.locator('[data-plugin-name]') - expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-agent-team-profile') - expect(await panel.getByText(experimentalBundleDescription('agent-team-profile', 'zh')).count()).toBe(1) - const child = panel.locator('[data-plugin-row]', { hasText: 'tool-agent-team' }) - await child.getByText('团队工具', { exact: true }).waitFor() - expect(await child.getByText('为智能体提供成员协调、消息通信和共享任务管理工具。', { exact: true }).count()).toBe(1) + expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-voice-input-bundle') + expect(await panel.getByText('在本机使用 SenseVoice 转写录音,首次使用需安装依赖。').count()).toBe(1) try { await setLanguage('en') - await panel.getByRole('heading', { name: 'Agent teams', exact: true }).waitFor() - expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-agent-team-profile') - expect(await panel.getByText(experimentalBundleDescription('agent-team-profile', 'en')).count()).toBe(1) - await child.getByText('Team tools', { exact: true }).waitFor() - expect(await child.getByText('Give agents tools to coordinate members, exchange messages, and manage shared tasks.', { exact: true }).count()).toBe(1) + await panel.getByRole('heading', { name: 'Voice input', exact: true }).waitFor() + expect(await packageName.textContent()).toBe('@deepseek-ai/dsh-experimental-voice-input-bundle') + expect(await panel.getByText('Transcribe recordings locally with SenseVoice; first use requires installing dependencies').count()).toBe(1) await panel.getByRole('button', { name: 'Back to plugins' }).click() - await panel.getByRole('button', { name: 'View Agent teams', exact: true }).waitFor() - expect(await panel.getByRole('switch', { name: 'Enable Agent teams', exact: true }).count()).toBe(1) + await panel.getByRole('button', { name: 'View Voice input', exact: true }).waitFor() + expect(await panel.getByRole('switch', { name: 'Enable Voice input', exact: true }).count()).toBe(1) // Schedule ships in the delivered composition, so no bundle card carries it in either language. expect(await panel.getByRole('button', { name: 'View Automation tasks', exact: true }).count()).toBe(0) // The official configuration pages follow the language too, from their own dictionary. @@ -1130,69 +1123,35 @@ describe('web e2e: plugin manager', () => { } finally { await setLanguage('zh') } - await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).waitFor() + await panel.getByRole('button', { name: '查看 语音输入', exact: true }).waitFor() expect(tripwire.pageErrors).toEqual([]) }, 60_000) - it('enables the Team tools and browser plugin with one bundle switch', async () => { + it('provides Team mode per Session without an experimental plugin switch', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-manager-team')) + onTestFinished(closeSettings) const panel = await openPluginsPanel() - const toggle = panel.getByRole('switch', { name: '启用 智能体团队', exact: true }) - const teamRows = () => [...scaffold.ctx.loader.entries()] - .filter(entry => ['agent-team', 'tool-agent-team', 'ui-agent-team'].includes(entry.options.id)) + expect(await panel.getByRole('switch', { name: '启用 智能体团队', exact: true }).count()).toBe(0) + expect(await panel.locator('[data-plugin-package="@deepseek-ai/dsh-experimental-agent-team-profile"]').count()).toBe(0) + expect([...scaffold.ctx.loader.entries()].filter(entry => + ['agent-team', 'tool-agent-team', 'ui-agent-team'].includes(entry.options.id) + && entry.fiber?.state === FiberState.ACTIVE)).toHaveLength(3) const teamPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) const teamTripwire = watchConsole(teamPage) try { await teamPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) await connectFreshWorkspaceZh(teamPage, scaffold.workspaceCwd) - const agent = scaffold.ctx.agents.list()[0] - if (agent === undefined) throw new Error('connected Team workspace did not create an Agent') - // Session actions render only after the conversation leaves its blank state. - agent.session.append('turn/start', { turn: 1 }) - agent.session.append('user/message', createUserMessage({ - content: [{ type: 'text', text: 'Team UI lifecycle' }], source: { kind: 'user' }, - }), { surfaceOp: 'append' }) - agent.session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - await scaffold.ctx.sessions.flush(agent.session) - // The current crumb renders as plain text inside the zh-labeled hierarchy nav. - await teamPage.getByRole('navigation', { name: '会话层级' }) - .getByText('Team UI lifecycle', { exact: true }).waitFor() - const action = teamPage.locator('[data-team-action]') - expect(await action.count()).toBe(0) - await toggle.click() - try { - await expect.poll(() => teamRows().filter(entry => entry.fiber?.state === FiberState.ACTIVE).length, { timeout: 20_000 }).toBe(3) - await expect.poll(() => toggle.getAttribute('aria-checked'), { timeout: PLUGIN_TOGGLE_SETTLE_MS }).toBe('true') - await action.waitFor({ timeout: 20_000 }) - await action.getByRole('button', { name: '智能体团队', exact: true }).click() - const teamPanel = teamPage.getByRole('dialog', { name: '智能体团队', exact: true }) - await teamPanel.getByText('Team 暂不可用', { exact: true }).waitFor() - await teamPage.reload({ waitUntil: 'load' }) - await action.getByRole('button', { name: '智能体团队', exact: true }).click() - await teamPanel.getByText('暂无共享任务,可以通过对话创建').waitFor() - await teamPanel.getByText('lead', { exact: true }).waitFor() - const manifest = JSON.parse(await homeFile('profiles', 'scaffold', 'package.json')) as { - dsh: { profile: { bundles: string[] } } - } - expect(manifest.dsh.profile.bundles).toEqual([...SCAFFOLD_BUNDLES, '@deepseek-ai/dsh-experimental-agent-team-profile']) - await panel.getByRole('button', { name: '查看 智能体团队', exact: true }).click() - for (const id of ['agent-team', 'tool-agent-team', 'ui-agent-team']) { - await panel.locator('[data-plugin-row]', { hasText: id }).first().waitFor() - } - await panel.getByRole('button', { name: '返回插件' }).click() - } finally { - const back = panel.getByRole('button', { name: '返回插件' }) - if (await back.count() > 0) await back.click() - if (await toggle.getAttribute('aria-checked') === 'true') await toggle.click() - await expect.poll(() => teamRows().filter(entry => entry.fiber?.state === FiberState.ACTIVE).length, { timeout: 20_000 }).toBe(0) - await expect.poll(() => action.count(), { timeout: 20_000 }).toBe(0) - } + await teamPage.getByRole('button', { name: /^选择模型/u }).click() + const mode = teamPage.getByRole('switch', { name: '启用智能体团队协作', exact: true }) + await mode.waitFor() + expect(await mode.getAttribute('aria-checked')).toBe('false') + await mode.click() + await expect.poll(() => mode.getAttribute('aria-checked')).toBe('true') expect(teamTripwire.pageErrors).toEqual([]) expect(teamTripwire.warnings).toEqual([]) } finally { await teamPage.close() } - expect(tripwire.pageErrors).toEqual([]) }, 60_000) it('mounts the delivered Automation tasks rows without a bundle switch', async () => { @@ -1249,6 +1208,19 @@ describe('web e2e: plugin manager', () => { const registryToggle = dialog.getByRole('button', { name: /^安装源/ }) await registryToggle.click() const registry = probe.locator('[data-install-registry]') + await registry.waitFor() + for (const width of [390, 800, 1680]) { + await probe.setViewportSize({ width, height: 1000 }) + await probe.clock.runFor(300) + await expect.poll(async () => { + const rect = await registry.boundingBox() + const anchor = await registryToggle.boundingBox() + return rect !== null && anchor !== null + && rect.x >= 11 && rect.x + rect.width <= width - 11 + && rect.y >= 11 && rect.y + rect.height <= 989 + && Math.abs(rect.x - Math.max(12, Math.min(anchor.x + anchor.width - rect.width, width - rect.width - 12))) <= 1 + }).toBe(true) + } const offered = registry.getByRole('radio', { name: 'npm 官方源 registry.npmjs.org', exact: true }) const custom = registry.getByRole('radio', { name: '自定义地址', exact: true }) field = registry.getByRole('textbox', { name: '自定义地址', exact: true }) diff --git a/apps/web/tests/preset-migration.snapshot.ts b/apps/web/tests/preset-migration.snapshot.ts index 302aea3fdc..cf2aac31b8 100644 --- a/apps/web/tests/preset-migration.snapshot.ts +++ b/apps/web/tests/preset-migration.snapshot.ts @@ -76,10 +76,13 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t expect(resolved.agent.session.snapshotEvents() .filter(event => event.type === 'agent-preset/selected') .map(event => event.data.agentPreset)).toEqual(withSelections ? ['ptc', 'standard', 'ptc'] : []) - expect(await scaffold.ctx.subagents.listChildren(id)).toEqual([ - { id: brokenId, createdAt: childFixture[0]?.['createdAt'], mode: 'unknown' }, - { id: childId, createdAt: childFixture[0]?.['createdAt'], mode: 'one-shot', label: 'historical child' }, - ]) + { + using observed = await scaffold.ctx.sessionQuery.observeSession(id) + expect(observed.projections?.values.subagentCatalog).toEqual([ + { id: brokenId, createdAt: childFixture[0]?.['createdAt'], mode: 'unknown' }, + { id: childId, createdAt: childFixture[0]?.['createdAt'], mode: 'one-shot', label: 'historical child' }, + ]) + } const childSuccessor = generationLogPath(scaffold.persistenceRoot, scaffold.workspaceCwd, childId, SESSION_FORMAT_VERSION, 'zstd') await expect(readFile(childSuccessor)).rejects.toMatchObject({ code: 'ENOENT' }) diff --git a/apps/web/tests/reasoning-preview.e2e.ts b/apps/web/tests/reasoning-preview.e2e.ts index 7f7a34c8e7..e03e2d827c 100644 --- a/apps/web/tests/reasoning-preview.e2e.ts +++ b/apps/web/tests/reasoning-preview.e2e.ts @@ -10,12 +10,13 @@ import { import { connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage, writeComposerDraft } from './support.ts' const SUMMARY = `Next paragraph: ${'inspect the loaded context and pending tools '.repeat(8).trim()}` -const DELTAS = ['First paragraph', `\nDetails\n\n\n${SUMMARY}`, '\nMore detail'] +const DELTAS = ['First paragraph', `\nDetails\n\n\n${SUMMARY}`, '\nMore detail', '\n\nExpanded update'] const UI_EXPECTED = fileURLToPath(new URL('./expected/reasoning-preview/running.expected.md', import.meta.url)) /** Computed mask of the animated whale: the ui-chat package asset URL, whose `@` is percent-encoded. */ const WHALE_MASK = /^url\("([^"]*\/plugins\/@deepseek-ai\/dsh-client-ui-chat\/assets\/running-whale%402x-[0-9a-f]{12}\.png)"\)$/ class PausedReasoningAdapter extends LlmAdapter { + constructor(private readonly prefix: string) { super() } override async listModels(provider: string) { return [{ provider, id: 'paused', name: `${provider}/paused` }] } readonly stages = DELTAS.map(text => ({ text, @@ -29,13 +30,14 @@ class PausedReasoningAdapter extends LlmAdapter { override async *stream(options: GenerateOptions): AsyncIterable { yield { type: 'block-start', index: 0, blockType: 'reasoning' } + if (this.prefix !== '') yield { type: 'reasoning-delta', index: 0, text: this.prefix } for (const stage of this.stages) { yield { type: 'reasoning-delta', index: 0, text: stage.text } stage.arrived.resolve(undefined) await stage.proceed.promise options.signal?.throwIfAborted() } - yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: DELTAS.join('') } } + yield { type: 'block-end', index: 0, block: { type: 'reasoning', text: this.prefix + DELTAS.join('') } } yield { type: 'block-start', index: 1, blockType: 'text' } yield { type: 'text-delta', index: 1, text: 'Done' } yield { type: 'block-end', index: 1, block: { type: 'text', text: 'Done' } } @@ -43,9 +45,9 @@ class PausedReasoningAdapter extends LlmAdapter { } } -it('shows completed paragraph first lines across blank lines with a right-edge fade', async () => { +it.each(['plain', 'signature'])('shows completed paragraph first lines with a right-edge fade (%s)', async (format) => { const scaffold = await launchWebScaffold() - const adapter = new PausedReasoningAdapter() + const adapter = new PausedReasoningAdapter(format === 'signature' ? 'metadata.payload\n\n' : '') try { scaffold.ctx.effect(() => scaffold.ctx.llm.registerAdapter(['reasoning-preview-test'], adapter)) await scaffold.ctx.agentDefaultModel.saveSelection({ provider: 'reasoning-preview-test', model: 'paused' }) @@ -61,8 +63,10 @@ it('shows completed paragraph first lines across blank lines with a right-edge f await writeComposerDraft(page, input, 'Show a streamed reasoning preview.') await input.press('Enter') - const [first, second, third] = adapter.stages - if (first === undefined || second === undefined || third === undefined) throw new Error('preview stages are incomplete') + const [first, second, third, fourth] = adapter.stages + if (first === undefined || second === undefined || third === undefined || fourth === undefined) { + throw new Error('preview stages are incomplete') + } await first.arrived.promise const reasoning = page.locator('[data-variant="think"][data-state="running"]') await expandOwningTurnProcess(page, reasoning) @@ -120,6 +124,7 @@ it('shows completed paragraph first lines across blank lines with a right-edge f await page.emulateMedia({ reducedMotion: null, forcedColors: null }) } expect(await reasoning.getAttribute('data-preview')).toBeNull() + expect(await reasoning.textContent()).not.toContain('metadata.payload') first.proceed.resolve(undefined) await second.arrived.promise @@ -138,7 +143,14 @@ it('shows completed paragraph first lines across blank lines with a right-edge f await compareOrRefreshGolden(UI_EXPECTED, await captureStableAria(page, '[data-variant="think"]', scaffold.workspaceCwd), webSnapshotMode()) + await reasoning.getByRole('button').click() + await reasoning.getByText('More detail', { exact: false }).waitFor() + expect(await reasoning.textContent()).not.toContain('metadata.payload') third.proceed.resolve(undefined) + await fourth.arrived.promise + await reasoning.getByText('Expanded update', { exact: true }).waitFor() + expect(await reasoning.textContent()).not.toContain('metadata.payload') + fourth.proceed.resolve(undefined) await settled await page.getByText('Done', { exact: true }).waitFor() await whale.waitFor({ state: 'detached' }) diff --git a/apps/web/tests/scaffold.ts b/apps/web/tests/scaffold.ts index 963c21ce6c..9f7c61f962 100644 --- a/apps/web/tests/scaffold.ts +++ b/apps/web/tests/scaffold.ts @@ -412,8 +412,8 @@ export interface LaunchOptions { * the settings switch does. */ deepSeekWebApi?: { - /** Search and Fetch API base URL; the providers append `/search` or `/fetch`. */ - baseURL: string + /** Search and Fetch API base URL; omitted uses the provider default. The providers append `/search` or `/fetch`. */ + baseURL?: string /** Credential reference resolved by both providers. */ apiKeyEnv: string /** Select `deepseek-search-api` and `deepseek-fetch-api` in place of the shipped selection. */ @@ -699,7 +699,13 @@ export async function launchWebScaffold(options: LaunchOptions = {}): Promise { this.requests.push(options) - yield * textResponse(EVERY_REPLY) + const last = options.messages.findLast(message => message.source?.kind === 'schedule') + yield * textResponse(last?.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) === true + ? EVERY_REPLY : 'Task change noted.') } } @@ -184,6 +186,21 @@ function localAt(epoch: number, timeZone: string): LocalAt { } } +/** One occurrence in the target-based tool's explicit local-time format. */ +function oneOccurrence(at: LocalAt): string { + return `DTSTART;TZID=${at.time_zone}:${at.date.replaceAll('-', '')}T${at.time.replaceAll(':', '')}\nRRULE:FREQ=DAILY;COUNT=1` +} + +/** Historical rules retain their exact dispatch semantics in the Host task domain. */ +function hostTask(record: ScheduleRecord, sessionId: SessionId): ScheduleTask { + const instant = new Date().toISOString() + return { + record, target: { kind: 'session', sessionId }, involvedSessionIds: [sessionId], status: 'active', + createdAt: instant, updatedAt: instant, + deliveryHistory: { records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false }, + } +} + /** Dynamic model seam proving request-local browser context becomes an explicit At selector. */ class BrowserZoneAtAdapter extends LlmAdapter { override async listModels(provider: string) { return [{ provider, id: MODEL, name: `${provider}/${MODEL}` }] } @@ -201,7 +218,7 @@ class BrowserZoneAtAdapter extends LlmAdapter { const target = Math.ceil((Date.now() + 5_000) / 1_000) * 1_000 this.selectedAt = localAt(target, AT_BROWSER_ZONE) this.scheduledAt = new Date(target).toISOString() - const argumentsJson = JSON.stringify({ prompt: AT_PROMPT, title: AT_PROMPT, at: this.selectedAt }) + const argumentsJson = JSON.stringify({ prompt: AT_PROMPT, title: AT_PROMPT, rrule: oneOccurrence(this.selectedAt), target: 'this_session' }) const callId = ToolCallId('schedule-at-browser-zone') yield { type: 'block-start', index: 0, blockType: 'tool-call' } yield { @@ -224,7 +241,10 @@ class BrowserZoneAtAdapter extends LlmAdapter { yield { type: 'finish', reason: { kind: 'tool-calls' } } return } - yield * textResponse(this.requests.length === 3 ? AT_ACK : AT_REPLY) + const last = options.messages.findLast(message => message.source?.kind === 'schedule') + yield * textResponse(this.requests.length === 3 ? AT_ACK + : last?.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) === true + ? AT_REPLY : 'Task change noted.') } } @@ -249,6 +269,7 @@ function requestText(options: GenerateOptions): string { function expectReminderFraming(options: GenerateOptions): void { const reminder = options.messages.find(message => ( message.role === 'user' && message.source?.kind === 'schedule' + && message.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) )) expect(reminder?.role).toBe('user') const text = reminder?.content.find(block => block.type === 'text')?.text @@ -277,15 +298,11 @@ function assistantKey(event: SessionEvent<'assistant/message'>): string { return conversationContextKey('assistant-step', `${String(event.data.turn)}:${String(event.data.step)}`) } -/** Wait until opening a persisted Session publishes its live Agent. */ +/** Restore a persisted Session explicitly when the fixture needs a tool-calling Agent. */ async function liveAgent(scaffold: WebScaffold, sessionId: SessionId): Promise { - const deadline = Date.now() + 30_000 - for (;;) { - const found = scaffold.ctx.agents.get(sessionId) - if (found !== undefined) return found - if (Date.now() >= deadline) throw new Error(`opening session "${sessionId}" published no live Agent`) - await new Promise(resolve => setTimeout(resolve, 100)) - } + const resolved = await scaffold.ctx.sessionController.resolveAgent(sessionId) + if ('error' in resolved) throw new Error(`restoring session "${sessionId}" failed`) + return resolved.agent } describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { @@ -360,7 +377,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { signal: AbortSignal.timeout(10_000), callId: ToolCallId('schedule-after-create'), name: 'schedule_create', - arguments: { prompt: AFTER_PROMPT, title: AFTER_PROMPT, after_seconds: 1 }, + arguments: { prompt: AFTER_PROMPT, title: AFTER_PROMPT, + rrule: oneOccurrence(localAt(Math.ceil((Date.now() + 5_000) / 1_000) * 1_000, 'UTC')), target: 'this_session' }, agent: afterHandle.agent, }) if (afterCreated.isError) { @@ -372,11 +390,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { } expect(createdView.id).toMatch(/^schedule-/) expect(createdView).toMatchObject({ - kind: 'after', prompt: AFTER_PROMPT, - afterSeconds: 1, - state: 'scheduled', - deliveryMode: 'host', + target: { kind: 'session', sessionId: afterHandle.agent.id }, status: 'active', }) afterAssistantReply = await waitForReply(afterHandle, AFTER_REPLY, 15_000) await afterHandle.agent.whenIdle() @@ -415,12 +430,10 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { const domain = scaffold.ctx.storageDomain.get('schedule') if (domain === undefined) throw new Error('Schedule domain was not opened') for (const record of everyRecords) { - await domain.table('tasks').put(record.id, { sessionId: everyHandle.agent.id, record, status: 'active' }) + await domain.table('tasks').put(record.id, hostTask(record, everyHandle.agent.id)) } - const wake = await scaffold.ctx.schedule.create(everyHandle.agent.id, { - prompt: 'Unused future scheduling wake', title: 'Future wake', after_seconds: 86_400, - }) - await scaffold.ctx.schedule.delete({ sessionId: everyHandle.agent.id, id: wake.id }) + const wake = await scaffold.ctx.schedule.create({ prompt: 'Unused future scheduling wake', title: 'Future wake', timing: { kind: 'after', after_seconds: 86_400 }, target: { kind: 'session', sessionId: everyHandle.agent.id } }, everyHandle.agent.id) + await scaffold.ctx.schedule.edit({ action: 'delete', id: wake.id }) await workspace.attachSession(everyHandle.agent.id) const everyListed = await executeToolFixture(scaffold.ctx, { signal: AbortSignal.timeout(10_000), @@ -472,9 +485,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { await atSession.click() const composer = page.locator('[data-composer-input][contenteditable="true"]').last() await composer.fill(AT_USER_PROMPT) - const settled = scaffold.whenTurnSettled(60_000) await page.getByRole('button', { name: 'Send message', exact: true }).click() - expect(await settled).toBe(atHandle.agent.id) + await waitForReply(atHandle, AT_ACK, 60_000) await page.getByText(AT_ACK, { exact: true }).waitFor({ timeout: 15_000 }) atAssistantReply = await waitForReply(atHandle, AT_REPLY, 20_000) await atHandle.agent.whenIdle() @@ -518,18 +530,19 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { ) await expectNoReminderEntry(page) await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).some(task => ( - task.sessionId === afterHandle.agent.id && task.status === 'inactive' && task.lastDelivery !== undefined + task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id && task.status === 'ended' && task.lastDelivery !== undefined ))).toBe(true) - const delivered = (await scaffold.ctx.schedule.catalog()).find(task => task.sessionId === afterHandle.agent.id) + const delivered = (await scaffold.ctx.schedule.catalog()).find(task => task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id) if (delivered?.lastDelivery === undefined) throw new Error('delivered one-shot receipt was not retained') - expect(await scaffold.ctx.schedule.list({ sessionId: afterHandle.agent.id })).toEqual([]) + expect((await scaffold.ctx.schedule.list({ active: true })).items.filter(task => + task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id)).toEqual([]) // Archiving the Session shown in the main pane returns the app to its // workspace-selection view and unmounts the Tasks page with it, so the // linked-Session assertions run with another Session in the main pane. await page.getByRole('treeitem', { name: /Explicit local-time reminder/ }).click() await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') - await manager.getByRole('button', { name: 'Inactive', exact: true }).click() + await manager.getByRole('button', { name: 'Ended', exact: true }).click() await manager.getByRole('list', { name: 'Task catalog' }) .getByRole('button', { name: AFTER_PROMPT, exact: true }).click() const detail = manager.getByRole('complementary', { name: 'Task details' }) @@ -550,7 +563,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { await scaffold.ctx.workspaceRegistry.archiveSession(afterHandle.agent.id) try { await expect.poll(() => linkedSession.isDisabled(), { timeout: 15_000 }).toBe(true) - expect(await detail.getByText('The original session is archived.', { exact: true }).count()).toBe(1) + expect(await detail.getByText('The linked session is archived.', { exact: true }).count()).toBe(1) expect(await detail.getByText('Scheduled After follow-up', { exact: true }).count()).toBe(1) const moreActions = detail.getByRole('button', { name: 'Automation task actions', exact: true }) await moreActions.click() @@ -562,7 +575,9 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { // must not reach the page's own handler and close the whole panel. await expect.poll(() => page.getByRole('menu').count(), { timeout: 5_000 }).toBe(0) await detail.waitFor({ timeout: 5_000 }) - expect((await scaffold.ctx.schedule.catalog()).find(task => task.id === delivered.id)).toEqual(delivered) + expect((await scaffold.ctx.schedule.catalog()).find(task => task.id === delivered.id)).toMatchObject({ + id: delivered.id, status: 'ended', prompt: delivered.prompt, lastDelivery: delivered.lastDelivery, + }) } finally { await scaffold.ctx.workspaceRegistry.unarchiveSession(afterHandle.agent.id) } @@ -577,6 +592,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { const messages = everyHandle.agent.session.snapshotEvents().filter(event => ( event.type === 'user/message' && event.data.source.kind === 'schedule' + && event.data.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) )) expect(messages).toHaveLength(1) const texts = messages.map((event) => { @@ -587,9 +603,11 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { expect(texts.filter(text => text.includes(record.id))).toHaveLength(1) expect(texts.some(text => text.includes(record.prompt))).toBe(true) } - expect(everyAdapter.requests).toHaveLength(1) - for (const request of everyAdapter.requests) expectReminderFraming(request) - const active = await scaffold.ctx.schedule.list({ sessionId: everyHandle.agent.id }) + const request = everyAdapter.requests.find(request => request.messages.some(message => message.content.some(block => + block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')))) + if (request === undefined) throw new Error('the recurring delivery did not reach the model') + expectReminderFraming(request) + const active = (await scaffold.ctx.schedule.list({ active: true })).items expect(active).toHaveLength(2) for (const record of active) { const original = everyRecords.find(candidate => candidate.id === record.id) @@ -611,11 +629,11 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { await captureStableAria(page, selector, scaffold.workspaceCwd), MODE, ) - await page.getByRole('button', { name: '2 reminders', exact: true }).waitFor({ timeout: 15_000 }) - expect(await page.getByRole('list', { name: 'Active reminders' }).count()).toBe(0) + await page.getByRole('button', { name: '2 automation tasks', exact: true }).waitFor({ timeout: 15_000 }) + expect(await page.getByRole('list', { name: 'Enabled automation tasks' }).count()).toBe(0) const original = everyRecords[0] - const first = await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 }) + const first = await scaffold.ctx.schedule.history({ id: original.id, limit: 20 }) if ('code' in first || first.records.length !== 1) throw new Error('expected one actual recurring receipt') await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') @@ -631,17 +649,19 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { if (domain === undefined) throw new Error('Schedule domain was not opened') const latest = first.records[0]! // Make the next occurrence due through the fixture's existing stored-time input. + const stored = hostTask(original, everyHandle.agent.id) + const dueAt = new Date(Date.now() - 1_000).toISOString() await domain.table('tasks').put(original.id, { - sessionId: everyHandle.agent.id, - record: { ...original, scheduledAt: new Date(Date.now() - 1_000).toISOString() }, - status: 'active', - lastDelivery: { scheduledAt: latest.scheduledAt, deliveredAt: latest.deliveredAt, messageId: latest.messageId }, - deliveryHistory: { records: [...first.records].reverse(), earlierRecordsUnavailable: first.earlierRecordsUnavailable }, + ...stored, record: { ...stored.record, scheduledAt: dueAt }, + lastDelivery: { ...latest, targetSessionId: everyHandle.agent.id }, + deliveryHistory: { records: [...first.records].reverse().map(receipt => ({ ...receipt, targetSessionId: everyHandle.agent.id })), + earlierRecordsUnavailable: first.earlierRecordsUnavailable }, }) - const wake = await scaffold.ctx.schedule.create(everyHandle.agent.id, { prompt: 'Future history refresh wake', title: 'History refresh wake', after_seconds: 86_400 }) - await scaffold.ctx.schedule.delete({ sessionId: everyHandle.agent.id, id: wake.id }) - await expect.poll(() => receipts.count(), { timeout: 15_000 }).toBe(2) - const saved = await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 }) + const wake = await scaffold.ctx.schedule.create({ prompt: 'Future history refresh wake', title: 'History refresh wake', timing: { kind: 'after', after_seconds: 86_400 }, target: { kind: 'session', sessionId: everyHandle.agent.id } }, everyHandle.agent.id) + await scaffold.ctx.schedule.edit({ action: 'delete', id: wake.id }) + // A second delivery waits for the Host's one-minute admission interval. + await expect.poll(() => receipts.count(), { timeout: 75_000 }).toBe(2) + const saved = await scaffold.ctx.schedule.history({ id: original.id, limit: 20 }) if ('code' in saved) throw new Error('recurring delivery history was unavailable') expect(saved.records).toHaveLength(2) expect(saved.records[1]).toEqual(latest) @@ -652,28 +672,27 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { } expect(await detail.getByRole('tab', { name: 'Records', exact: true }).getAttribute('aria-selected')).toBe('true') await detail.getByRole('tab', { name: 'Rules', exact: true }).click() - // The interval row states its quantity in the friendly unit the stored - // seconds select: 3600 seconds is one whole hour, so the row shows 1 and - // doubling the interval is two of those hours. - const interval = detail.getByLabel('Repeat every', { exact: true }) + await detail.getByRole('button', { name: /^Repeat / }).click() + await page.getByRole('menuitem', { name: 'Every N hours', exact: true }).click() + const interval = detail.getByLabel('Interval', { exact: true }) expect(await interval.inputValue()).toBe('1') await interval.fill('2') // Run-time rows edit a local draft; the save bar is the only commit path. await detail.getByText('Unsaved changes', { exact: true }).waitFor({ timeout: 15_000 }) await detail.getByRole('button', { name: 'Save changes', exact: true }).click() - await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).find(task => task.id === original.id), { timeout: 15_000 }) - .toMatchObject({ - id: original.id, sessionId: everyHandle.agent.id, prompt: original.prompt, - kind: 'every', everySeconds: EVERY_INTERVAL_SECONDS * 2, status: 'active', - }) - expect(await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 })).toEqual(saved) + await expect.poll(async () => rruleOf((await scaffold.ctx.schedule.catalog()).find(task => task.id === original.id)), + { timeout: 15_000 }) + .toContain('FREQ=HOURLY;INTERVAL=2') + expect(await scaffold.ctx.schedule.history({ id: original.id, limit: 20 })).toEqual({ + ...saved, records: saved.records.map(receipt => ({ ...receipt, targetSessionId: everyHandle.agent.id })), + }) await detail.getByRole('tab', { name: 'Records', exact: true }).click() await expect.poll(() => receipts.count()).toBe(2) // The linked-session row renders on the Rules view only. await detail.getByRole('tab', { name: 'Rules', exact: true }).click() - await detail.getByRole('button', { name: 'Linked session Fixed-rate reminder batch: open original session', exact: true }).click() - await page.getByRole('button', { name: '2 reminders', exact: true }).waitFor({ timeout: 15_000 }) - }, 60_000) + await detail.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click() + await page.getByRole('button', { name: '2 automation tasks', exact: true }).waitFor({ timeout: 15_000 }) + }) it('uses request-local browser context to create an explicit local At reminder', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-at')) @@ -706,7 +725,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { event.type === 'tool/call' && event.data.name === 'schedule_create' )) if (toolCall?.type !== 'tool/call') throw new Error('missing schedule_create tool call') - expect(JSON.parse(toolCall.data.arguments)).toEqual({ prompt: AT_PROMPT, title: AT_PROMPT, at: selectedAt }) + expect(JSON.parse(toolCall.data.arguments)).toEqual({ prompt: AT_PROMPT, title: AT_PROMPT, rrule: oneOccurrence(selectedAt), target: 'this_session' }) const result = atHandle.agent.session.snapshotEvents().find(event => ( event.type === 'tool/result' && event.data.message.toolCallId === toolCall.data.callId )) @@ -714,15 +733,18 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => { expect(result.data.message.isError).not.toBe(true) const resultText = result.data.message.content.find(block => block.type === 'text') if (resultText?.type !== 'text') throw new Error('missing schedule_create response fields') - expect(JSON.parse(resultText.text)).toMatchObject({ kind: 'at', prompt: AT_PROMPT, scheduledAt }) + expect(JSON.parse(resultText.text)).toMatchObject({ prompt: AT_PROMPT, scheduledAt, + target: { kind: 'session', sessionId: atHandle.agent.id } }) const reminders = atHandle.agent.session.snapshotEvents().filter(event => ( event.type === 'user/message' && event.data.source.kind === 'schedule' + && event.data.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) )) expect(reminders).toHaveLength(1) - expect(await scaffold.ctx.schedule.list({ sessionId: atHandle.agent.id })).toEqual([]) - expect(atAdapter.requests).toHaveLength(4) - const reminderRequest = atAdapter.requests[3] + expect((await scaffold.ctx.schedule.list({ active: true })).items.filter(task => + task.target.kind === 'session' && task.target.sessionId === atHandle.agent.id)).toEqual([]) + const reminderRequest = atAdapter.requests.find(request => request.messages.some(message => message.content.some(block => + block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')))) if (reminderRequest === undefined) throw new Error('model did not receive the At reminder') expectReminderFraming(reminderRequest) @@ -768,16 +790,23 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { extraOverlayPath: [await writeEveryStepOverlay(root)], }) await seedSession(scaffold, fixture, CATALOG_SESSION_ID, 'standard') - const records = foldScheduleEvents(fixture.trim().split('\n').slice(1).map(line => JSON.parse(line) as SessionEvent)).active + const events = fixture.trim().split('\n').slice(1).map(line => JSON.parse(line) as SessionEvent) + const records = events.flatMap(event => event.type === 'schedule/change' && event.data.operation === 'create' + ? [event.data.schedule] : []) + expect(records.map(record => record.id)).toEqual(Object.keys(CATALOG_TITLES)) const domain = scaffold.ctx.storageDomain.get('schedule') if (domain === undefined) throw new Error('Schedule domain was not opened') // The fixture holds the bytes its writer produced before titles existed, so // each recorded task is seeded under the name this catalog lane asserts. - const seeded = records.map(record => ({ ...record, title: CATALOG_TITLES[record.id] })) + const seeded = records.map((record) => { + const title = CATALOG_TITLES[record.id] + if (title === undefined) throw new Error(`unnamed catalog fixture task: ${record.id}`) + return { ...record, title } + }) for (const record of seeded) { - await domain.table('tasks').put(record.id, { sessionId: CATALOG_SESSION_ID, record, status: 'active' }) + await domain.table('tasks').put(record.id, hostTask(record, CATALOG_SESSION_ID)) } - expect(await scaffold.ctx.schedule.list({ sessionId: CATALOG_SESSION_ID })).toEqual(seeded) + expect((await scaffold.ctx.schedule.list({ active: true })).items).toMatchObject(seeded) expect(scaffold.ctx.agents.get(CATALOG_SESSION_ID)).toBeUndefined() const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) @@ -816,9 +845,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { it('manages cross-Session tasks from the sidebar without activating their Sessions', async () => { const otherSessionId = SessionId('schedule-manager-other-session') await seedSession(scaffold, await readFile(CATALOG_FIXTURE, 'utf8'), otherSessionId, 'standard') - const other = await scaffold.ctx.schedule.create(otherSessionId, { - prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', at: '2099-08-25T12:08:00.000Z', - }) + const other = await scaffold.ctx.schedule.create({ prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'session', sessionId: otherSessionId } }, otherSessionId) await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') await manager.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor() @@ -831,7 +858,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { // unrestricted state; the repeating task is reached by name instead of a // retired type chip. const statuses = manager.getByRole('group', { name: 'Task status' }) - expect(await statuses.getByRole('button').count()).toBe(3) + expect(await statuses.getByRole('button').count()).toBe(4) await manager.getByRole('button', { name: 'All', exact: true }).click() await expect.poll(() => tasks.getByRole('listitem').count()).toBe(4) expect(await tasks.textContent()).toContain('Check exact cadence') @@ -850,8 +877,8 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await page.setViewportSize({ width: 600, height: 340 }) // The linked Session is a seat in the detail's tab strip, above the rule's // scroll region, so it stays fully visible however far that region scrolls. - const contextRow = details.locator('[class*="detailContext"]') - const linkedSession = contextRow.getByRole('button', { name: 'Linked session: open original session', exact: true }) + const contextRow = details.locator('[class*="hostSessionFooter"]') + const linkedSession = contextRow.getByRole('button', { name: 'Linked session: open linked session', exact: true }) expect(await contextRow.getByRole('button').count()).toBe(1) expect(await linkedSession.textContent()).toContain(otherSessionId) expect(await contextRow.evaluate(element => element.closest('[class*="detailScroll"]') === null)).toBe(true) @@ -887,9 +914,9 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await tasks.getByRole('button', { name: 'Check exact cadence', exact: true }).click() // This Session's catalog row carries no title before the Session is opened, // so its link shows the Session id and is named without one. - await manager.getByRole('button', { name: 'Linked session: open original session', exact: true }).click() + await manager.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click() await liveAgent(scaffold, CATALOG_SESSION_ID) - await page.getByRole('button', { name: '3 reminders', exact: true }).waitFor() + await page.getByRole('button', { name: '3 automation tasks', exact: true }).waitFor() expect(tripwire.pageErrors).toEqual([]) }, 60_000) @@ -935,20 +962,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') await manager.getByRole('button', { name: 'Check exact cadence', exact: true }).click() - await manager.getByRole('button', { name: `Linked session ${CATALOG_TITLE}: open original session`, exact: true }).click() + await manager.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click() await liveAgent(scaffold, CATALOG_SESSION_ID) await page.getByRole('navigation', { name: 'Session hierarchy' }) .getByText(CATALOG_TITLE, { exact: true }).waitFor({ timeout: 15_000 }) - const trigger = page.getByRole('button', { name: '3 reminders' }) + const trigger = page.getByRole('button', { name: '3 automation tasks' }) await trigger.waitFor({ timeout: 15_000 }) await trigger.click() - const catalog = page.getByRole('list', { name: 'Active reminders' }) + const catalog = page.getByRole('list', { name: 'Enabled automation tasks' }) await catalog.waitFor({ timeout: 10_000 }) expect(await catalog.getByRole('listitem').count()).toBe(3) const lightLayout = await page.evaluate(() => { - const triggerElement = document.querySelector('button[aria-label="3 reminders"]') - const catalogElement = document.querySelector('[aria-label="Active reminders"]') + const triggerElement = document.querySelector('button[aria-label="3 automation tasks"]') + const catalogElement = document.querySelector('[aria-label="Enabled automation tasks"]') if (!(triggerElement instanceof HTMLElement) || !(catalogElement instanceof HTMLElement)) { throw new Error('active reminder trigger or catalog is not mounted') } @@ -983,7 +1010,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { // pushing the popover past its own width, and a longer stored name wraps // through the same `overflow-wrap: anywhere` declaration the stylesheet // states for the title. - const longPrompt = longRow.getByRole('button', { name: 'Open reminder details: Join release review' }) + const longPrompt = longRow.getByRole('button', { name: 'Open automation task details: Join release review' }) const promptLayout = await longPrompt.evaluate(element => ({ clientWidth: element.clientWidth, scrollWidth: element.scrollWidth, @@ -1046,7 +1073,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { expect(darkBackground).not.toBe(lightLayout.background) await compareOrRefreshGolden( CATALOG_EXPECTED, - await captureStableAria(page, '[aria-label="Active reminders"]', scaffold.workspaceCwd), + await captureStableAria(page, '[aria-label="Enabled automation tasks"]', scaffold.workspaceCwd), MODE, ) @@ -1069,16 +1096,16 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { expect(metadataText).toMatch(/\d{1,2}:\d{2}/) // The delete glyph is an aria-hidden SVG, so the ARIA golden cannot prove it // still renders; the DOM has to. - const deleteButton = catalog.getByRole('button', { name: /^Delete reminder:/ }).first() + const deleteButton = catalog.getByRole('button', { name: /^Delete automation task:/ }).first() await expect.poll(() => deleteButton.locator('svg').count(), { timeout: 15_000 }).toBe(1) for (let remaining = 3; remaining > 0; remaining--) { - await catalog.getByRole('button', { name: /^Delete reminder:/ }).first().click() - await expect.poll(() => catalog.getByRole('button', { name: /^Delete reminder:/ }).count(), { timeout: 15_000 }) + await catalog.getByRole('button', { name: /^Delete automation task:/ }).first().click() + await expect.poll(() => catalog.getByRole('button', { name: /^Delete automation task:/ }).count(), { timeout: 15_000 }) .toBe(remaining - 1) } await expectNoReminderEntry(page) - expect(await scaffold.ctx.schedule.list({ sessionId: CATALOG_SESSION_ID })).toEqual([]) + expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([]) await page.reload({ waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await expectNoReminderEntry(page) @@ -1100,9 +1127,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { it('shows the pruning footer only for confirmed cleanup after the final saved page', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-retention')) - const record = await scaffold.ctx.schedule.create(CATALOG_SESSION_ID, { - prompt: 'Review retained records', title: 'History retention review', at: '2099-09-01T12:00:00.000Z', - }) + const record = await scaffold.ctx.schedule.create({ prompt: 'Review retained records', title: 'History retention review', timing: { kind: 'at', at: '2099-09-01T12:00:00.000Z' }, target: { kind: 'session', sessionId: CATALOG_SESSION_ID } }, CATALOG_SESSION_ID) try { await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() const manager = page.getByTestId('task-manager-page') @@ -1119,10 +1144,10 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { const domain = scaffold.ctx.storageDomain.get('schedule') if (domain === undefined) throw new Error('Schedule domain was not opened') const instant = new Date().toISOString() - const receipt = { scheduledAt: instant, deliveredAt: instant, messageId: MessageId('retention-legacy') } + const receipt = { scheduledAt: instant, deliveredAt: instant, messageId: MessageId('retention-legacy'), targetSessionId: CATALOG_SESSION_ID } await rulesTab.click() await domain.table('tasks').put(record.id, { - sessionId: CATALOG_SESSION_ID, record, status: 'inactive', lastDelivery: receipt, + ...hostTask(record, CATALOG_SESSION_ID), status: 'ended', lastDelivery: receipt, deliveryHistory: { records: [receipt], earlierRecordsUnavailable: true }, }) await recordsTab.click() @@ -1131,13 +1156,16 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { expect(await notice.count()).toBe(0) await rulesTab.click() let task: ScheduleTask = { - sessionId: CATALOG_SESSION_ID, record, status: 'inactive', - deliveryHistory: { records: [], earlierRecordsUnavailable: false }, + record, + target: { kind: 'session', sessionId: CATALOG_SESSION_ID }, + involvedSessionIds: [CATALOG_SESSION_ID], status: 'ended', + createdAt: instant, updatedAt: instant, + deliveryHistory: { records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false }, } for (let index = 0; index < 23; index++) { const time = new Date(Date.now() - (index === 0 ? 40 * 86_400_000 : (23 - index) * 3_600_000)).toISOString() task = { ...task, ...appendDelivery(task, { - scheduledAt: time, deliveredAt: time, messageId: MessageId(`retention-${index}`), + scheduledAt: time, deliveredAt: time, messageId: MessageId(`retention-${index}`), targetSessionId: CATALOG_SESSION_ID, }, { days: 30, records: 200 }) } } expect(task.deliveryHistory?.records).toHaveLength(22) @@ -1153,7 +1181,8 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await info.click() const bounds = detail.getByText('Each task keeps up to 200 delivery records from the last 30 days.', { exact: true }) await bounds.waitFor() - expect(await detail.locator('footer').innerText()).toMatchInlineSnapshot(` + const retentionFooter = detail.locator('[class*="retentionEnd"]') + expect(await retentionFooter.innerText()).toMatchInlineSnapshot(` "Earlier delivery records have been cleared Each task keeps up to 200 delivery records from the last 30 days. @@ -1163,15 +1192,17 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await info.click() expect(await bounds.count()).toBe(0) const panelBox = await detail.boundingBox() - const footerBox = await detail.locator('footer').boundingBox() + const footerBox = await retentionFooter.boundingBox() + const sessionFooterBox = await detail.locator('[class*="hostSessionFooter"]').boundingBox() expect(panelBox).not.toBeNull() expect(footerBox).not.toBeNull() expect(Math.abs(footerBox!.x - panelBox!.x)).toBeLessThan(2) - expect(Math.abs(footerBox!.y + footerBox!.height - panelBox!.y - panelBox!.height)).toBeLessThan(2) - expect(await detail.locator('footer').evaluate(element => getComputedStyle(element).borderTopWidth)).toBe('0px') + expect(sessionFooterBox).not.toBeNull() + expect(footerBox!.y + footerBox!.height).toBeLessThanOrEqual(sessionFooterBox!.y) + expect(await retentionFooter.evaluate(element => getComputedStyle(element).borderTopWidth)).toBe('0px') expect(tripwire.pageErrors).toEqual([]) } finally { - await scaffold.ctx.schedule.delete({ sessionId: CATALOG_SESSION_ID, id: record.id }) + await scaffold.ctx.schedule.edit({ action: 'delete', id: record.id }) } }, 60_000) @@ -1182,20 +1213,22 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { const clock = new Intl.DateTimeFormat('en-GB-u-nu-latn', { timeZone, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23', }) - const time = clock.format(new Date(Date.now() + 3_600_000)) + const at = localAt(Math.ceil((Date.now() + 3_600_000) / 60_000) * 60_000, timeZone) + const time = at.time + const rrule = `DTSTART;TZID=${timeZone}:${at.date.replaceAll('-', '')}T${time.replaceAll(':', '')}\nRRULE:FREQ=DAILY` const prompt = 'Inspect the daily calendar rule' const result = await executeToolFixture(scaffold.ctx, { signal: AbortSignal.timeout(10_000), callId: ToolCallId('schedule-daily-catalog-create'), - name: 'schedule_create', arguments: { prompt, title: prompt, daily: { time, time_zone: timeZone } }, agent, + name: 'schedule_create', arguments: { prompt, title: prompt, rrule, target: 'this_session' }, agent, }) const created = (await scaffold.ctx.schedule.catalog()).find(task => ( - task.sessionId === CATALOG_SESSION_ID && task.prompt === prompt + task.target.kind === 'session' && task.target.sessionId === CATALOG_SESSION_ID && task.prompt === prompt )) if (created === undefined) throw new Error('daily tool did not create a stored task') try { expect(result.isError).toBe(false) - expect(result.value).toMatchObject({ kind: 'daily', time: `${time}.000`, timeZone }) - expect(created).toMatchObject({ kind: 'daily', time: `${time}.000`, timeZone, status: 'active' }) + expect(result.value).toMatchObject({ rrule, target: { kind: 'session', sessionId: CATALOG_SESSION_ID } }) + expect(created).toMatchObject({ rrule, status: 'active' }) expect(clock.format(new Date(created.scheduledAt))).toBe(time) await page.clock.setFixedTime(new Date()) await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() @@ -1217,7 +1250,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { expect(await row.textContent()).toContain(frequency) await row.click() const detail = manager.getByRole('complementary', { name: 'Task details' }) - expect(await detail.getByText(frequency, { exact: true }).count()).toBe(1) + expect(await detail.getByRole('button', { name: /^Repeat / }).textContent()).toContain('Every day') expect(await detail.getByText('Once', { exact: true }).count()).toBe(0) const runTime = detail.getByRole('region', { name: 'Run time', exact: true }) const timeField = runTime.getByRole('button', { name: 'Time', exact: true }) @@ -1227,41 +1260,73 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { // Zone rows lead with the current offset and the localized zone name, so // the browser's own zone is the row marked as the system one. await page.getByRole('menuitem', { name: /China Standard Time \(system\)$/ }).click() - // The Time row opens three clock columns; a pick stages the clock itself, - // and the stored rule keeps the millisecond precision the picker writes. + // Daily guided rules keep minute precision; a pick stages the clock. await timeField.click() expect(await timeField.getAttribute('aria-expanded')).toBe('true') await page.getByRole('listbox', { name: 'Hour', exact: true }).getByRole('option', { name: '12', exact: true }).click() await page.getByRole('listbox', { name: 'Minute', exact: true }).getByRole('option', { name: '34', exact: true }).click() - await page.getByRole('listbox', { name: 'Second', exact: true }).getByRole('option', { name: '56', exact: true }).click() await page.keyboard.press('Escape') - expect(await timeField.textContent()).toBe('12:34:56') + expect(await timeField.textContent()).toBe('12:34:00') await expect.poll(() => detail.getByText('Unsaved changes', { exact: true }).count(), { timeout: 15_000 }).toBe(1) // The staged draft reaches the Host only through the save bar's Save action. await detail.getByRole('button', { name: 'Save changes', exact: true }).click() - await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id), { timeout: 15_000 }) - .toMatchObject({ time: '12:34:56.000', timeZone: 'Asia/Shanghai' }) + await expect.poll(async () => rruleOf((await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id)), + { timeout: 15_000 }) + .toContain('DTSTART;TZID=Asia/Shanghai:') const saved = (await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id) expect(saved).toMatchObject({ - id: created.id, sessionId: CATALOG_SESSION_ID, prompt, status: 'active', - kind: 'daily', time: '12:34:56.000', timeZone: 'Asia/Shanghai', + id: created.id, target: { kind: 'session', sessionId: CATALOG_SESSION_ID }, prompt, status: 'active', }) + expect(rruleOf(saved)).toContain('BYHOUR=12;BYMINUTE=34') // A stored zone equal to the browser zone is omitted from the frequency line. - await expect.poll(() => detail.getByText('Daily at 12:34:56', { exact: true }).count(), { timeout: 15_000 }).toBe(1) - expect(await scaffold.ctx.schedule.history({ sessionId: CATALOG_SESSION_ID, id: created.id, limit: 20 })) + await expect.poll(() => row.textContent(), { timeout: 15_000 }).toContain('Daily at 12:34') + expect(await scaffold.ctx.schedule.history({ id: created.id, limit: 20 })) .toEqual({ id: created.id, records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false, retention: { days: 30, records: 200 } }) // The created rule stays active, so the ended-status filter hides every // row; the retired type chips no longer exist. - await manager.getByRole('button', { name: 'Inactive', exact: true }).click() + await manager.getByRole('button', { name: 'Ended', exact: true }).click() await expect.poll(() => tasks.getByRole('listitem').count()).toBe(0) expect(tripwire.pageErrors).toEqual([]) } finally { - await scaffold.ctx.schedule.delete({ sessionId: CATALOG_SESSION_ID, id: created.id }) + await scaffold.ctx.schedule.edit({ id: created.id, action: 'delete' }) await page.clock.setFixedTime(new Date(CATALOG_NOW)) } }, 60_000) + it('restores the latest linked Session after reviewing a concurrent destination change', async () => { + const before = SessionId('schedule-destination-before') + const after = SessionId('schedule-destination-after') + const fixture = await readFile(CATALOG_FIXTURE, 'utf8') + for (const id of [before, after]) await seedSession(scaffold, fixture, id, 'standard') + const created = await scaffold.ctx.schedule.create({ title: 'Destination recovery', prompt: 'Review the destination', + timing: { kind: 'at', at: '2099-09-01T12:00:00.000Z' }, target: { kind: 'session', sessionId: before } }) + try { + await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() + const manager = page.getByTestId('task-manager-page') + await manager.getByRole('searchbox', { name: 'Search tasks' }).fill('') + await manager.getByRole('button', { name: 'All', exact: true }).click() + await manager.getByRole('button', { name: 'Destination recovery', exact: true }).click() + const detail = manager.getByRole('complementary') + await detail.getByRole('textbox', { name: 'Automation task name', exact: true }).fill('Recovered destination') + await detail.getByRole('button', { name: /^Run in / }).click() + await page.getByRole('menuitem', { name: /^Create a session and reuse it/ }).click() + const remote = await scaffold.ctx.schedule.edit({ id: created.id, action: 'update', expectedUpdatedAt: created.updatedAt ?? null, + patch: { target: { kind: 'session', sessionId: after } } }) + expect(remote).toMatchObject({ target: { kind: 'session', sessionId: after } }) + await detail.getByRole('button', { name: 'Review with my edits', exact: true }).click() + await detail.getByRole('button', { name: /^Run in / }).click() + await page.getByRole('menuitem', { name: 'Current linked session', exact: true }).click() + await detail.getByRole('button', { name: 'Save changes', exact: true }).click() + await detail.getByRole('heading', { name: 'Recovered destination', exact: true }).waitFor() + expect(await scaffold.ctx.schedule.view({ id: created.id })) + .toMatchObject({ title: 'Recovered destination', target: { kind: 'session', sessionId: after } }) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await scaffold.ctx.schedule.edit({ id: created.id, action: 'delete' }) + } + }) + it('removes every ended task from the page and keeps the active ones', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-clear-ended')) const endedSession = SessionId('schedule-manager-ended-clear') @@ -1279,17 +1344,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { scheduledAt: record.scheduledAt, deliveredAt: new Date(Date.parse(record.scheduledAt) + 1_000).toISOString(), messageId: MessageId(`${id}-delivery`), + targetSessionId: endedSession, } await domain.table('tasks').put(record.id, { - sessionId: endedSession, record, status: 'inactive', lastDelivery: receipt, - deliveryHistory: { records: [receipt], earlierRecordsUnavailable: false }, + target: { kind: 'session', sessionId: endedSession }, involvedSessionIds: [endedSession], + record, status: 'ended', lastDelivery: receipt, + deliveryHistory: { records: [receipt], earlierRecordsUnavailable: false, earlierRecordsPruned: false }, }) } // The running task is what the cleanup must leave alone. Creating it also // announces a committed Host change, so the open page reads the rows seeded // above without waiting for its own first catalog read. - const kept = await scaffold.ctx.schedule.create(endedSession, { - prompt: 'Keep this running task', title: 'Keep this running task', at: '2099-08-25T12:08:00.000Z', + const kept = await scaffold.ctx.schedule.create({ + prompt: 'Keep this running task', title: 'Keep this running task', + timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, }) try { await page.getByRole('button', { name: 'Automation tasks', exact: true }).click() @@ -1304,22 +1372,22 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { // The confirmation states the Host-side target and removes nothing until it // is confirmed. await more.click() - await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click() - const confirmation = page.getByRole('dialog', { name: 'Clear inactive tasks (2)?' }) + await page.getByRole('menuitem', { name: 'Clear all ended tasks', exact: true }).click() + const confirmation = page.getByRole('dialog', { name: 'Clear ended tasks (2)?' }) await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click() - expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toHaveLength(2) + expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended')).toHaveLength(2) await more.click() - await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click() + await page.getByRole('menuitem', { name: 'Clear all ended tasks', exact: true }).click() await confirmation.getByRole('button', { name: 'Clear tasks', exact: true }).click() await expect.poll( - async () => (await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive'), + async () => (await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended'), { timeout: 15_000 }, ).toEqual([]) const remaining = await scaffold.ctx.schedule.catalog() expect(remaining.some(task => endedIds.includes(task.id))).toBe(false) expect(remaining.map(task => task.title)).toContain('Keep this running task') - await page.getByText('Cleared 2 inactive tasks.', { exact: true }).waitFor({ timeout: 15_000 }) + await page.getByText('Cleared 2 ended tasks.', { exact: true }).waitFor({ timeout: 15_000 }) // The trigger left with the rows it removed, so the page heading owns the // focus after the confirmation closes; this confirms the heading fallback // in a real browser. @@ -1332,15 +1400,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await manager.getByRole('button', { name: 'All', exact: true }).click() await expect.poll(() => manager.getByRole('list', { name: 'Task catalog' }) .getByRole('button', { name: kept.title, exact: true }).count(), { timeout: 15_000 }).toBe(1) - expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toEqual([]) + expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended')).toEqual([]) expect(tripwire.pageErrors).toEqual([]) } finally { // The shared page and Host outlive a failed assertion: remove every row // this scenario introduced so the next one starts from the same state. A // teardown rejection must not mask the assertion that failed first. await Promise.allSettled( - [kept.id, ...endedIds].map(id => scaffold.ctx.schedule.delete({ sessionId: endedSession, id })), + [kept.id, ...endedIds].map(id => scaffold.ctx.schedule.edit({ id, action: 'delete' })), ) } }, 60_000) }) + +/** Read a known RRULE task from the shared catalog after an explicit rule replacement. */ +function rruleOf(task: ScheduleRecord | undefined): string | undefined { + return task?.kind === 'rrule' ? task.rrule : undefined +} diff --git a/apps/web/tests/schedule-manual.e2e.ts b/apps/web/tests/schedule-manual.e2e.ts new file mode 100644 index 0000000000..60ca701a4d --- /dev/null +++ b/apps/web/tests/schedule-manual.e2e.ts @@ -0,0 +1,194 @@ +/** Manual task creation and editing through the shipped Web composition. */ +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { launchWebScaffold, watchConsole } from './scaffold.ts' + +it('creates from a paused empty state, selects the task, and saves an inline edit without starting an Agent', async () => { + // First use registers the default Workspace, which a new task's directory starts with. + const scaffold = await launchWebScaffold({ firstUse: true }) + let browser: Awaited> | undefined + try { + browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'zh') }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('button', { name: '自动化任务', exact: true }).click() + const manager = page.getByTestId('task-manager-page') + const createStyles = await manager.getByRole('group', { name: '创建', exact: true }).getByRole('button').evaluateAll(buttons => buttons.map((button) => { + const style = getComputedStyle(button) + return { height: style.height, topLeft: style.borderTopLeftRadius, bottomLeft: style.borderBottomLeftRadius, + topRight: style.borderTopRightRadius, bottomRight: style.borderBottomRightRadius } + })) + expect(createStyles).toEqual([ + { height: '32px', topLeft: '16px', bottomLeft: '16px', topRight: '0px', bottomRight: '0px' }, + { height: '32px', topLeft: '0px', bottomLeft: '0px', topRight: '16px', bottomRight: '16px' }, + ]) + await manager.getByRole('button', { name: '已暂停', exact: true }).click() + await manager.getByRole('heading', { name: '没有已暂停的自动化任务', exact: true }).waitFor() + await manager.getByRole('button', { name: '选择创建方式', exact: true }).click() + await page.getByRole('menuitem', { name: '手动创建', exact: true }).waitFor() + await page.keyboard.press('Escape') + await manager.getByRole('button', { name: '新建自动化任务', exact: true }).click() + const dialog = manager.getByRole('complementary', { name: '手动创建', exact: true }) + await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('AI 新闻简报') + expect(await dialog.getByRole('status').count()).toBe(0) + expect(await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).getAttribute('aria-required')).toBe('true') + await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接。') + await dialog.getByRole('button', { name: /^重复 / }).click() + await page.getByRole('menuitem', { name: '周一至周五', exact: true }).click() + await dialog.getByRole('button', { name: '时间', exact: true }).click() + await page.getByRole('listbox', { name: '时', exact: true }).getByRole('option', { name: '09', exact: true }).click() + await page.getByRole('listbox', { name: '分', exact: true }).getByRole('option', { name: '00', exact: true }).click() + await page.getByRole('listbox', { name: '秒', exact: true }).getByRole('option', { name: '00', exact: true }).click() + await page.keyboard.press('Escape') + await dialog.getByRole('button', { name: /^执行位置 / }).click() + await page.getByRole('menuitem', { name: '新建会话并复用 首次运行时创建,之后沿用这个会话', exact: true }).waitFor() + expect(await page.getByRole('menuitem').count()).toBe(2) + const workspace = dialog.getByRole('button', { name: /^关联工作区 / }) + await expect.poll(() => workspace.textContent()).toContain('默认工作区') + await page.keyboard.press('Escape') + // The workspace menu states each directory, so the default workspace names its folder. + const defaultPath = scaffold.ctx.workspaceRegistry.list()[0]?.path + if (defaultPath === undefined) throw new Error('first use did not register the default workspace') + await workspace.click() + await page.getByRole('menuitem').getByTitle(defaultPath, { exact: true }).waitFor() + await page.keyboard.press('Escape') + expect(await dialog.count()).toBe(1) + await dialog.getByRole('button', { name: '创建', exact: true }).click() + const detail = manager.getByRole('complementary', { name: '任务详情', exact: true }) + await detail.getByRole('heading', { name: 'AI 新闻简报', exact: true }).waitFor() + expect(await manager.getByRole('button', { name: '全部', exact: true }).getAttribute('aria-pressed')).toBe('true') + expect(await manager.getByRole('list', { name: '任务列表', exact: true }).getByRole('button', { name: 'AI 新闻简报', exact: true }).count()).toBe(1) + await detail.getByText('待创建', { exact: true }).waitFor() + const task = (await scaffold.ctx.schedule.catalog()).find(task => task.title === 'AI 新闻简报') + if (task === undefined || task.target.kind !== 'new_once') throw new Error('manual task was not created with the reusable target') + expect(task.target.create.cwd).toBe(defaultPath) + expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。') + expect(await detail.getByRole('button', { name: '暂停任务', exact: true }).isDisabled()).toBe(true) + await manager.getByRole('button', { name: '关闭详情', exact: true }).click() + await manager.getByRole('list', { name: '任务列表', exact: true }).getByRole('button', { name: task.title, exact: true }).click() + expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()) + .toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。') + await detail.getByRole('button', { name: '保存修改', exact: true }).click() + await expect.poll(() => detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()) + .toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。') + const saved = await scaffold.ctx.schedule.view({ id: task.id }) + if ('code' in saved) throw new Error('edited task was not retained') + expect(saved.prompt).toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。') + await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('本地简报草稿') + const remote = await scaffold.ctx.schedule.edit({ id: task.id, action: 'update', + expectedUpdatedAt: saved.updatedAt ?? null, patch: { prompt: '来自其他窗口的新指令' } }) + expect(remote).toMatchObject({ prompt: '来自其他窗口的新指令' }) + const recovery = detail.getByRole('button', { name: '保留修改并复核', exact: true }) + await recovery.waitFor() + const notice = detail.getByRole('alert').locator('..') + const palettes = [] + for (const dark of [false, true]) { + await page.evaluate(dark => document.body.toggleAttribute('data-ds-dark-theme', dark), dark) + const [box, field, message, action] = await Promise.all([ + notice.boundingBox(), detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).locator('..').boundingBox(), + detail.getByRole('alert').boundingBox(), recovery.boundingBox(), + ]) + expect(box).not.toBeNull() + expect(field).not.toBeNull() + expect(message).not.toBeNull() + expect(action).not.toBeNull() + expect(Math.abs(box!.x - field!.x)).toBeLessThanOrEqual(1) + expect(Math.abs(box!.x + box!.width - field!.x - field!.width)).toBeLessThanOrEqual(1) + expect(action!.y).toBeLessThan(message!.y + message!.height) + expect(action!.y + action!.height).toBeGreaterThan(message!.y) + expect(box!.y + box!.height).toBeLessThan(field!.y) + palettes.push(await notice.evaluate((element) => { + const style = getComputedStyle(element) + return { color: style.color, background: style.backgroundColor } + })) + } + expect(palettes[0]).not.toEqual(palettes[1]) + await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') }) + expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe(saved.prompt) + await detail.getByRole('button', { name: '保留修改并复核', exact: true }).click() + expect(await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).inputValue()).toBe('本地简报草稿') + expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe('来自其他窗口的新指令') + expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: task.title }) + await detail.getByRole('button', { name: '保存修改', exact: true }).click() + await detail.getByRole('heading', { name: '本地简报草稿', exact: true }).waitFor() + expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: '本地简报草稿', prompt: '来自其他窗口的新指令' }) + expect(await detail.evaluate(element => element === document.activeElement)).toBe(true) + await manager.getByRole('button', { name: '选择创建方式', exact: true }).click() + await page.getByRole('menuitem', { name: '手动创建', exact: true }).click() + await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('检查最新进展') + await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('汇总最近的更新') + await dialog.getByRole('button', { name: /^重复 / }).click() + await page.getByRole('menuitem', { name: '每 N 分钟', exact: true }).click() + await dialog.getByRole('spinbutton', { name: '重复间隔', exact: true }).fill('5') + await dialog.getByRole('button', { name: /^执行位置 / }).click() + await page.getByRole('menuitem', { name: '每次新建会话 每次运行都创建独立会话', exact: true }).click() + await dialog.getByText('运行间隔至少 1分钟', { exact: true }).waitFor() + const beforeCreate = Date.now() + await dialog.getByRole('button', { name: '创建', exact: true }).click() + await detail.getByRole('heading', { name: '检查最新进展', exact: true }).waitFor() + const intervalTask = (await scaffold.ctx.schedule.catalog()).find(item => item.title === '检查最新进展') + if (intervalTask === undefined) throw new Error('interval task was not created') + expect(intervalTask.target.kind).toBe('new') + expect(Date.parse(intervalTask.scheduledAt) - beforeCreate).toBeGreaterThan(240_000) + expect(Date.parse(intervalTask.scheduledAt) - beforeCreate).toBeLessThanOrEqual(300_000) + await detail.getByRole('button', { name: '暂停任务', exact: true }).click() + await detail.getByRole('button', { name: '恢复任务', exact: true }).waitFor() + expect(await detail.getByText('待创建', { exact: true }).count()).toBe(0) + expect(await detail.getByText('最近运行会话', { exact: true }).count()).toBe(0) + expect(await detail.getByText('运行间隔至少', { exact: false }).count()).toBe(1) + expect(tripwire.pageErrors).toEqual([]) + expect(scaffold.ctx.agents.get(task.target.sessionId)).toBeUndefined() + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) + +it('creates and edits Custom Cron through the built UI while retaining its explicit zone and record kind', async () => { + const scaffold = await launchWebScaffold({ firstUse: true }) + let browser: Awaited> | undefined + try { + browser = await chromium.launch() + const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }) + await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'zh') }) + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('button', { name: '自动化任务', exact: true }).click() + const manager = page.getByTestId('task-manager-page') + await manager.getByRole('button', { name: '选择创建方式', exact: true }).click() + await page.getByRole('menuitem', { name: '手动创建', exact: true }).click() + const dialog = manager.getByRole('complementary', { name: '手动创建', exact: true }) + await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('Cron deployment check') + await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('Check the deployment status.') + await dialog.getByRole('button', { name: /^重复 / }).click() + await page.getByRole('menuitem', { name: '自定义', exact: true }).click() + await dialog.getByRole('textbox', { name: '自定义', exact: true }).fill('0 9 * * 1-5') + await dialog.getByRole('button', { name: /^时区 / }).waitFor() + await dialog.getByRole('button', { name: '创建', exact: true }).click() + const detail = manager.getByRole('complementary', { name: '任务详情', exact: true }) + await detail.getByRole('heading', { name: 'Cron deployment check', exact: true }).waitFor() + const created = (await scaffold.ctx.schedule.catalog()).find(task => task.title === 'Cron deployment check') + if (created === undefined) throw new Error('Custom Cron creation did not store a task') + expect(created).toMatchObject({ kind: 'cron', expression: '0 9 * * 1-5', timeZone: 'Asia/Shanghai' }) + expect(created).not.toHaveProperty('rrule') + + await detail.getByRole('textbox', { name: '自定义', exact: true }).fill(' ') + expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + await detail.getByRole('status').getByText('请检查必填项和运行规则', { exact: true }).waitFor() + expect(await scaffold.ctx.schedule.view({ id: created.id })).toEqual(created) + await detail.getByRole('textbox', { name: '自定义', exact: true }).fill('0 10 * * 1-5') + await detail.getByRole('button', { name: /^时区 / }).waitFor() + await detail.getByRole('button', { name: '保存修改', exact: true }).click() + await expect.poll(() => detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + const edited = await scaffold.ctx.schedule.view({ id: created.id }) + expect(edited).toMatchObject({ id: created.id, kind: 'cron', expression: '0 10 * * 1-5', timeZone: 'Asia/Shanghai' }) + expect(edited).not.toHaveProperty('rrule') + expect(tripwire.pageErrors).toEqual([]) + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}) diff --git a/apps/web/tests/schedule-phone.e2e.ts b/apps/web/tests/schedule-phone.e2e.ts index e82104196a..6fdd275553 100644 --- a/apps/web/tests/schedule-phone.e2e.ts +++ b/apps/web/tests/schedule-phone.e2e.ts @@ -4,12 +4,10 @@ import type { Browser, Locator, Page } from 'playwright' import { chromium } from 'playwright' import { expect, it } from 'vitest' -import { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-schedule' import { launchWebScaffold, watchConsole } from './scaffold.ts' import { revealNavigationDrawer } from './support.ts' -const PHONE_TASK_SESSION = SessionId('schedule-phone-web-e2e') const PHONE_TASK_TITLE = 'Review overdue deployment' const PHONE_PAGE_WIDTH = 390 @@ -48,19 +46,40 @@ async function viewFacts(page: Page): Promise { width: window.innerWidth, documentWidth: document.documentElement.scrollWidth, smallestField: steps.length === 0 ? -1 : Math.min(...steps), - name: step('[class*="_editName"]'), + name: step('[class*="_editorField"] input'), search: step('[class*="_searchField"] input'), instruction: step('[class*="_instruction"]'), } }) } +/** Header, form, notices, and footer share the pane's visible content edges. */ +async function expectEditorAlignment(title: Locator): Promise { + await expect.poll(() => title.evaluate((field) => { + const pane = field.closest('aside')! + const bounds = pane.getBoundingClientRect() + const name = field.parentElement!.getBoundingClientRect() + const action = pane.querySelector('footer:last-of-type > button:last-of-type')!.getBoundingClientRect() + const content = Array.from(pane.querySelectorAll('h2, textarea, [class*="_ruleRows"], [class*="_saveNotice"], [class*="_detailNotice"], [class*="_saveFailure"]')) + .filter(node => node.getClientRects().length > 0) + const offsets = { + gutters: Math.abs(name.left - bounds.left - bounds.right + name.right), + action: Math.abs(action.right - name.right), + left: Math.max(...content.map(node => Math.abs(node.getBoundingClientRect().left - name.left))), + right: Math.max(...Array.from(pane.querySelectorAll('textarea, [class*="_ruleRows"]')) + .map(node => Math.abs(node.getBoundingClientRect().right - name.right))), + } + return Object.fromEntries(Object.entries(offsets).filter(([, offset]) => offset > 1)) + })).toEqual({}) +} + it('keeps the automation page on screen with its text fields at the touch step', async () => { const scaffold = await launchWebScaffold() const url = scaffold.authenticatedUrl try { - await scaffold.ctx.schedule.create(PHONE_TASK_SESSION, { - prompt: 'Check the deployment log', title: PHONE_TASK_TITLE, at: '2099-08-25T12:08:00.000Z', + await scaffold.ctx.schedule.create({ + prompt: 'Check the deployment log', title: PHONE_TASK_TITLE, + timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'new_once' }, }) const browser: Browser = await chromium.launch() try { @@ -80,18 +99,77 @@ it('keeps the automation page on screen with its text fields at the touch step', search: '16px', instruction: 'absent', }) - // The detail keeps the floor too, and the name control keeps the 20px step - // the floor must not flatten. + // The editor keeps the touch floor for its name and instruction fields. await phonePanel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click() await phonePanel.locator('[class*="_detailScroll"]').waitFor({ timeout: 10_000 }) await expect.poll(() => viewFacts(phonePage)).toEqual({ width: PHONE_PAGE_WIDTH, documentWidth: PHONE_PAGE_WIDTH, smallestField: 16, - name: '20px', + name: '16px', search: '16px', instruction: '16px', }) + const detail = phonePanel.getByRole('complementary', { name: '任务详情', exact: true }) + await expectEditorAlignment(detail.getByRole('textbox', { name: '自动化任务名称', exact: true })) + await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('未保存的手机草稿') + const task = (await scaffold.ctx.schedule.catalog()).find(item => item.title === PHONE_TASK_TITLE) + if (task === undefined) throw new Error('phone task was not retained') + await scaffold.ctx.schedule.edit({ id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt ?? null, + patch: { prompt: '其他窗口的最新内容' } }) + const recovery = detail.getByRole('button', { name: '保留修改并复核', exact: true }) + await recovery.waitFor() + await recovery.scrollIntoViewIfNeeded() + const recoveryBox = await recovery.boundingBox() + expect(recoveryBox).not.toBeNull() + expect(recoveryBox!.x).toBeGreaterThanOrEqual(0) + expect(recoveryBox!.x + recoveryBox!.width).toBeLessThanOrEqual(PHONE_PAGE_WIDTH) + expect(recoveryBox!.y).toBeGreaterThanOrEqual(0) + expect(recoveryBox!.y + recoveryBox!.height).toBeLessThanOrEqual(844) + const [noticeBox, messageBox, nameBox] = await Promise.all([ + detail.getByRole('alert').locator('..').boundingBox(), detail.getByRole('alert').boundingBox(), + detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).locator('..').boundingBox(), + ]) + expect(noticeBox).not.toBeNull() + expect(messageBox).not.toBeNull() + expect(nameBox).not.toBeNull() + expect(Math.abs(noticeBox!.x - nameBox!.x)).toBeLessThanOrEqual(1) + expect(Math.abs(noticeBox!.x + noticeBox!.width - nameBox!.x - nameBox!.width)).toBeLessThanOrEqual(1) + expect(recoveryBox!.y).toBeGreaterThanOrEqual(messageBox!.y + messageBox!.height) + expect(recoveryBox!.x + recoveryBox!.width).toBeLessThanOrEqual(noticeBox!.x + noticeBox!.width) + expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true) + await recovery.click() + expect(await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).inputValue()).toBe('未保存的手机草稿') + expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe('其他窗口的最新内容') + expect((await viewFacts(phonePage)).documentWidth).toBe(PHONE_PAGE_WIDTH) + expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: PHONE_TASK_TITLE }) + await detail.getByRole('button', { name: '放弃', exact: true }).click() + await phonePanel.getByRole('button', { name: '关闭详情', exact: true }).click() + await phonePanel.getByRole('button', { name: '选择创建方式', exact: true }).click() + await phonePage.getByRole('menuitem', { name: '手动创建', exact: true }).click() + const creation = phonePanel.getByRole('complementary', { name: '手动创建', exact: true }) + await creation.waitFor() + await expectEditorAlignment(creation.getByRole('textbox', { name: '自动化任务名称', exact: true })) + await expect.poll(() => viewFacts(phonePage)).toEqual({ + width: PHONE_PAGE_WIDTH, + documentWidth: PHONE_PAGE_WIDTH, + smallestField: 16, + name: '16px', + search: '16px', + instruction: '16px', + }) + for (const name of ['放弃', '创建']) { + const button = creation.getByRole('button', { name, exact: true }) + await button.scrollIntoViewIfNeeded() + const box = await button.boundingBox() + expect(box).not.toBeNull() + expect(box!.x).toBeGreaterThanOrEqual(0) + expect(box!.x + box!.width).toBeLessThanOrEqual(PHONE_PAGE_WIDTH) + expect(box!.y).toBeGreaterThanOrEqual(0) + expect(box!.y + box!.height).toBeLessThanOrEqual(844) + } + await creation.getByRole('button', { name: '放弃', exact: true }).click() + expect(await phonePanel.getByRole('complementary').count()).toBe(0) await phone.close() // A fine pointer keeps the compact steps: the floor is pointer-scoped. @@ -113,7 +191,7 @@ it('keeps the automation page on screen with its text fields at the touch step', width: 1024, documentWidth: 1024, smallestField: 14, - name: '20px', + name: '14px', search: '14px', instruction: '14px', }) @@ -130,3 +208,83 @@ it('keeps the automation page on screen with its text fields at the touch step', await scaffold.close() } }, 180_000) + +it.each([ + { locale: 'en-US', tasks: 'Automation tasks', sidebar: 'Collapse sidebar', openSidebar: 'Open sidebar', close: 'Close details', + methods: 'Choose a creation method', manual: 'Create manually', title: 'Automation task name', discard: 'Discard', + instruction: 'Automation task instruction', create: 'Create', + repeat: /^Repeat /, frequencies: ['Every month', 'Weekly', 'Once'] }, + { locale: 'zh-CN', tasks: '自动化任务', sidebar: '收起侧边栏', openSidebar: '打开侧边栏', close: '关闭详情', + methods: '选择创建方式', manual: '手动创建', title: '自动化任务名称', discard: '放弃', + instruction: '自动化任务内容', create: '创建', + repeat: /^重复 /, frequencies: ['每月', '每周', '仅一次'] }, + { locale: 'fr-FR', tasks: "Tâches d'automatisation", sidebar: 'Réduire la barre latérale', openSidebar: 'Ouvrir la barre latérale', close: 'Fermer les détails', + methods: 'Choisir le mode de création', manual: 'Créer manuellement', title: "Nom de la tâche d'automatisation", discard: 'Abandonner', + instruction: "Instruction de tâche d'automatisation", create: 'Créer', + repeat: /^Répéter /, frequencies: ['Tous les mois', 'Hebdomadaire', 'Une fois'] }, +] as const)('keeps both editor modes inside a narrow pane with the sidebar open ($locale)', async (copy) => { + const scaffold = await launchWebScaffold() + let browser: Browser | undefined + try { + browser = await chromium.launch() + await scaffold.ctx.schedule.create({ + title: PHONE_TASK_TITLE, prompt: 'Check the deployment log', + timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'new_once' }, + }) + const context = await browser.newContext({ viewport: { width: 1100, height: 844 }, locale: copy.locale, timezoneId: 'Asia/Shanghai' }) + const page = await context.newPage() + const consoleWatch = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.getByRole('button', { name: copy.sidebar, exact: true }).waitFor() + await page.getByRole('button', { name: copy.tasks, exact: true }).click() + const panel = page.getByTestId('task-manager-page') + await panel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click() + await page.evaluate(() => document.fonts.ready) + for (const mode of ['edit', 'create']) { + if (mode === 'create') { + await panel.getByRole('button', { name: copy.close, exact: true }).click() + await panel.getByRole('button', { name: copy.methods, exact: true }).click() + await page.getByRole('menuitem', { name: copy.manual, exact: true }).click() + } + const editor = panel.getByRole('complementary') + const title = editor.getByRole('textbox', { name: copy.title, exact: true }) + if (mode === 'create') { + for (const name of [copy.title, copy.instruction]) { + const field = editor.getByRole('textbox', { name, exact: true }) + expect(await field.getAttribute('required')).toBeNull() + expect(await field.getAttribute('aria-required')).toBe('true') + expect(await field.evaluate(node => (node as HTMLInputElement | HTMLTextAreaElement).validationMessage)).toBe('') + } + expect(await editor.getByRole('button', { name: copy.create, exact: true }).isDisabled()).toBe(true) + } + await title.fill('Retained draft through resizing') + await editor.getByRole('button', { name: copy.discard, exact: true }).waitFor() + for (const width of [1280, 1100, 1024, 900, 800]) { + await title.focus() + await page.setViewportSize({ width, height: 844 }) + expect(await title.evaluate(node => document.activeElement === node)).toBe(true) + // Entering the shell's narrow range publishes the reopen action after its resize observer runs. + if (width === 900) { await page.getByRole('button', { name: copy.openSidebar, exact: true }).click(); await title.focus() } + await page.getByRole('button', { name: copy.sidebar, exact: true }).waitFor() + expect(await panel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).isVisible()).toBe(true) + for (const frequency of copy.frequencies) { + await editor.getByRole('button', { name: copy.repeat }).click() + await page.getByRole('menuitem', { name: frequency, exact: true }).click() + await expectEditorAlignment(title) + await expect.poll(() => editor.locator('[class*="_detailScroll"]').evaluate(node => node.scrollWidth - node.clientWidth)).toBe(0) + expect(await editor.locator('input, textarea, button').evaluateAll(nodes => nodes.every((node) => { + const box = node.getBoundingClientRect() + const pane = node.closest('aside')!.getBoundingClientRect() + return box.left >= pane.left && box.right <= pane.right + }))).toBe(true) + } + expect(await title.inputValue()).toBe('Retained draft through resizing') + } + await page.setViewportSize({ width: 1100, height: 844 }) + } + expect(consoleWatch.pageErrors).toEqual([]) + expect(consoleWatch.warnings).toEqual([]) + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } +}, 180_000) diff --git a/apps/web/tests/schedule-pickers.e2e.ts b/apps/web/tests/schedule-pickers.e2e.ts new file mode 100644 index 0000000000..2548f71777 --- /dev/null +++ b/apps/web/tests/schedule-pickers.e2e.ts @@ -0,0 +1,129 @@ +/** Zoomed automation pickers truncate wide labels and keep vertical choices reachable. */ +import type { Browser, Locator, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import type {} from '@deepseek-ai/dsh-schedule' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { revealNavigationDrawer, saveFailureShot } from './support.ts' + +const TITLE = 'Inspect zoomed automation pickers' +let scaffold: WebScaffold +let browser: Browser + +beforeAll(async () => { + scaffold = await launchWebScaffold() + // Two digits must overflow at 500% zoom; narrower system UI fonts can fit. + await scaffold.ctx.settings.update('ui-theme', { textFontFamily: 'monospace' }) + await scaffold.ctx.schedule.create({ + title: TITLE, prompt: 'Inspect the deployment log', + timing: { kind: 'rrule', rrule: 'DTSTART;TZID=Asia/Shanghai:20990825T200800\nRRULE:FREQ=DAILY;COUNT=1' }, + target: { kind: 'new_once' }, + }) + browser = await chromium.launch() +}) + +afterAll(async () => { + try { + await browser?.close() + } finally { + await scaffold?.close() + } +}) + +/** Assert that the complete floating card stays inside the zoomed visual viewport. */ +async function expectContained(panel: Locator): Promise { + await expect.poll(() => panel.evaluate((node) => { + const view = window.visualViewport! + const rect = node.getBoundingClientRect() + return Math.min(rect.left - view.offsetLeft, rect.top - view.offsetTop, + view.offsetLeft + view.width - rect.right, view.offsetTop + view.height - rect.bottom) + })).toBeGreaterThanOrEqual(11.5) +} + +/** Narrow labels ellipsize instead of increasing their row's width. */ +async function expectEllipsizedText(labels: Locator): Promise { + expect(await labels.evaluateAll(nodes => nodes.every((node) => { + const style = getComputedStyle(node) + return style.textOverflow === 'ellipsis' && style.overflowX === 'hidden' + }))).toBe(true) + expect(await labels.evaluateAll(nodes => nodes.some(node => node.scrollWidth > node.clientWidth))).toBe(true) +} + +describe.each([ + { locale: 'en-US', tasks: 'Automation tasks', time: 'Time', second: 'Second', zone: 'Time zone' }, + { locale: 'zh-CN', tasks: '自动化任务', time: '时间', second: '秒', zone: '时区' }, +])('automation pickers ($locale)', (copy) => { + it.each(['clock', 'zone'] as const)('ellipsizes the %s labels and keeps vertical choices reachable at 500% zoom', async (kind) => { + const context = await browser.newContext({ + viewport: { width: 390, height: 844 }, locale: copy.locale, timezoneId: 'Asia/Shanghai', + isMobile: true, hasTouch: true, + }) + const page: Page = await context.newPage() + try { + const consoleWatch = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await revealNavigationDrawer(page, copy.locale === 'zh-CN' ? 'zh' : 'en') + await page.getByRole('button', { name: copy.tasks, exact: true }).click() + const detail = page.getByTestId('task-manager-page') + await detail.getByRole('button', { name: TITLE, exact: true }).click() + await page.evaluate(() => document.fonts.ready) + const trigger = kind === 'clock' + ? detail.getByRole('button', { name: copy.time, exact: true }) + : detail.getByRole('button', { name: new RegExp(`^${copy.zone}`) }) + await trigger.click() + const panel = kind === 'clock' + ? page.getByRole('dialog', { name: copy.time, exact: true }) + : page.getByRole('menu') + const cdp = await context.newCDPSession(page) + await cdp.send('Emulation.setPageScaleFactor', { pageScaleFactor: 5 }) + await expect.poll(() => page.evaluate(() => window.visualViewport!.scale)).toBe(5) + await expectContained(panel) + + expect(await panel.evaluate(node => node.scrollWidth <= node.clientWidth)).toBe(true) + if (kind === 'clock') { + await expectEllipsizedText(panel.locator('[role="option"] > span')) + const columns = panel.getByRole('listbox') + expect(await columns.evaluateAll(nodes => nodes.every(node => + node.scrollWidth <= node.clientWidth))).toBe(true) + const seconds = panel.getByRole('listbox', { name: copy.second, exact: true }) + expect(await seconds.evaluate((node) => { + node.scrollTop = node.scrollHeight + return node.scrollTop > 0 + })).toBe(true) + const last = seconds.getByRole('option', { name: '59', exact: true }) + await expect.poll(() => last.evaluate((node) => { + const label = node.firstElementChild!.getBoundingClientRect() + const column = node.parentElement!.getBoundingClientRect() + return label.left >= column.left && label.right <= column.right + && label.top >= column.top && label.bottom <= column.bottom + })).toBe(true) + await last.click() + await expect.poll(() => trigger.textContent()).toMatch(/:59$/) + } else { + await expectEllipsizedText(panel.locator('[role="menuitem"] > span')) + const viewport = panel.locator('[role="presentation"]').last() + expect(await viewport.evaluate((node) => { + node.scrollTop = node.scrollHeight + return node.scrollTop > 0 && node.scrollWidth <= node.clientWidth + })).toBe(true) + const last = panel.getByRole('menuitem').last() + await expect.poll(() => last.evaluate((node) => { + const row = node.getBoundingClientRect() + const viewport = node.parentElement!.getBoundingClientRect() + return row.left >= viewport.left && row.right <= viewport.right + && row.top >= viewport.top && row.bottom <= viewport.bottom + })).toBe(true) + await last.click() + await panel.waitFor({ state: 'hidden' }) + } + expect(consoleWatch.pageErrors).toEqual([]) + expect(consoleWatch.warnings).toEqual([]) + await cdp.detach() + } catch (error) { + await saveFailureShot(page, `schedule-picker-${copy.locale}-${kind}`) + throw error + } finally { + await context.close() + } + }) +}) diff --git a/apps/web/tests/session-inspector.e2e.ts b/apps/web/tests/session-inspector.e2e.ts index cba16b1571..74b853fef4 100644 --- a/apps/web/tests/session-inspector.e2e.ts +++ b/apps/web/tests/session-inspector.e2e.ts @@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises' import { fileURLToPath } from 'node:url' import { join } from 'node:path' -import { chromium, type Browser } from 'playwright' +import { chromium, webkit, type Browser } from 'playwright' import { expect, it, onTestFinished } from 'vitest' import { assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, launchWebScaffold, @@ -16,7 +16,9 @@ const fixture = fileURLToPath(new URL('../../../snapshots/web/fresh-round-trip/s const bundle = fileURLToPath(new URL('../../../packages/experimental/inspector-profile', import.meta.url)) const picker = fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)) -it.skipIf(webSnapshotMode() === 'record')('inspects a replayed Session log and Chat groups through the optional bundle', async () => { +it.skipIf(webSnapshotMode() === 'record').each([ + { name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }, +])('inspects a replayed Session log and Chat groups through the optional bundle ($name)', async ({ engine }) => { const resources: { browser?: Browser; scaffold?: WebScaffold } = {} onTestFinished(async () => { try { await resources.browser?.close() } finally { await resources.scaffold?.close() } @@ -29,7 +31,7 @@ it.skipIf(webSnapshotMode() === 'record')('inspects a replayed Session log and C extraOverlayPath: picker, replayFixture, compareReplaySession: 'read-only', paceMs: 5, }) resources.scaffold = scaffold - const browser = await chromium.launch() + const browser = await engine.launch() resources.browser = browser const page = await newEnglishPage(browser) await page.setViewportSize({ width: 1680, height: 1000 }) @@ -48,6 +50,18 @@ it.skipIf(webSnapshotMode() === 'record')('inspects a replayed Session log and C expect(await mode.inputValue()).toBe('session-log') const raw = page.getByRole('table', { name: 'Raw log', exact: true }) await raw.getByRole('button', { name: 'Filter types', exact: true }).click() + const filter = page.getByRole('dialog', { name: 'Filter types', exact: true }) + const keyword = page.getByRole('combobox', { name: 'Type keyword', exact: true }) + await filter.waitFor() + await expect.poll(() => keyword.evaluate(element => element === document.activeElement)).toBe(true) + for (const width of [1680, 800, 390, 1680]) { + await page.setViewportSize({ width, height: 1000 }) + await expect.poll(async () => { + const rect = await filter.boundingBox() + return rect !== null && rect.x >= 11 && rect.x + rect.width <= width - 11 + && rect.y >= 11 && rect.y + rect.height <= 989 + }).toBe(true) + } await page.getByRole('combobox', { name: 'Type keyword', exact: true }).fill('user/message') await page.getByRole('option', { name: 'user/message', exact: true }).click() await raw.getByRole('button', { name: 'user/message', exact: true }).first().click() diff --git a/apps/web/tests/sessionless-header.e2e.ts b/apps/web/tests/sessionless-header.e2e.ts index 142777bfcd..3ea1d15223 100644 --- a/apps/web/tests/sessionless-header.e2e.ts +++ b/apps/web/tests/sessionless-header.e2e.ts @@ -19,7 +19,9 @@ afterAll(async () => { }) describe('navigation without a selected Session', () => { - it.each(['web', 'win32', 'linux', 'darwin'] as const)('%s preserves its empty-header geometry and sidebar access', async (platform) => { + // The resident header keeps the blank-Session row height on every platform, + // so the Hero centers below the same header before and after a Workspace is bound. + it.each(['web', 'win32', 'linux', 'darwin'] as const)('%s keeps the blank-Session header height and sidebar access', async (platform) => { const page = await newEnglishPage(browser) try { if (platform !== 'web') { @@ -41,14 +43,14 @@ describe('navigation without a selected Session', () => { const sessionHeader = page.locator('[data-slot="conversation.session.header"]') expect(await sessionHeader.count()).toBe(0) const header = page.locator('[data-slot="conversation.header"] > header') - expect(await header.evaluate(element => element.getBoundingClientRect().height)).toBe(platform === 'darwin' ? 40 : 0) + expect(await header.evaluate(element => element.getBoundingClientRect().height)).toBe(40) await page.getByRole('button', { name: 'Collapse sidebar', exact: true }).click() const reopen = platform === 'darwin' ? page.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }) : page.getByRole('button', { name: 'Open sidebar', exact: true }) await reopen.waitFor({ state: 'visible' }) expect(await sessionHeader.count()).toBe(0) - expect(await header.evaluate(element => element.getBoundingClientRect().height)).toBe(platform === 'darwin' ? 40 : 0) + expect(await header.evaluate(element => element.getBoundingClientRect().height)).toBe(40) if (platform === 'darwin') { expect(await page.locator('[data-shell-leading]').getByRole('button', { name: 'New session', exact: true }).isVisible()).toBe(true) } diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index ceb4b4644b..48ca2546c6 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -473,6 +473,7 @@ function assertLeanChildRecord(agent: Agent): void { * Agent Note owns the rationale and its sources. */ const EXPECTED_TOOLS = [ + 'apply_patch', 'ask_user_question', 'bash', 'create_goal', @@ -490,15 +491,20 @@ const EXPECTED_TOOLS = [ 'read', 'read_image', 'schedule_create', - 'schedule_delete', + 'schedule_edit', 'schedule_list', - 'schedule_update', + 'schedule_view', 'send_message', 'skill', 'subagent', 'subagent_fork', + 'team_task_create', + 'team_task_get', + 'team_task_list', + 'team_task_update', 'todo_write', 'update_goal', + 'wait_agent', 'web_fetch', 'web_search', 'workflow', @@ -592,8 +598,10 @@ it('assembles the shipped Web transport, catalog, guidance, and defaults', async "mode": "always", } `) - // The directory tool is global; the deployment's default preset supplies the agent's remaining tools. - expect(ctx.tools.schemas().map(schema => schema.name)).toEqual(['working_directory']) + // Directory and conditional Team tools are global; presets supply the remaining registrations. + expect(ctx.tools.schemas().map(schema => schema.name)).toEqual([ + 'working_directory', 'team_task_create', 'team_task_list', 'team_task_get', 'team_task_update', + ]) const handle = await ctx.agents.create({ sessionId: SessionId('shipped-composition'), setup: agentCtx => ctx.agentPresets.mount(agentCtx).then(() => undefined), diff --git a/apps/web/tests/sidebar-right.e2e.ts b/apps/web/tests/sidebar-right.e2e.ts index 064adbb620..461947ed21 100644 --- a/apps/web/tests/sidebar-right.e2e.ts +++ b/apps/web/tests/sidebar-right.e2e.ts @@ -7,7 +7,7 @@ // draws the panel is a recorded, reversible choice, so this file asserts against // the frame's track as much as against the panel itself. The way back in while // collapsed is not in the column at all: it is one button in the conversation -// header, and it leaves when the panel opens. +// header, visible only while the panel is collapsed. // // Ordering is the product's own: the hero comes before any session, so the // empty right edge is asserted first and the session-bound cases follow in a @@ -114,7 +114,7 @@ async function holdPanelSlide(panel: Locator) { }) } -/** The expand button in the conversation header, present only while collapsed. */ +/** The conversation header's expand control, visible only while collapsed. */ function expandOf(page: Page): Locator { return page.locator('[data-sidebar-right-expand]') } @@ -379,8 +379,7 @@ describe('web e2e: shipped right Sidebar', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-right-pageup')) const frame = page.locator('[class*="frame"]').first() const composer = page.locator('textarea, [contenteditable="true"]').first() - // The expand button exists only while the panel is collapsed, when its - // docked hosts sit translated past the frame's right edge. + // Collapsed docked hosts sit translated past the frame's right edge. await expandOf(page).waitFor({ timeout: 15_000 }) await composer.click() await composer.pressSequentially('caret') @@ -644,6 +643,74 @@ describe('web e2e: shipped right Sidebar', () => { expect(tripwire.warnings).toEqual([]) }) + it.each([390, 767])('keeps the mobile conversation title still while the right sidebar slides at %ipx', async (viewportWidth) => { + const caseName = `mobile-title-${viewportWidth}` + const mobilePage = await browser.newPage({ + viewport: { width: viewportWidth, height: 844 }, + locale: 'en-US', timezoneId: 'Asia/Shanghai', + userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_6 like Mac OS X) AppleWebKit/605.1.15 Version/18.6 Mobile/15E148 Safari/604.1', + isMobile: true, hasTouch: true, reducedMotion: 'no-preference', + storageState: await page.context().storageState(), + }) + const mobileTripwire = watchConsole(mobilePage) + try { + await mobilePage.goto(page.url(), { waitUntil: 'load' }) + const column = await resetSidebar(mobilePage) + const panel = column.locator('[data-sidebar-right-panel]') + const title = mobilePage.locator('[class*="titleCluster"]').first() + const utilities = mobilePage.locator('[class*="headerUtilities"]').first() + await expect.poll(() => panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') + await column.locator('[data-sidebar-right-toggle]').tap() + await panel.evaluate(async (node) => { + await Promise.allSettled(node.getAnimations({ subtree: true }).map(animation => animation.finished)) + }) + await expandOf(mobilePage).waitFor() + const titleNode = await title.locator('[class*="crumbCurrent"]').elementHandle() + if (titleNode === null) throw new Error('conversation title is not rendered') + const titleBefore = await title.boundingBox() + const utilitiesBefore = await utilities.boundingBox() + expect(titleBefore?.width).toBeGreaterThan(0) + expect(utilitiesBefore?.width).toBeGreaterThan(0) + await shot(mobilePage, `${caseName}-collapsed`) + try { + for (const opening of [true, false]) { + const held = await holdPanelSlide(panel) + try { + await (opening ? expandOf(mobilePage) : column.locator('[data-sidebar-right-toggle]')).tap() + await expect.poll(() => held.evaluate(state => state.animation?.playState)).toBe('paused') + const progress = await held.evaluate(state => state.animation?.effect?.getComputedTiming().progress) + expect(progress).toBeGreaterThan(0) + expect(progress).toBeLessThan(1) + expect(await title.boundingBox()).toEqual(titleBefore) + expect(await utilities.boundingBox()).toEqual(utilitiesBefore) + expect(await titleNode.evaluate(node => node.isConnected)).toBe(true) + expect(await expandOf(mobilePage).isDisabled()).toBe(opening) + expect(await mobilePage.getByRole('button', { name: 'Open right sidebar', exact: true }).count()).toBe(opening ? 0 : 1) + await shot(mobilePage, `${caseName}-${opening ? 'opening' : 'closing'}`) + await held.evaluate((state) => { (state.animation as Animation).finish() }) + expect(await title.boundingBox()).toEqual(titleBefore) + expect(await utilities.boundingBox()).toEqual(utilitiesBefore) + } finally { + await held.evaluate((state) => { + state.dispose() + if (state.animation?.playState === 'paused') state.animation.finish() + }) + await held.dispose() + } + } + } finally { + await titleNode.dispose() + } + expect(mobileTripwire.pageErrors).toEqual([]) + expect(mobileTripwire.warnings).toEqual([]) + } catch (error) { + await saveFailureShot(mobilePage, `web-e2e-sidebar-right-${caseName}`) + throw error + } finally { + await mobilePage.close() + } + }) + it('keeps a capacity-closed panel closed after widening and uses fullscreen on a narrow viewport', async () => { const viewport = page.viewportSize() if (viewport === null) throw new Error('expected a fixed viewport') @@ -668,6 +735,7 @@ describe('web e2e: shipped right Sidebar', () => { await expect.poll(async () => await panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') await expect.poll(async () => await width(panel)).toBe(767) await expect.poll(() => frame.getAttribute('data-rightbar-fullscreen')).toBe('true') + expect(await expandOf(page).count()).toBe(0) expect(await frame.locator('[data-side="rightbar"]').count()).toBe(0) await column.locator('[data-sidebar-right-mode="push"]').click() await expect.poll(async () => await column.locator('[data-sidebar-right-open]').count()).toBe(0) diff --git a/apps/web/tests/sidebar-subagent-activity.e2e.ts b/apps/web/tests/sidebar-subagent-activity.e2e.ts index f2c8eb3434..7ae28dd478 100644 --- a/apps/web/tests/sidebar-subagent-activity.e2e.ts +++ b/apps/web/tests/sidebar-subagent-activity.e2e.ts @@ -101,10 +101,8 @@ describe('web e2e: sidebar subagent activity', () => { provider: 'spawn', label: 'sidebar activity child', signal: new AbortController().signal, - request: { - prompt: [{ type: 'text', text: 'Hold this delegated task open.' }], - parent: parentHandle.agent, - }, + prompt: [{ type: 'text', text: 'Hold this delegated task open.' }], + parent: parentHandle.agent, }) childId = started.childId await waitForRunningChild(scaffold, adapter, childId) @@ -147,10 +145,72 @@ describe('web e2e: sidebar subagent activity', () => { ) expect(await ownerRow.locator('[data-state="ongoing"]').count()).toBe(1) await ownerRow.click() - const runningTrigger = page.getByRole('button', { name: '1 subagent running' }) + const runningTrigger = page.getByRole('button', { name: '1 subagent', exact: true }) await runningTrigger.waitFor({ timeout: 10_000 }) expect(await runningTrigger.locator('[data-state="ongoing"]').count()).toBe(1) - await assertFixtureInventory(SNAPSHOT_DIR, ['owner-running.expected.md']) + // This directly created owner has no tool preset; the fixture collects its own job. + scaffold.ctx.effect(() => scaffold.ctx.jobs.attachController('compact header fixture'), 'compact header job controller') + const completion = Promise.withResolvers<{ status: 'completed' }>() + const ownerId = parentHandle.agent.id + const jobId = scaffold.ctx.jobs.start({ + kind: 'bash', label: 'Concurrent background work', owner: ownerId, + run(handle) { + handle.append('Background work is running.\n') + return { done: completion.promise, cancel: () => { completion.resolve({ status: 'completed' }) } } + }, + }) + const viewport = page.viewportSize()! + try { + const jobTrigger = page.getByRole('button', { name: '1 background job', exact: true }) + await jobTrigger.waitFor() + expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running') + const controls = [ + { trigger: runningTrigger, icon: '[data-icon="dsw-icon-users-outline-regular"]', count: '[data-subagent-count]' }, + { trigger: jobTrigger, icon: '[data-icon="dsw-icon-layers-outline-regular"]', count: '[data-job-count]' }, + ] + for (const { trigger, icon, count } of controls) { + expect(await trigger.locator(count).isVisible()).toBe(true) + expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true) + expect(await trigger.locator(icon).isVisible()).toBe(false) + } + await runningTrigger.focus() + await page.setViewportSize({ width: 390, height: 700 }) + for (const { trigger, icon, count } of controls) { + await expect.poll(() => trigger.locator(count).isVisible()).toBe(false) + expect(await trigger.locator(icon).isVisible()).toBe(true) + expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(false) + } + expect(await runningTrigger.evaluate(element => element === document.activeElement)).toBe(true) + expect(await jobTrigger.evaluate(element => document.getElementById(element.getAttribute('aria-describedby')!)?.textContent)).toBe('Running') + await compareOrRefreshGolden( + join(SNAPSHOT_DIR, 'compact-running.expected.md'), + await captureStableAria(page, 'header:has([data-subagent-action])', scaffold.workspaceCwd), + MODE, + ) + await saveFailureShot(page, 'web-e2e-compact-running-icons') + await runningTrigger.click() + const members = page.locator('[data-subagent-panel]') + await members.waitFor() + expect(await members.getByRole('treeitem').locator('[data-state="ongoing"]').isVisible()).toBe(true) + await page.keyboard.press('Escape') + await jobTrigger.click() + const jobs = page.getByRole('list', { name: 'Background jobs', exact: true }) + await jobs.waitFor() + expect(await jobs.locator('[data-state="ongoing"]').isVisible()).toBe(true) + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + for (const { trigger, icon, count } of controls) { + await expect.poll(() => trigger.locator(count).isVisible()).toBe(true) + expect(await trigger.locator('[data-state="ongoing"]').isVisible()).toBe(true) + expect(await trigger.locator(icon).isVisible()).toBe(false) + } + } finally { + completion.resolve({ status: 'completed' }) + await scaffold.ctx.jobs.wait(jobId, 5_000, ownerId) + await page.keyboard.press('Escape') + await page.setViewportSize(viewport) + } + await assertFixtureInventory(SNAPSHOT_DIR, ['owner-running.expected.md', 'compact-running.expected.md']) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) diff --git a/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md new file mode 100644 index 0000000000..07a6ac96dc --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/collaboration.zh.expected.md @@ -0,0 +1,17 @@ +## Menu + +- menu "模型与推理等级": + - menuitem "模型 DeepSeek-V4-Flash" + - text: 启用智能体团队协作 + - button "关于智能体团队协作" + - switch "启用智能体团队协作" [checked] + +## Confirmation + +- dialog "确认停用智能体团队协作?": + - heading "确认停用智能体团队协作?" [level=2] + - button "关闭" + - paragraph: 对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。 + - paragraph: 停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。 + - button "取消" + - button "确认停用" diff --git a/apps/web/tests/snapshots/agent-team-panel/command-error.en.expected.md b/apps/web/tests/snapshots/agent-team-panel/command-error.en.expected.md new file mode 100644 index 0000000000..f636b75b13 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/command-error.en.expected.md @@ -0,0 +1,8 @@ +## Failed receipt + +- 'button "Agent teamwork Failed: Use /team on or /team off."' + +## Raw error + +- 'button "Agent teamwork Failed: Use /team on or /team off." [expanded]' +- text: Use /team on or /team off. diff --git a/apps/web/tests/snapshots/agent-team-panel/command-error.zh.expected.md b/apps/web/tests/snapshots/agent-team-panel/command-error.zh.expected.md new file mode 100644 index 0000000000..198f3edb33 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/command-error.zh.expected.md @@ -0,0 +1,8 @@ +## Failed receipt + +- button "智能体团队协作 执行失败:Use /team on or /team off." + +## Raw error + +- button "智能体团队协作 执行失败:Use /team on or /team off." [expanded] +- text: Use /team on or /team off. diff --git a/apps/web/tests/snapshots/agent-team-panel/disable-confirmation.expected.md b/apps/web/tests/snapshots/agent-team-panel/disable-confirmation.expected.md new file mode 100644 index 0000000000..ae29ea02b2 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/disable-confirmation.expected.md @@ -0,0 +1,7 @@ +- dialog "Disable agent teamwork?": + - heading "Disable agent teamwork?" [level=2] + - button "Close" + - paragraph: Disabling agent teamwork during a conversation stops the use of shared task tools and team coordination instructions. + - paragraph: Disabling it may affect cache reuse, increase subsequent token usage and costs, and affect collaboration on the current task. + - button "Cancel" + - button "Disable" diff --git a/apps/web/tests/snapshots/agent-team-panel/info.expected.md b/apps/web/tests/snapshots/agent-team-panel/info.expected.md new file mode 100644 index 0000000000..5e675607a5 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/info.expected.md @@ -0,0 +1 @@ +- tooltip "Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs." diff --git a/apps/web/tests/snapshots/agent-team-panel/resize.expected.md b/apps/web/tests/snapshots/agent-team-panel/resize.expected.md index 57fbab1f84..3e8f7521b2 100644 --- a/apps/web/tests/snapshots/agent-team-panel/resize.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/resize.expected.md @@ -1,15 +1,26 @@ -- dialog "Agent team": - - heading "Members" [level=3] - - button "lead Current chat Inactive" [disabled] - - heading "Shared tasks 2" [level=3] - - article: - - strong: Agent task - - text: In progress - - paragraph: Created by the Team Lead - - text: "task-1Owner: leadWrite scopes: src/web" - - article: - - strong: Responsive task - - text: Pending - - paragraph: Check the task description before you start work. Check the task description before you start work. Check the task description before you start work. - - button "Show more" - - text: "task-2Owner: UnownedReady" +- dialog "Subagent sessions": + - heading "Subagents" [level=3] + - text: 1 external + - tree "Subagent sessions": + - 'treeitem "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher · External task" [disabled] [level=1]': "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher" + - region "Task board": + - heading "Shared tasks 1 completed · 1 in progress · 2 pending" [level=3] + - list: + - listitem: + - button "In progress Agent task": + - img "In progress" + - text: Agent task + - listitem: + - button "Completed Completed preparation": + - img "Completed" + - text: Completed preparation + - listitem: + - button "Pending Dependency task": + - img "Pending" + - text: Dependency task + - listitem: + - button "Blocked by dependencies Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport" [expanded]: + - img "Blocked by dependencies" + - text: Responsive task with a long title that remains fully readable when expanded at the minimum supported viewport + - paragraph: Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. Check every dependency and write scope before you start work. + - paragraph: "Owner: Unowned" diff --git a/apps/web/tests/snapshots/agent-team-panel/task-only.expected.md b/apps/web/tests/snapshots/agent-team-panel/task-only.expected.md new file mode 100644 index 0000000000..6a663176b6 --- /dev/null +++ b/apps/web/tests/snapshots/agent-team-panel/task-only.expected.md @@ -0,0 +1,11 @@ +- dialog "Subagent sessions": + - heading "Subagents" [level=3] + - paragraph: No subagents + - tree "Subagent sessions" + - region "Task board": + - heading "Shared tasks 1 pending" [level=3] + - list: + - listitem: + - button "Pending Plan before delegation": + - img "Pending" + - text: Plan before delegation diff --git a/apps/web/tests/snapshots/agent-team-panel/task.expected.md b/apps/web/tests/snapshots/agent-team-panel/task.expected.md index d5593a069b..9032c3413b 100644 --- a/apps/web/tests/snapshots/agent-team-panel/task.expected.md +++ b/apps/web/tests/snapshots/agent-team-panel/task.expected.md @@ -1,9 +1,14 @@ -- dialog "Agent team": - - heading "Members" [level=3] - - button "lead Current chat Inactive" [disabled] - - heading "Shared tasks 1" [level=3] - - article: - - strong: Agent task - - text: In progress - - paragraph: Created by the Team Lead - - text: "task-1Owner: leadWrite scopes: src/web" +- dialog "Subagent sessions": + - heading "Subagents" [level=3] + - text: 1 external + - tree "Subagent sessions": + - 'treeitem "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher · External task" [disabled] [level=1]': "Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. Researcher: investigate the construction and verify every bound before reporting the result. team-panel-researcher" + - region "Task board": + - heading "Shared tasks 1 in progress" [level=3] + - list: + - listitem: + - button "In progress Agent task" [expanded]: + - img "In progress" + - text: Agent task + - paragraph: Created by the root agent + - paragraph: "Owner: session-{{uuid}}" diff --git a/apps/web/tests/snapshots/subagent-summary/fork.expected.md b/apps/web/tests/snapshots/subagent-summary/fork.expected.md new file mode 100644 index 0000000000..c94fd252dd --- /dev/null +++ b/apps/web/tests/snapshots/subagent-summary/fork.expected.md @@ -0,0 +1,40 @@ +## Running + +- text: Running +- button "Fork subagent Review inherited conversation context" + +## Creation receipt and complete task + +- button "Fork subagent Review inherited conversation context" [expanded] +- text: Recorded result +- list: + - listitem: + - text: Started + - term: Agent task description + - definition: Review inherited conversation context + - term: ID + - definition: fork-worker + - group: + - text: Task + - list: + - listitem: + - paragraph: Summarize the earlier agreed requirements. Do not modify files. +- button "Inspect" + +## Restored creation receipt + +- button "Fork subagent Review inherited conversation context" [expanded] +- text: Recorded result +- list: + - listitem: + - text: Started + - term: Agent task description + - definition: Review inherited conversation context + - term: ID + - definition: fork-worker + - group: + - text: Task + - list: + - listitem: + - paragraph: Summarize the earlier agreed requirements. Do not modify files. +- button "Inspect" diff --git a/apps/web/tests/snapshots/subagent-summary/lifecycle.expected.md b/apps/web/tests/snapshots/subagent-summary/lifecycle.expected.md new file mode 100644 index 0000000000..105e201da9 --- /dev/null +++ b/apps/web/tests/snapshots/subagent-summary/lifecycle.expected.md @@ -0,0 +1,52 @@ +## Preparing without description + +- text: Preparing tool call Create subagent + +## Preparing with partial description + +- text: Preparing tool call Create subagent Review subagent task summaries + +## Running + +- text: Running +- button "Create subagent Review subagent task summaries" + +## Created + +- button "Create subagent Review subagent task summaries" + +## Creation receipt and complete task + +- button "Create subagent Review subagent task summaries" [expanded] +- text: Recorded result +- list: + - listitem: + - text: Started + - term: Agent task description + - definition: Review subagent task summaries Additional description context + - term: ID + - definition: child-foo + - group: + - text: Task + - list: + - listitem: + - paragraph: Inspect the subagent tool card across its lifecycle. Check streaming arguments, creation receipts, and restored history. Return findings without changing unrelated files. +- button "Inspect" + +## Restored creation receipt + +- button "Create subagent Review subagent task summaries" [expanded] +- text: Recorded result +- list: + - listitem: + - text: Started + - term: Agent task description + - definition: Review subagent task summaries Additional description context + - term: ID + - definition: child-foo + - group: + - text: Task + - list: + - listitem: + - paragraph: Inspect the subagent tool card across its lifecycle. Check streaming arguments, creation receipts, and restored history. Return findings without changing unrelated files. +- button "Inspect" diff --git a/apps/web/tests/snapshots/subagent-summary/variants.expected.md b/apps/web/tests/snapshots/subagent-summary/variants.expected.md new file mode 100644 index 0000000000..b79b9010c4 --- /dev/null +++ b/apps/web/tests/snapshots/subagent-summary/variants.expected.md @@ -0,0 +1,39 @@ +## fallback + +- button "Create subagent Review the fallback summary." [expanded] +- text: Recorded result +- list: + - listitem: + - text: Started + - term: ID + - definition: fallback-worker + - group: + - text: Task + - list: + - listitem: + - paragraph: Review the fallback summary. Keep the complete task in details. +- button "Inspect" + +## reply + +- button "Create subagent Check synchronous agent reply" [expanded] +- text: Recorded result +- list: + - listitem: + - text: Agent response + - paragraph: The synchronous agent found two issues. Both are documented in the report. + - group: + - text: Task + - list: + - listitem: + - paragraph: Review the synchronous report. Keep every instruction available. +- button "Inspect" + +## title-only + +- button "Create subagent" + +## error + +- text: Failed +- button "Create subagent Subagent capacity exceeded" diff --git a/apps/web/tests/startup-auto-selection.e2e.ts b/apps/web/tests/startup-auto-selection.e2e.ts index 613eb4a7d0..eb24b80a57 100644 --- a/apps/web/tests/startup-auto-selection.e2e.ts +++ b/apps/web/tests/startup-auto-selection.e2e.ts @@ -61,10 +61,36 @@ describe('web e2e: startup auto-selection', () => { if (Object.values(refs).some(node => node === null)) throw new Error('incomplete initial Hero tree') ;(window as unknown as { __heroTree: typeof refs }).__heroTree = refs }) + // The input card's distance from the conversation top, once it holds for three frames. + const heroCardOffset = (): Promise => page.evaluate(async () => { + const read = (): number => { + const root = document.querySelector('div[data-phase="hero"]') + const card = document.querySelector('[data-composer-card]') + if (root === null || card === null) throw new Error('incomplete Hero composer') + return card.getBoundingClientRect().top - root.getBoundingClientRect().top + } + const deadline = performance.now() + 5_000 + let previous = read() + let stableFrames = 0 + while (performance.now() < deadline) { + await new Promise((resolve) => { requestAnimationFrame(() => { resolve() }) }) + const current = read() + stableFrames = Math.abs(current - previous) < 0.01 ? stableFrames + 1 : 0 + if (stableFrames >= 3) return current + previous = current + } + throw new Error('Hero input card did not settle') + }) + const sessionlessOffset = await heroCardOffset() // A registered Workspace is the precondition for the reload case below; // this first connection is also the no-Workspace → Workspace path. await connectFreshWorkspace(page, scaffold.workspaceCwd, 'startup-auto-selection') + await page.locator('[data-slot="conversation.session.header"]').waitFor({ timeout: 15_000 }) + // Binding the Workspace keeps the input card at the same height in the Hero. + // This holds for the default plugin set: `conversation.hero.options` entries + // render only with a Session and can change the Hero's height. + expect(Math.abs(await heroCardOffset() - sessionlessOffset)).toBeLessThanOrEqual(0.5) expect(await page.evaluate(() => { const before = (window as unknown as { __heroTree: Record }).__heroTree diff --git a/apps/web/tests/steering.e2e.ts b/apps/web/tests/steering.e2e.ts index 3b47c0a4b5..a687c45f57 100644 --- a/apps/web/tests/steering.e2e.ts +++ b/apps/web/tests/steering.e2e.ts @@ -371,8 +371,8 @@ describe.each(['reconnect', 'delayed-inbox'] as const)('web e2e: composer shortc server.onMessage((message) => { const frame = parseRemoteStreamServerMessage(String(message)) if (holdInbox && frame.type === 'item') { - const value = frame.value as { type?: string; key?: string } - if (value.type === 'projection' && value.key === 'inbox') heldStream = frame.streamId + const value = frame.value as { type?: string; changes?: readonly { key: string }[] } + if (value.type === 'projection' && value.changes?.some(change => change.key === 'inbox') === true) heldStream = frame.streamId } // Hold the remaining control stream in FIFO order, while history keeps flowing. if (holdInbox && frame.streamId === heldStream) heldControl.push(() => { route.send(message) }) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 56d7f0e66b..2b9cae7b84 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -5,7 +5,7 @@ import { dirname, join } from 'node:path' import { zstdCompressSync } from 'node:zlib' import type { Browser, Page } from 'playwright' import { chromium } from 'playwright' -import { afterAll, beforeAll, describe, expect, it, onTestFailed, vi } from 'vitest' +import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished, vi } from 'vitest' import { prepareSessionSnapshotFixtureForComparison } from '@deepseek-ai/dsh-llm-replay' import { SESSION_FORMAT_VERSION, SessionId as sessionId, SessionLogOffset, SessionSeq, @@ -32,7 +32,7 @@ const TREE_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-con const BRANCHLESS_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/branchless.expected.md', import.meta.url)) const SIDEBAR_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/sidebar.expected.md', import.meta.url)) const SIDEBAR_CHAT_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/sidebar-chat.expected.md', import.meta.url)) -const UNAVAILABLE_GRANDCHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/nested.expected.md', import.meta.url)) +const GRANDCHILD_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/nested.expected.md', import.meta.url)) const FORK_EXPECTED = fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/fork.expected.md', import.meta.url)) const MIGRATING_CHILD_EXPECTED = fileURLToPath(new URL( './expected/subagent-conversation/migration-required-child.expected.md', import.meta.url, @@ -102,6 +102,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = let browser: Browser let page: Page let sidecarRoot: string + let parentId: SessionId let childId: SessionId let oneShotId: SessionId let grandchildId: SessionId @@ -139,8 +140,9 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) - const parent = scaffold.ctx.agents.roots()[0] + const parent = scaffold.ctx.agents.list().filter(agent => agent.session.header.origin !== 'subagent')[0] if (parent === undefined) throw new Error('fresh workspace did not publish its parent Agent') + parentId = parent.id const parentSettled = scaffold.whenTurnSettled() const parentInput = page.locator('[data-composer-input][contenteditable="true"]').first() await parentInput.fill(PARENT_PROMPT) @@ -152,10 +154,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () = provider: 'spawn', label: LABEL, signal: new AbortController().signal, - request: { - prompt: [{ type: 'text', text: INITIAL_PROMPT }], - parent, - }, + prompt: [{ type: 'text', text: INITIAL_PROMPT }], + parent, }) childId = started.childId await waitForAgentToSettle(scaffold, childId) @@ -309,25 +309,23 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(scaffold.ctx.agents.get(childId)).toBeUndefined() expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined() expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() - expect(await scaffold.ctx.subagents.listChildren(parent.id)).toMatchObject([ - { - id: childId, mode: 'continuable', label: LABEL, - }, - { - id: oneShotId, mode: 'one-shot', label: ONE_SHOT_LABEL, - }, - ]) + { + using observed = await scaffold.ctx.sessionQuery.observeSession(parent.id) + expect(observed.projections?.values.subagentCatalog).toMatchObject([ + { + id: childId, mode: 'continuable', label: LABEL, + }, + { + id: oneShotId, mode: 'one-shot', label: ONE_SHOT_LABEL, + }, + ]) + } { using observed = await scaffold.ctx.sessionQuery.observeSession(childId) expect(observed.source).toBe('prepared') expect(observed.projections?.values.subagentCatalog).toEqual([ { id: grandchildId, createdAt: authoredAt, mode: 'continuable', label: NESTED_LABEL }, ]) - expect(await scaffold.ctx.subagents.listChildren(childId)).toMatchObject([ - { - id: grandchildId, mode: 'continuable', label: NESTED_LABEL, - }, - ]) } await waitForCacheRow(scaffold, childHeader) const cache = scaffold.ctx.storageDomain.get(projectionCacheDomainSpec.name) @@ -379,6 +377,65 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await writeComposerDraft(page, input, '') }) + it('enters the member tree after pointer or keyboard activation of its trigger', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-trigger-focus')) + const trigger = page.getByRole('button', { name: '2 subagents', exact: true }) + const panel = page.locator('[data-subagent-panel]') + try { + for (const activation of ['click', 'Enter', 'Space']) { + if (activation === 'click') await trigger.click() + else await trigger.press(activation) + await expect.poll(() => panel.evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('ArrowDown') + expect(await panel.locator('[role="treeitem"]:not([aria-disabled="true"])').first() + .evaluate(element => element === document.activeElement)).toBe(true) + await page.keyboard.press('Escape') + await panel.waitFor({ state: 'detached' }) + expect(await trigger.evaluate(element => element === document.activeElement)).toBe(true) + } + } finally { + await page.locator('[data-composer-input]').first().hover() + } + }) + + it('shows complete descriptions and IDs without hover at desktop and touch widths', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-catalog-labels')) + const originalViewport = page.viewportSize()! + const originalUrl = page.url() + try { + for (const width of [originalViewport.width, 390]) { + await page.setViewportSize({ ...originalViewport, width }) + const trigger = page.getByRole('button', { name: '2 subagents', exact: true }) + await trigger.click() + const panel = page.locator('[data-subagent-panel]') + const row = panel.getByRole('treeitem', { name: new RegExp(LABEL) }) + const primary = row.getByText(LABEL, { exact: true }) + const secondary = row.getByText(childId, { exact: true }) + const primaryBounds = await primary.boundingBox() + const secondaryBounds = await secondary.boundingBox() + expect(primaryBounds).not.toBeNull() + expect(secondaryBounds).not.toBeNull() + expect(primaryBounds!.y + primaryBounds!.height).toBeLessThanOrEqual(secondaryBounds!.y) + for (const label of [primary, secondary]) { + expect(await label.evaluate(element => element.scrollWidth <= element.clientWidth + && element.scrollHeight <= element.clientHeight)).toBe(true) + } + expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${childId} `) + expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0) + expect(await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).count()).toBe(1) + expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1) + expect(page.url()).toBe(originalUrl) + expect(await page.getByRole('tooltip').count()).toBe(0) + expect(scaffold.ctx.agents.get(childId)).toBeUndefined() + await page.keyboard.press('Escape') + await panel.waitFor({ state: 'detached' }) + } + } finally { + await page.setViewportSize(originalViewport) + await page.locator('[data-composer-input]').first().hover() + } + }) + it('recovers a current-format cold child catalog cache miss without activating either level', async () => { onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree')) await page.getByRole('button', { name: '2 subagents' }).hover() @@ -388,6 +445,8 @@ describe('web e2e: persisted subagent conversation and human continuation', () = const hit = document.elementFromPoint(rect.left + 8, rect.top + 8) return hit !== null && element.contains(hit) })).toBe(true) + const sectionHeader = page.locator('[data-subagent-section-header]') + expect(await sectionHeader.count()).toBe(0) const oneShotDisclosure = page.getByRole('button', { name: `Expand ${ONE_SHOT_LABEL} descendants`, }) @@ -396,22 +455,112 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1) expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1) expect(await oneShotRow.getAttribute('aria-label')).toContain('192d 00h 00m 00s') + const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) }) + const disclosure = childRow.getByRole('button', { name: new RegExp(`^(Expand|Collapse) ${LABEL} descendants$`, 'u') }) + const beforeDisclosureUrl = page.url() + const clickDisclosureGutter = async (offset: number): Promise => { + const geometry = await disclosure.evaluate((button, xOffset) => { + const row = button.closest('[role="treeitem"]')! + const rowBounds = row.getBoundingClientRect() + const buttonBounds = button.getBoundingClientRect() + const glyph = getComputedStyle(button.querySelector('svg')!) + const target = { x: rowBounds.left + xOffset, y: rowBounds.bottom - 3 } + const pseudo = getComputedStyle(button, '::after') + const status = row.querySelector('[data-state]')!.getBoundingClientRect() + return { + target, + outsideButton: target.x < buttonBounds.left || target.x > buttonBounds.right + || target.y < buttonBounds.top || target.y > buttonBounds.bottom, + pseudo: { width: pseudo.width, height: pseudo.height, top: pseudo.top, bottom: pseudo.bottom, left: pseudo.left }, + rowHeight: rowBounds.height, + glyph: { width: glyph.width, height: glyph.height }, + transform: getComputedStyle(button).transform, + hitsDisclosure: document.elementFromPoint(target.x, target.y) === button, + missesNextRow: document.elementFromPoint(target.x, rowBounds.bottom + 1) !== button, + endsBeforeStatus: rowBounds.left + 28 <= status.left, + missesStatus: document.elementFromPoint(status.left + status.width / 2, status.top + status.height / 2) !== button, + } + }, offset) + expect(geometry.outsideButton, JSON.stringify(geometry)).toBe(true) + expect(geometry.pseudo).toEqual({ width: '28px', height: `${geometry.rowHeight}px`, top: '0px', bottom: '0px', left: '0px' }) + expect(geometry.glyph).toEqual({ width: '12px', height: '12px' }) + expect(geometry.transform).toBe('none') + expect(geometry.hitsDisclosure).toBe(true) + expect(geometry.missesNextRow).toBe(true) + expect(geometry.endsBeforeStatus).toBe(true) + expect(geometry.missesStatus).toBe(true) + const body = childRow.locator(':scope > div') + await childRow.getByText(LABEL, { exact: true }).hover() + expect(await body.evaluate(element => getComputedStyle(element).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)') + await page.mouse.move(geometry.target.x, geometry.target.y) + expect(await body.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + await page.mouse.click(geometry.target.x, geometry.target.y) + expect(page.url()).toBe(beforeDisclosureUrl) + expect(await page.getByText(PARENT_PROMPT, { exact: true }).isVisible()).toBe(true) + expect(await page.locator('[data-sidebar-chat]').count()).toBe(0) + } const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') try { const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections') - await page.getByRole('button', { name: `Expand ${LABEL} descendants` }).click() + await clickDisclosureGutter(3) await projections await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 }) + expect(await sectionHeader.count()).toBe(0) expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true) expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false) } finally { observe.mockRestore() } - const childRow = page.getByRole('treeitem', { name: new RegExp(LABEL) }) + await clickDisclosureGutter(26) + await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' }) + expect(await childRow.getAttribute('aria-expanded')).toBe('false') + await clickDisclosureGutter(3) + await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor() + expect(await childRow.getAttribute('aria-expanded')).toBe('true') + const connector = await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).evaluate((row) => { + const rowBounds = row.getBoundingClientRect() + const dot = row.querySelector('[data-state]')! + const dotBounds = dot.getBoundingClientRect() + const slot = dot.parentElement!.getBoundingClientRect() + const horizontal = getComputedStyle(row, '::before') + const node = row.parentElement! + const spine = getComputedStyle(node, '::before') + const stroke = Number.parseFloat(horizontal.borderTopWidth) + const colorProbe = document.createElement('span') + colorProbe.style.cssText = 'display:none;color:var(--dsw-alias-border-l3)' + row.append(colorProbe) + let expectedColor: string + try { + expectedColor = getComputedStyle(colorProbe).color + } finally { + colorProbe.remove() + } + return { + rowTop: rowBounds.top, + dotCenter: dotBounds.top + dotBounds.height / 2, + lineCenter: rowBounds.top + Number.parseFloat(horizontal.top) + stroke / 2, + lineEnd: rowBounds.left + Number.parseFloat(horizontal.left) + Number.parseFloat(horizontal.width), + slotLeft: slot.left, + spineEnd: node.getBoundingClientRect().top + Number.parseFloat(spine.top) + Number.parseFloat(spine.height), + lastSibling: node.nextElementSibling === null, + stroke, + color: horizontal.borderTopColor, + spineColor: spine.borderLeftColor, + expectedColor, + } + }) + expect(connector.lastSibling).toBe(true) + expect(Math.abs(connector.lineCenter - connector.dotCenter), JSON.stringify(connector)).toBeLessThanOrEqual(0.5) + expect(Math.abs(connector.spineEnd - connector.dotCenter), JSON.stringify(connector)).toBeLessThanOrEqual(0.5) + expect(Math.abs(connector.lineEnd - connector.slotLeft), JSON.stringify(connector)).toBeLessThanOrEqual(0.5) + expect(connector.stroke).toBeGreaterThanOrEqual(0.5) + expect(connector.stroke).toBeLessThanOrEqual(1) + expect(connector.color).toBe(connector.expectedColor) + expect(connector.spineColor).toBe(connector.expectedColor) const childLabel = await childRow.getAttribute('aria-label') await page.waitForTimeout(1_100) expect(await childRow.getAttribute('aria-label')).toBe(childLabel) - expect(await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).textContent()).toContain('continuable') + expect(await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getAttribute('aria-label')).toContain('continuable') expect(scaffold.ctx.agents.get(childId)).toBeUndefined() expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() const snapshot = await captureStableAria( @@ -420,7 +569,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = scaffold.workspaceCwd, ) await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE) - await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click() await page.getByText(NESTED_PROMPT).waitFor() const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' }) await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true }).waitFor() @@ -435,7 +584,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await page.getByRole('button', { name: '2 subagents' }).hover() await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).click() const sidebarChat = page.locator('[data-sidebar-chat]') - await sidebarChat.getByText(/^Explain event sourcing in one sentence\.Your parent agent id is /).waitFor({ timeout: 15_000 }) + await sidebarChat.getByText(/^Explain event sourcing in one sentence\./).waitFor({ timeout: 15_000 }) await compareOrRefreshGolden( SIDEBAR_CHAT_EXPECTED, await captureStableAria(page, '[data-sidebar-chat]', scaffold.workspaceCwd), @@ -456,16 +605,34 @@ describe('web e2e: persisted subagent conversation and human continuation', () = it('opens the completed child from persistence without activating it', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-open')) await page.getByRole('button', { name: '2 subagents' }).hover() - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(LABEL, { exact: true }).click() await expect.poll( - () => page.getByText(/^Explain event sourcing in one sentence\.Your parent agent id is /).count(), + () => page.getByText(/^Explain event sourcing in one sentence\./).count(), { timeout: 15_000 }, ).toBe(1) if (scaffold.ctx.agents.get(childId) !== undefined) { throw new Error(`viewing the child activated it; API calls: ${apiCalls.join(', ')}`) } const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' }) - await hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor() + const currentCrumb = hierarchy.getByRole('button', { name: `Switch subagent: ${LABEL}` }) + await currentCrumb.waitFor() + const crumbGeometry = await Promise.all([hierarchy.getByRole('button').first(), currentCrumb].map(crumb => crumb.evaluate((element) => { + const style = getComputedStyle(element) + const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT) + let text = walker.nextNode() + while (text !== null && text.textContent?.trim() === '') text = walker.nextNode() + if (text === null) throw new Error('Breadcrumb has no title text') + const range = document.createRange() + range.selectNodeContents(text) + const bounds = range.getBoundingClientRect() + return { fontSize: style.fontSize, lineHeight: style.lineHeight, top: bounds.top, bottom: bounds.bottom } + }))) + expect(crumbGeometry.map(({ fontSize, lineHeight }) => ({ fontSize, lineHeight }))) + .toEqual([{ fontSize: '14px', lineHeight: '20px' }, { fontSize: '14px', lineHeight: '20px' }]) + expect(Math.abs(crumbGeometry[0]!.top - crumbGeometry[1]!.top), JSON.stringify(crumbGeometry)).toBeLessThanOrEqual(1) + expect(Math.abs(crumbGeometry[0]!.bottom - crumbGeometry[1]!.bottom), JSON.stringify(crumbGeometry)).toBeLessThanOrEqual(1) + expect(await hierarchy.getByRole('button', { name: '1 subagent', exact: true }) + .evaluate(element => getComputedStyle(element).fontSize)).toBe('12px') const sidebar = await captureStableAria( page, '[role="tree"][aria-label="Sessions"]', @@ -494,7 +661,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await expect.poll(() => requested, { timeout: 15_000 }).toBe(true) expect(await page.getByText('This subagent is read-only for now', { exact: true }).count()).toBe(0) expect(await page.getByRole('navigation', { name: 'Session hierarchy' }).count()).toBe(0) - expect(await page.getByText(/^Explain event sourcing in one sentence\.Your parent agent id is /).count()).toBe(0) + expect(await page.getByText(/^Explain event sourcing in one sentence\./).count()).toBe(0) releaseCatalog() await page.getByRole('button', { name: `Switch subagent: ${LABEL}` }).waitFor({ timeout: 15_000 }) const input = page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }) @@ -549,7 +716,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(tripwire.warnings).toEqual([]) }) - it('opens an unavailable persisted grandchild after recording the available child', async () => { + it('opens a persisted grandchild with input enabled while its creator is offline', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-grandchild')) await page.getByRole('button', { name: '1 subagent' }).hover() const tree = page.getByRole('tree', { name: 'Subagent sessions' }) @@ -562,7 +729,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = const clickArea = nestedRow.locator(':scope > div') expect(await clickArea.count()).toBe(1) const [menuBox, clickAreaBox] = await Promise.all([ - tree.locator('..').boundingBox(), + page.locator('[data-subagent-panel]').boundingBox(), clickArea.boundingBox(), ]) expect(menuBox).not.toBeNull() @@ -570,27 +737,23 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect([ Math.round(clickAreaBox!.x - menuBox!.x), Math.round(menuBox!.x + menuBox!.width - clickAreaBox!.x - clickAreaBox!.width), - // The outer menu padding insets the scrollable tree rows. - ]).toEqual([4, 4]) + // Menu padding plus the branchless row's one-pixel leading inset. + ]).toEqual([7, 6]) await compareOrRefreshGolden( BRANCHLESS_EXPECTED, await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE, ) - await nestedRow.click() - await page.getByText('The parent session is offline; reopen it to continue sending messages.').waitFor() - // The offline banner renders from the descriptor alone, so it says nothing - // about the transcript below it. The golden pins that transcript, and - // `captureStableAria` calls two identical polls stable — including two of - // "Loading history…". Wait for the message the golden asserts. + await nestedRow.getByText(grandchildId, { exact: true }).click() await page.getByText(NESTED_PROMPT).waitFor() + expect(await page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }).isEnabled()).toBe(true) const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' }) const crumbs = await hierarchy.getByRole('button').allTextContents() expect(crumbs.slice(-2)).toEqual([LABEL, NESTED_LABEL]) expect(scaffold.ctx.agents.get(childId)).toBeUndefined() expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() await compareOrRefreshGolden( - UNAVAILABLE_GRANDCHILD_EXPECTED, + GRANDCHILD_EXPECTED, await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd), MODE, ) @@ -602,7 +765,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = .getByRole('treeitem', { name: /Ask a research subagent to/ }) await parentSession.click() await page.getByRole('button', { name: '2 subagents' }).hover() - await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).getByText(oneShotId, { exact: true }).click() await page.getByText('One-shot tasks do not accept follow-ups; review the full execution record here.').waitFor() expect(scaffold.ctx.agents.get(oneShotId)).toBeUndefined() }) @@ -613,7 +776,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = .getByRole('treeitem', { name: /Ask a research subagent to/ }) .click() await page.getByRole('button', { name: '2 subagents' }).hover() - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(childId, { exact: true }).click() await page.getByRole('textbox', { name: 'Message or run a task, / commands, @ files or sessions' }).waitFor() const forkResponse = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/fork') @@ -642,7 +805,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = const sessions = page.getByRole('tree', { name: 'Sessions' }) await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click() await page.getByRole('button', { name: '2 subagents' }).hover() - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(childId, { exact: true }).click() await page.locator('[data-composer-input][contenteditable="true"]').first().waitFor() expect(scaffold.ctx.agents.get(childId)).toBeUndefined() @@ -659,7 +822,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await sessions.getByRole('treeitem', { name: /Ask a research subagent to/ }).click() await page.getByRole('button', { name: '2 subagents' }).press('ArrowDown') - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(childId, { exact: true }).click() const input = page.locator('[data-composer-input][contenteditable="true"]').first() await input.waitFor() const promptResponse = page.waitForResponse(response => @@ -683,6 +846,56 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(scaffold.ctx.agents.get(forkId)).not.toBeUndefined() await expect.poll(() => scaffold.ctx.agents.get(childId), { timeout: 10_000 }).toBeUndefined() }) + + it('shows shared tasks only in the root conversation while keeping child navigation', async () => { + const parent = scaffold.ctx.agents.get(parentId) + if (parent === undefined) throw new Error('task-board fixture requires the live parent') + const enabled = scaffold.ctx.agentTeams.isEnabled(parent) + onTestFinished(() => scaffold.ctx.agentTeams.setEnabled(parent, enabled)) + await scaffold.ctx.agentTeams.setEnabled(parent, true) + await scaffold.ctx.agentTeams.createTask(parent, { + subject: 'Root-only shared task', description: 'Inspect from the root conversation.', writeScopes: [], + }) + await page.getByRole('tree', { name: 'Sessions' }) + .getByRole('treeitem', { name: /Ask a research subagent to/ }).click() + await page.getByRole('button', { name: '2 subagents', exact: true }).click() + await page.locator('[data-team-panel]').getByText('Root-only shared task', { exact: true }).waitFor() + const rootHeader = page.locator('[data-subagent-section-header]') + expect(await rootHeader.textContent()).toBe('Subagents1 completed\u2002·\u20021 not running') + expect(await rootHeader.getByRole('button').count()).toBe(0) + expect(await rootHeader.locator('[data-icon="dsw-icon-users-outline-regular"]').count()).toBe(1) + const progress = await rootHeader.textContent() + await page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).click() + await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor() + expect(await rootHeader.textContent()).toBe(progress) + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).getByText(childId, { exact: true }).click() + const switcher = page.getByRole('button', { name: `Switch subagent: ${LABEL}`, exact: true }) + await switcher.click() + const panel = page.locator('[data-subagent-panel]') + await panel.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }).waitFor() + expect(await panel.locator('[data-team-panel]').count()).toBe(0) + expect(await panel.evaluate(element => element.getBoundingClientRect().width)).toBe(360) + const header = panel.locator('[data-subagent-section-header]') + expect(await header.count()).toBe(0) + expect(await switcher.textContent()).toBe(LABEL) + const currentRow = panel.getByRole('treeitem', { name: new RegExp(LABEL) }) + const currentCheck = currentRow.locator('[data-subagent-current]') + expect(await currentRow.getAttribute('aria-current')).toBe('true') + expect(await currentCheck.getAttribute('aria-hidden')).toBe('true') + expect(await currentCheck.evaluate(element => element.tagName)).toBe('SPAN') + expect(await currentCheck.locator('button, [role="button"], [tabindex]').count()).toBe(0) + expect(await currentRow.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(0) + const otherRow = panel.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }) + expect(await otherRow.locator('[data-subagent-current]').count()).toBe(0) + expect(await otherRow.getByRole('button', { name: `Open ${ONE_SHOT_LABEL} in sidebar`, exact: true }).isEnabled()).toBe(true) + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/subagent-conversation/navigation-only.expected.md', import.meta.url)), + await captureStableAria(page, '[data-subagent-panel]', scaffold.workspaceCwd), MODE, + ) + await page.keyboard.press('Escape') + }) + + }) describe('web e2e: migration-required subagent catalog', () => { @@ -795,7 +1008,7 @@ describe('web e2e: migration-required subagent catalog', () => { expect(observe.mock.calls.some(([id]) => id === childId || id === grandchildId)).toBe(false) expect(projections).not.toHaveBeenCalled() - await childRow.click() + await childRow.getByText(childId, { exact: true }).click() await page.getByRole('button', { name: `Switch subagent: ${childLabel}`, exact: true }).waitFor() await page.getByRole('button', { name: '1 subagent', exact: true }).hover() const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) }) diff --git a/apps/web/tests/subagent-fork-schedule.snapshot.ts b/apps/web/tests/subagent-fork-schedule.snapshot.ts index 62f42cb69a..00678b48f4 100644 --- a/apps/web/tests/subagent-fork-schedule.snapshot.ts +++ b/apps/web/tests/subagent-fork-schedule.snapshot.ts @@ -48,7 +48,7 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a const activation = await scaffold.ctx.subagents.startActivation({ provider: 'fork', label: 'Check child reminder refusal', delivery: 'caller', signal: new AbortController().signal, - request: { parent, prompt: [...childPrompt.data.content] }, + parent, prompt: [...childPrompt.data.content], }) try { await activation.result @@ -81,9 +81,9 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a const results = child.snapshotEvents().slice(child.inheritedEventCount) .filter(event => event.type === 'tool/result') expect(results.map(event => event.data.message.content)).toEqual(Array.from({ length: 4 }, () => [ - { type: 'text', text: '{"code":"subagent_session","message":"A delegated subagent cannot use reminders."}' }, + { type: 'text', text: '{"code":"subagent_session","message":"A delegated subagent cannot use scheduled tasks."}' }, ])) - expect(await scaffold.ctx.schedule.list({ sessionId: child.id })).toEqual([]) + expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([]) if (MODE === 'refresh') { const replacements = refreshFixtureReplacements(raw.map((content, index) => ({ diff --git a/apps/web/tests/subagent-interrupt-ui.e2e.ts b/apps/web/tests/subagent-interrupt-ui.e2e.ts index 7afeaa9a10..8c5f8fb1ea 100644 --- a/apps/web/tests/subagent-interrupt-ui.e2e.ts +++ b/apps/web/tests/subagent-interrupt-ui.e2e.ts @@ -1,7 +1,7 @@ // Web e2e scenario: the composer's independent Stop interrupts a running // continuable child. The child holds its model turn open through a replay -// hang entry; the browser proves Send and Stop coexist, the parent-offline -// disabled-Send-with-Stop composer, the subagents/interruptByParent +// hang entry; the browser proves Send and Stop coexist regardless of the +// creator's list availability, the subagents/interruptByUser // (never session.cancel) transport, the parked follow-up, and the FIFO resume // on a waking send. // @@ -144,7 +144,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await connectFreshWorkspace(page, scaffold.workspaceCwd) - const root = scaffold.ctx.agents.roots()[0] + const root = scaffold.ctx.agents.list().filter(agent => agent.session.header.origin !== 'subagent')[0] if (root === undefined) throw new Error('fresh workspace did not publish its parent Agent') parent = root // The child's first model call claims the primary override and holds. @@ -153,7 +153,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co provider: 'spawn', label: LABEL, signal: new AbortController().signal, - request: { prompt: [{ type: 'text', text: INITIAL }], parent }, + prompt: [{ type: 'text', text: INITIAL }], parent, }) childId = started.childId await waitFor(() => existsSync(readyFile), 'the held child turn to open') @@ -188,7 +188,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co if (failures.length > 1) throw new AggregateError(failures, 'subagent interrupt UI teardown failed') }) - it('interrupts the live child through the parent-offline composer', async () => { + it('queues and interrupts the live child despite its creator being listed offline', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-interrupt-offline')) // The parent is unavailable in the Session list while the child stays live. const pattern = '**/api/session/list' @@ -210,31 +210,22 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) acknowledgeReloadConnectionLoss(tripwire, warningStart) await page.getByRole('button', { name: /1 subagent/ }).click() - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() - const input = page.getByRole('textbox', { - name: 'Parent session offline; sending is unavailable but you can still stop the run', - }) + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter') + const input = page.locator('[data-composer-input]').first() await input.waitFor({ timeout: 15_000 }) - await page.getByText(/^Explain event sourcing in one sentence\.Your parent agent id is /) + await page.getByText(/^Explain event sourcing in one sentence\./) .waitFor({ timeout: 15_000 }) - expect(await input.isDisabled()).toBe(true) + expect(await input.isDisabled()).toBe(false) const stop = page.getByRole('button', { name: 'Stop generating' }) expect(await stop.count()).toBe(1) expect(await stop.isEnabled()).toBe(true) - const send = page.getByRole('button', { name: 'Send message' }) - expect(await send.count()).toBe(1) - expect(await send.isDisabled()).toBe(true) - // Keep the continuable Activation resident after this first abort. The - // direct setup queue also proves the ordinary row controls remain - // available while this parent-offline composer cannot submit new input. - await scaffold.ctx.subagents.prompt({ - requestId: 'interrupt-ui-rearm' as SubagentPromptRequestId, - parentSessionId: parent.id, - childSessionId: childId, - mode: 'continuable', - delivery: 'queue', - content: [{ type: 'text', text: REARM }], - }, new AbortController().signal) + const promptResponse = page.waitForResponse(response => + new URL(response.url()).pathname === '/api/subagents/prompt') + await input.fill(REARM) + const send = page.getByRole('button', { name: 'Queue message' }) + expect(await send.isEnabled()).toBe(true) + await send.click() + expect(((await (await promptResponse).json()) as { result: { ok: boolean } }).result).toMatchObject({ ok: true }) await page.getByRole('button', { name: 'Edit queued message' }).waitFor({ timeout: 15_000 }) expect(await page.getByRole('button', { name: 'Remove queued message' }).count()).toBe(1) expect(await page.getByRole('button', { name: 'Steer queued message' }).count()).toBe(1) @@ -246,7 +237,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co const aborted = waitForAbortedTurn(scaffold, childId) const interruptResponse = page.waitForResponse(response => - new URL(response.url()).pathname === '/api/subagents/interruptByParent') + new URL(response.url()).pathname === '/api/subagents/interruptByUser') await stop.click() expect(((await (await interruptResponse).json()) as { result: { ok: boolean; value?: { accepted: boolean } } @@ -256,12 +247,10 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co await expect.poll(() => scaffold.ctx.agents.get(childId)?.status, { timeout: 15_000 }).toBe('idle') // Wake the parked setup message only after cancellation converges. A - // second hang keeps the parent-available case independent from this stop. + // second hang keeps the next interrupt case independent from this stop. await scaffold.ctx.subagents.prompt({ requestId: 'interrupt-ui-rearm-wake' as SubagentPromptRequestId, - parentSessionId: parent.id, childSessionId: childId, - mode: 'continuable', delivery: 'queue', content: [{ type: 'text', text: REARM_WAKE }], }, new AbortController().signal) @@ -272,9 +261,8 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co } }, 60_000) - it('interrupts through subagents/interruptByParent, parks the follow-up, and resumes it FIFO', async () => { + it('interrupts through subagents/interruptByUser, parks the follow-up, and resumes it FIFO', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-interrupt-flow')) - // A new connection reloads the truthful parent-availability hint. const warningStart = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) @@ -282,7 +270,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co await page.getByRole('navigation', { name: 'Session hierarchy' }) .getByRole('button').first().click() await page.getByRole('button', { name: /1 subagent/ }).click() - await page.getByRole('treeitem', { name: new RegExp(LABEL) }).click() + await page.getByRole('treeitem', { name: new RegExp(LABEL) }).press('Enter') // A live continuable child advertises the ordinary steer-all gesture, so // that placeholder is the composer's accessible name in this window. It // changes back as the queue drains, so later interactions address the @@ -343,7 +331,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co const stop = page.getByRole('button', { name: 'Stop generating' }) expect(await stop.count()).toBe(1) const interruptResponse = page.waitForResponse(response => - new URL(response.url()).pathname === '/api/subagents/interruptByParent') + new URL(response.url()).pathname === '/api/subagents/interruptByUser') await stop.click() expect(((await (await interruptResponse).json()) as { result: { ok: boolean; value?: { accepted: boolean } } @@ -378,7 +366,7 @@ describe.skipIf(MODE === 'record')('web e2e: composer interrupt for a running co ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []) : []) expect(userTexts[0]).toBe(INITIAL) - expect(userTexts[1]).toMatch(/^Your parent agent id is .+send_message\(\{ agent_id: /) + expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./) expect(userTexts.slice(2)).toEqual([REARM, REARM_WAKE, EDITED_FOLLOWUP, WAKING]) const imageMessage = events.find(event => event.type === 'user/message' && event.data.content.some(block => block.type === 'image')) diff --git a/apps/web/tests/subagent-interrupt.e2e.ts b/apps/web/tests/subagent-interrupt.e2e.ts index a1b1284a19..526e115437 100644 --- a/apps/web/tests/subagent-interrupt.e2e.ts +++ b/apps/web/tests/subagent-interrupt.e2e.ts @@ -70,7 +70,7 @@ function textCompletion(text: string): object { } } -describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over the real composition', () => { +describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByUser over the real composition', () => { let scaffold: WebScaffold let sidecarRoot: string let readyFile: string @@ -113,7 +113,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over th provider: 'spawn', label: 'event-sourcing researcher', signal: new AbortController().signal, - request: { prompt: [{ type: 'text', text: INITIAL }], parent }, + prompt: [{ type: 'text', text: INITIAL }], parent, }) childId = started.childId // The hang entry writes readyFile after its prefix chunks, immediately @@ -134,9 +134,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over th const queued = await remote<{ messageId: string }>(scaffold, 'subagents/prompt', { request: { requestId: randomUUID(), - parentSessionId: parentId, childSessionId: childId, - mode: 'continuable', delivery: 'queue', content: [{ type: 'text', text: FOLLOWUP }], }, @@ -144,10 +142,8 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over th expect(queued).toMatchObject({ ok: true }) const settled = scaffold.whenTurnSettled() - const interrupted = await remote<{ accepted: true }>(scaffold, 'subagents/interruptByParent', { + const interrupted = await remote<{ accepted: true }>(scaffold, 'subagents/interruptByUser', { childSessionId: childId, - parentSessionId: parentId, - mode: 'continuable', }) expect(interrupted).toMatchObject({ ok: true, value: { accepted: true } }) // accepted acknowledges the admitted cancel, not quiescence: wait for the @@ -169,9 +165,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over th const waking = await remote<{ messageId: string }>(scaffold, 'subagents/prompt', { request: { requestId: randomUUID(), - parentSessionId: parentId, childSessionId: childId, - mode: 'continuable', delivery: 'queue', content: [{ type: 'text', text: WAKING }], }, @@ -189,7 +183,7 @@ describe.skipIf(MODE === 'record')('web e2e: subagents/interruptByParent over th ? event.data.content.flatMap(block => block.type === 'text' ? [block.text] : []) : []) expect(userTexts[0]).toBe(INITIAL) - expect(userTexts[1]).toMatch(/^Your parent agent id is .+send_message\(\{ agent_id: /) + expect(userTexts[1]).toMatch(/^Your final answer is delivered automatically if your parent is still online\./) expect(userTexts.slice(2)).toEqual([FOLLOWUP, WAKING]) const turnEndKinds = events .filter(event => event.type === 'turn/end') diff --git a/apps/web/tests/subagent-result-notice.e2e.ts b/apps/web/tests/subagent-result-notice.e2e.ts new file mode 100644 index 0000000000..cff9482035 --- /dev/null +++ b/apps/web/tests/subagent-result-notice.e2e.ts @@ -0,0 +1,129 @@ +/** Keyless browser coverage of structured subagent outcomes and historical notice fallback. */ +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { chromium, type Browser, type BrowserContext } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { createAssistantMessage, createUserMessage } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import { createSettlementMessage } from '@deepseek-ai/dsh-subagent/src/continuation-messages.ts' +import type { SubagentStopReason } from '@deepseek-ai/dsh-subagent' +import { + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, watchConsole, webSnapshotMode, +} from './scaffold.ts' +import { connectFreshWorkspace, connectFreshWorkspaceZh } from './support.ts' + +const DIR = fileURLToPath(new URL('./expected/subagent-result-notice/', import.meta.url)) +const MODE = webSnapshotMode() +const OUTPUT = '## Research result\nThe original child reply stays available.' +const OUTCOMES = [ + { reason: 'completed', en: 'Subagent run completed', zh: '子智能体已完成任务' }, + { reason: 'aborted', en: 'Subagent run stopped', zh: '子智能体任务已停止' }, + { reason: 'error', en: 'Subagent run failed', zh: '子智能体执行失败' }, + { reason: 'max-tokens', en: 'Subagent reached the token limit', zh: '子智能体已达 token 上限' }, + { reason: 'refusal', en: 'Subagent declined the task', zh: '子智能体拒绝执行' }, +] as const satisfies readonly { reason: SubagentStopReason; en: string; zh: string }[] + +describe.skipIf(MODE === 'record')('web e2e: subagent result notices', () => { + let browser: Browser + beforeAll(async () => { browser = await chromium.launch() }) + afterAll(async () => { await browser?.close() }) + + it.each(['en', 'zh'] as const)('shows recorded outcomes and preserves notice bodies in %s', async (locale) => { + const scaffold = await launchWebScaffold() + let context: BrowserContext | undefined + try { + context = await browser.newContext({ + locale: locale === 'en' ? 'en-US' : 'zh-CN', timezoneId: 'Asia/Shanghai', viewport: { width: 1280, height: 900 }, + }) + const page = await context.newPage() + const tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await (locale === 'en' ? connectFreshWorkspace : connectFreshWorkspaceZh)(page, scaffold.workspaceCwd) + const agent = scaffold.ctx.agents.list()[0] + if (agent === undefined) throw new Error('Notice fixture has no connected Agent') + const session = agent.session + const appendTurn = (turn: number, message: ReturnType): void => { + const waking = message.source.kind !== 'user' + if (waking) session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, inserted: [message] }) + session.append('turn/start', { turn }) + if (waking) session.append('agent/inbox/spliced', { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }) + session.append('step/start', { turn, step: 1 }) + session.append('user/message', message, { surfaceOp: 'append' }) + session.append('assistant/message', { + turn, step: 1, stream: [], message: createAssistantMessage({ + content: [{ type: 'text', text: `Acknowledged ${turn}.` }], source: { provider: 'fixture', model: 'fixture' }, + }), + }, { surfaceOp: 'append' }) + session.append('step/end', { turn, step: 1 }) + session.append('turn/end', { turn, reason: { kind: 'completed' } }) + } + appendTurn(1, createUserMessage({ content: [{ type: 'text', text: 'Inspect child execution results.' }], source: { kind: 'user' } })) + const childId = SessionId('notice-result-child') + const notices: { title: string; message: ReturnType }[] = OUTCOMES.map(outcome => ({ + title: outcome[locale], + message: createSettlementMessage(childId, { + stopReason: outcome.reason, output: [{ type: 'text', text: OUTPUT }], + }), + })) + notices.push({ + title: OUTCOMES[0][locale], + message: createSettlementMessage(childId, { stopReason: 'completed', output: [] }), + }) + notices.push({ + title: locale === 'en' ? 'Subtask status updated' : '子任务状态更新', + message: createUserMessage({ + source: { kind: 'subagent-settled', form: 'notice', senderSessionId: childId, summary: 'Background subagent finished.' }, + content: [{ type: 'text', text: 'Background subagent finished.' }], + }), + }) + for (const [index, notice] of notices.entries()) appendTurn(index + 2, notice.message) + await scaffold.ctx.sessions.flush(session) + const snapshots: string[] = [] + for (const [index, notice] of notices.entries()) { + const selector = `[data-chat-turn="${index + 2}"] [data-turn-trigger]` + const card = page.locator(selector) + await card.waitFor({ state: 'attached' }) + const header = card.locator('button').first() + await expect.poll(() => header.locator(':scope > span').nth(1).textContent()).toBe(notice.title) + await header.click() + const original = notice.message.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('') + expect(await card.locator('[data-context-text]').textContent()).toBe(original) + snapshots.push(await captureStableAria(page, selector, scaffold.workspaceCwd)) + await header.click() + } + await page.setViewportSize({ width: 390, height: 844 }) + for (const card of await page.locator('[data-turn-trigger]').all()) { + const geometry = await card.evaluate((element) => { + const header = element.querySelector('button')! + const title = header.querySelectorAll('span')[1]! + const time = header.querySelector('time')! + return { + fits: element.scrollWidth <= element.clientWidth, + separate: title.getBoundingClientRect().right <= time.getBoundingClientRect().left, + } + }) + expect(geometry).toEqual({ fits: true, separate: true }) + } + const warningCount = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await page.locator('[data-turn-trigger]').first().waitFor({ state: 'attached' }) + for (const [index, notice] of notices.entries()) { + await expect.poll(() => page.locator(`[data-chat-turn="${index + 2}"] [data-turn-trigger] > button`).textContent()) + .toContain(notice.title) + } + acknowledgeReloadConnectionLoss(tripwire, warningCount) + if (MODE === 'refresh') await mkdir(DIR, { recursive: true }) + await compareOrRefreshGolden(join(DIR, `${locale}.expected.md`), snapshots.join('\n\n'), MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + } finally { + try { await context?.close() } finally { await scaffold.close() } + } + }) + + it('keeps the fixture inventory closed', async () => { + await assertFixtureInventory(DIR, ['en.expected.md', 'zh.expected.md']) + }) +}) diff --git a/apps/web/tests/subagent-summary.e2e.ts b/apps/web/tests/subagent-summary.e2e.ts new file mode 100644 index 0000000000..5d3c564b09 --- /dev/null +++ b/apps/web/tests/subagent-summary.e2e.ts @@ -0,0 +1,271 @@ +/** Keyless browser coverage of subagent task summaries and durable creation receipts. */ +import { mkdir } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Agent, AssistantStreamFrame } from '@deepseek-ai/dsh-agent' +import { + AssistantStreamAccumulator, LlmAttemptId, ToolCallId, + createAssistantMessage, createToolResultMessage, createUserMessage, + type StreamChunk, +} from '@deepseek-ai/dsh-llm' +import type { SessionEvent } from '@deepseek-ai/dsh-session' +import type { Browser, Locator, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { connectFreshWorkspace, expandOwningTurnProcess, newEnglishPage } from './support.ts' + +const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/subagent-summary/', import.meta.url)) +const MODE = webSnapshotMode() +const DESCRIPTION = 'Review subagent task summaries' +const PROMPT = 'Inspect the subagent tool card across its lifecycle.\nCheck streaming arguments, creation receipts, and restored history.\nReturn findings without changing unrelated files.' +const SOURCE = { provider: 'deepseek-official', model: 'deepseek-v4-flash' } + +async function snapshotGolden(name: string, actual: string): Promise { + if (MODE === 'refresh') await mkdir(SNAPSHOT_DIR, { recursive: true }) + await compareOrRefreshGolden(join(SNAPSHOT_DIR, `${name}.expected.md`), actual, MODE) +} + +function startTurn(agent: Agent, turn: number): void { + agent.session.append('turn/start', { turn }) + agent.session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: `Inspect subagent summary case ${turn}.` }], source: { kind: 'user' }, + }), { surfaceOp: 'append' }) + agent.session.append('step/start', { turn, step: 1 }) +} + +function appendCall(agent: Agent, turn: number, callId: ToolCallId, args: string, name = 'subagent'): SessionEvent<'tool/call'> { + agent.session.append('assistant/message', { + turn, step: 1, stream: [], + message: createAssistantMessage({ + content: [{ type: 'tool-call', id: callId, name, arguments: args }], source: SOURCE, + }), + }, { surfaceOp: 'append' }) + return agent.session.append('tool/call', { turn, step: 1, callId, name, arguments: args }) +} + +function finishCall(agent: Agent, call: SessionEvent<'tool/call'>, text: string, isError = false, meta?: SessionEvent<'tool/result'>['data']['meta']): void { + const { turn, step, callId } = call.data + agent.session.append('tool/result', { + turn, step, message: createToolResultMessage({ callId, content: [{ type: 'text', text }], isError }), + ...meta === undefined ? {} : { meta }, + }, { surfaceOp: 'append', sourceEventSeqs: [call.seq] }) + agent.session.append('step/end', { turn, step }) + agent.session.append('turn/end', { turn, reason: { kind: 'completed' } }) +} + +function toolSelector(callId: ToolCallId): string { + return `[data-chat-call-id="${callId}"] [data-tool="subagent"]` +} + +async function expectSummary(card: Locator, text: string): Promise { + const header = card.locator('[data-disclosure-row]').first() + await expect.poll(() => header.textContent(), { timeout: 10_000 }).toBe(`Create subagent${text}`) +} + +async function expandTask(card: Locator, prompt: string): Promise { + await expandOwningTurnProcess(card.page(), card) + const toggle = card.locator('[data-expandable]').first() + if (await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click() + const task = card.locator('details').filter({ has: card.page().locator('summary', { hasText: /^Task$/u }) }) + await task.waitFor() + if (await task.getAttribute('open') === null) await task.locator('summary').click() + await expect.poll(() => task.locator('p').textContent()).toBe(prompt) +} + +describe.skipIf(MODE === 'record')('web e2e: subagent task summary', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + let agent: Agent + + beforeAll(async () => { + scaffold = await launchWebScaffold() + browser = await chromium.launch() + page = await newEnglishPage(browser) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.locator('[class*="frame"]').waitFor() + await connectFreshWorkspace(page, scaffold.workspaceCwd) + const connected = scaffold.ctx.agents.list()[0] + if (connected === undefined) throw new Error('Subagent summary fixture has no connected Agent') + agent = connected + }) + + afterAll(async () => { + try { await browser?.close() } finally { await scaffold?.close() } + }) + + it('streams the description and preserves it through creation and restored history', async () => { + const callId = ToolCallId('subagent-summary-described') + const selector = toolSelector(callId) + const card = page.locator(selector) + const snapshots: string[] = [] + const capture = async (stage: string): Promise => { + await expandOwningTurnProcess(page, card) + snapshots.push(`## ${stage}\n\n${await captureStableAria(page, selector, scaffold.workspaceCwd)}`) + } + startTurn(agent, 1) + await scaffold.ctx.sessions.flush(agent.session) + await page.locator('[data-chat-turn="1"]').getByText('Inspect subagent summary case 1.', { exact: true }).waitFor() + + const attemptId = LlmAttemptId('subagent-summary-stream') + const stream = new AssistantStreamAccumulator() + let revision = 0 + let index = 0 + const emit = (frame: AssistantStreamFrame): void => { scaffold.ctx.emit('agent/assistant-stream', { agent, frame }) } + const push = (chunk: StreamChunk): void => { + const time = Date.now() + stream.push({ time, chunk }) + emit({ type: 'chunk', attemptId, revision: ++revision, index: index++, time, chunk }) + } + emit({ type: 'start', attemptId, revision: ++revision, turn: 1, step: 1 }) + push({ type: 'block-start', index: 0, blockType: 'tool-call' }) + push({ type: 'tool-call-delta', index: 0, id: callId, name: 'subagent', argumentsDelta: `{"prompt":${JSON.stringify(PROMPT)},` }) + await card.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, card) + await expect.poll(() => card.getAttribute('data-state')).toBe('preparing') + await expectSummary(card, '') + await capture('Preparing without description') + push({ type: 'tool-call-delta', index: 0, id: callId, argumentsDelta: '"description":"Review subagent' }) + await expectSummary(card, 'Review subagent') + push({ type: 'tool-call-delta', index: 0, id: callId, argumentsDelta: ' task summaries\\nAdditional description context' }) + await expectSummary(card, DESCRIPTION) + await capture('Preparing with partial description') + push({ type: 'tool-call-delta', index: 0, id: callId, argumentsDelta: '"}' }) + const args = JSON.stringify({ prompt: PROMPT, description: `${DESCRIPTION}\nAdditional description context` }) + const block = { type: 'tool-call' as const, id: callId, name: 'subagent', arguments: args } + push({ type: 'block-end', index: 0, block }) + push({ type: 'finish', reason: { kind: 'tool-calls' } }) + const message = agent.session.append('assistant/message', { + turn: 1, step: 1, stream: [...stream.snapshot()], + message: createAssistantMessage({ content: [block], source: SOURCE }), + }, { surfaceOp: 'append' }) + emit({ type: 'end', attemptId, revision: ++revision, index, outcome: { kind: 'committed', eventType: 'assistant/message', seq: message.seq } }) + const call = agent.session.append('tool/call', { turn: 1, step: 1, callId, name: 'subagent', arguments: args }) + await scaffold.ctx.sessions.flush(agent.session) + await expect.poll(() => card.getAttribute('data-state')).toBe('running') + await expectSummary(card, DESCRIPTION) + await capture('Running') + + finishCall(agent, call, 'Delegation accepted.', false, { kind: 'activation', subagentId: 'child-foo' }) + await scaffold.ctx.sessions.flush(agent.session) + await expect.poll(() => card.getAttribute('data-state')).toBe('ok') + await expectSummary(card, DESCRIPTION) + await capture('Created') + await expandTask(card, PROMPT) + await expectSummary(card, DESCRIPTION) + expect(await card.getByText('Agent response', { exact: true }).count()).toBe(0) + await card.getByText('Started', { exact: true }).waitFor() + expect(await card.locator('dt').allTextContents()).toEqual(['Agent task description', 'ID']) + expect(await card.locator('dd').allTextContents()).toEqual([`${DESCRIPTION}\nAdditional description context`, 'child-foo']) + await capture('Creation receipt and complete task') + + const beforeReload = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await card.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, card) + await expectSummary(card, DESCRIPTION) + await expandTask(card, PROMPT) + await expectSummary(card, DESCRIPTION) + expect(await card.getByText('Agent response', { exact: true }).count()).toBe(0) + await capture('Restored creation receipt') + acknowledgeReloadConnectionLoss(tripwire, beforeReload) + await snapshotGolden('lifecycle', snapshots.join('\n\n')) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('falls back to the prompt, keeps synchronous replies in details, and preserves errors', async () => { + const cases = [ + { id: 'fallback', args: { prompt: 'Review the fallback summary.\nKeep the complete task in details.' }, summary: 'Review the fallback summary.', result: 'started subagent fallback-worker' }, + { id: 'reply', args: { description: 'Check synchronous agent reply', prompt: 'Review the synchronous report.\nKeep every instruction available.' }, summary: 'Check synchronous agent reply', result: 'The synchronous agent found two issues.\nBoth are documented in the report.' }, + { id: 'title-only', args: {}, summary: '', result: 'started subagent empty-worker' }, + { id: 'error', args: { description: 'Delegate a failing task', prompt: 'Attempt the requested delegation.' }, summary: 'Subagent capacity exceeded', result: 'Subagent capacity exceeded\nWait for an active agent to finish.', error: true }, + ] + const snapshots: string[] = [] + for (const [index, fixture] of cases.entries()) { + const turn = index + 2 + const callId = ToolCallId(`subagent-summary-${fixture.id}`) + const selector = toolSelector(callId) + const card = page.locator(selector) + startTurn(agent, turn) + const call = appendCall(agent, turn, callId, JSON.stringify(fixture.args)) + await scaffold.ctx.sessions.flush(agent.session) + await card.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, card) + await expectSummary(card, fixture.args.description ?? fixture.args.prompt?.split('\n')[0] ?? '') + finishCall(agent, call, fixture.result, fixture.error) + await scaffold.ctx.sessions.flush(agent.session) + await expect.poll(() => card.getAttribute('data-state')).toBe(fixture.error === true ? 'error' : 'ok') + await expectSummary(card, fixture.summary) + if (fixture.args.prompt !== undefined && fixture.error !== true) { + await expandTask(card, fixture.args.prompt) + await expectSummary(card, fixture.summary) + if (fixture.id === 'reply') { + await card.getByText('Agent response', { exact: true }).waitFor() + await card.getByText('The synchronous agent found two issues.', { exact: false }).waitFor() + await card.getByText('Both are documented in the report.', { exact: false }).waitFor() + expect(await card.getByText('Started', { exact: true }).count()).toBe(0) + } else expect(await card.getByText('Agent response', { exact: true }).count()).toBe(0) + } + await expandOwningTurnProcess(page, card) + snapshots.push(`## ${fixture.id}\n\n${await captureStableAria(page, selector, scaffold.workspaceCwd)}`) + } + await snapshotGolden('variants', snapshots.join('\n\n')) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('presents fork creation with a distinct title, task summary, and restored receipt', async () => { + const name = 'subagent_fork' + const callId = ToolCallId('subagent-fork-summary') + const selector = `[data-chat-call-id="${callId}"] [data-tool="${name}"]` + const card = page.locator(selector) + const description = 'Review inherited conversation context' + const prompt = 'Summarize the earlier agreed requirements.\nDo not modify files.' + const snapshots: string[] = [] + const capture = async (stage: string): Promise => { + snapshots.push(`## ${stage}\n\n${await captureStableAria(page, selector, scaffold.workspaceCwd)}`) + } + const expectForkSummary = async (): Promise => { + await expect.poll(() => card.locator('[data-disclosure-row]').first().textContent()) + .toBe(`Fork subagent${description}`) + } + startTurn(agent, 6) + const call = appendCall(agent, 6, callId, JSON.stringify({ description, prompt }), name) + await scaffold.ctx.sessions.flush(agent.session) + await card.waitFor({ state: 'attached' }) + await expandOwningTurnProcess(page, card) + await expect.poll(() => card.getAttribute('data-state')).toBe('running') + await expectForkSummary() + await capture('Running') + finishCall(agent, call, 'started subagent fork-worker') + await scaffold.ctx.sessions.flush(agent.session) + await expect.poll(() => card.getAttribute('data-state')).toBe('ok') + await expandTask(card, prompt) + await expectForkSummary() + expect(await card.locator('dt').allTextContents()).toEqual(['Agent task description', 'ID']) + expect(await card.locator('dd').allTextContents()).toEqual([description, 'fork-worker']) + expect(await card.getByText('Agent response', { exact: true }).count()).toBe(0) + await capture('Creation receipt and complete task') + const beforeReload = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + await card.waitFor({ state: 'attached' }) + await expandTask(card, prompt) + await expectForkSummary() + await capture('Restored creation receipt') + acknowledgeReloadConnectionLoss(tripwire, beforeReload) + await snapshotGolden('fork', snapshots.join('\n\n')) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }) + + it('keeps the fixture inventory closed', async () => { + await assertFixtureInventory(SNAPSHOT_DIR, ['lifecycle.expected.md', 'variants.expected.md', 'fork.expected.md']) + }) +}) diff --git a/apps/web/tests/support-timezone.e2e.ts b/apps/web/tests/support-timezone.e2e.ts index 37e4de79b1..706c96a49d 100644 --- a/apps/web/tests/support-timezone.e2e.ts +++ b/apps/web/tests/support-timezone.e2e.ts @@ -1,6 +1,6 @@ import { chromium } from 'playwright' import { expect, it } from 'vitest' -import { newEnglishPage } from './support.ts' +import { newEnglishPage, pinBrowserClock, pinHostClock, WEB_FIXTURE_TIME } from './support.ts' it.each(['UTC', 'America/Los_Angeles'])('isolates the recorded browser timezone from %s', async (hostTimeZone) => { const browser = await chromium.launch({ env: { ...process.env, TZ: hostTimeZone } }) @@ -20,3 +20,40 @@ it.each(['UTC', 'America/Los_Angeles'])('isolates the recorded browser timezone await browser.close() } }) + +it('keeps browser timers and animation frames live with the Host date pinned, including reload', async () => { + const originalNow = Date.now + const hostClock = pinHostClock() + try { + const browser = await chromium.launch() + try { + const page = await newEnglishPage(browser) + await pinBrowserClock(page) + await page.goto('data:text/html,clock') + let previousTime = WEB_FIXTURE_TIME + for (const reload of [false, true]) { + if (reload) await page.reload() + const now = await page.evaluate(() => Date.now()) + if (reload) expect(now).toBeGreaterThan(previousTime) + else expect(now).toBeGreaterThanOrEqual(previousTime) + expect(now).toBeLessThan(WEB_FIXTURE_TIME + 60_000) + previousTime = now + await page.evaluate(() => { + setTimeout(() => { document.body.dataset.timer = 'fired' }, 0) + requestAnimationFrame(() => { document.body.dataset.frame = 'fired' }) + }) + await expect.poll(() => page.evaluate(() => ({ + timer: document.body.dataset.timer, frame: document.body.dataset.frame, + })), { timeout: 5_000 }).toEqual({ timer: 'fired', frame: 'fired' }) + } + await page.close() + const nextPage = await newEnglishPage(browser) + expect(await nextPage.evaluate(() => Math.abs(Date.now() - new Date().getTime()))).toBeLessThan(100) + } finally { + await browser.close() + } + } finally { + hostClock.mockRestore() + } + expect(Date.now).toBe(originalNow) +}) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index ad741f474d..048e3e1f6d 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -25,6 +25,36 @@ export function experimentalBundleDescription(bundle: string, locale: string): s const installationRequire = createRequire(join(REPO_ROOT, 'apps/cli/package.json')) +/** + * Check the shared warning title, theme color, and compact body alignment. + * @param dialog - visible warning dialog under test. + */ +export async function assertWarningDialogLayout(dialog: Locator): Promise { + const layout = await dialog.evaluate((element) => { + const title = element.querySelector('h2')! + const icon = title.querySelector('svg')! + const paragraph = element.querySelector('p')! + const titleRect = title.getBoundingClientRect() + const bodyRect = paragraph.getBoundingClientRect() + const color = getComputedStyle(icon).color + const previous = icon.style.color + icon.style.color = 'var(--dsw-alias-state-warn-primary)' + const warningColor = getComputedStyle(icon).color + icon.style.color = previous + return { + decorative: icon.getAttribute('aria-hidden'), + matchesWarningColor: color === warningColor, + leftGap: Math.abs(bodyRect.left - titleRect.left), + topGap: bodyRect.top - titleRect.bottom, + } + }) + expect(layout.decorative).toBe('true') + expect(layout.matchesWarningColor).toBe(true) + expect(layout.leftGap).toBeLessThan(1) + expect(layout.topGap).toBeGreaterThanOrEqual(0) + expect(layout.topGap).toBeLessThanOrEqual(16) +} + /** * The built copy of a workspace package, as the dsh installation resolves it. * The Host plugins a scaffold profile loads run from built packages through diff --git a/apps/web/tests/tool-details.e2e.ts b/apps/web/tests/tool-details.e2e.ts index 3ada042ef2..8a51e66d44 100644 --- a/apps/web/tests/tool-details.e2e.ts +++ b/apps/web/tests/tool-details.e2e.ts @@ -55,7 +55,7 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => { // turn-tail create card carries the same `data-tool` marker without being // one of the keyed call views this case walks. const rows = page.locator('[data-chat-call-id] [data-tool]') - expect(await rows.count()).toBe(45) + expect(await rows.count()).toBe(50) for (const row of await rows.all()) { await row.getByRole('button', { expanded: false }).first().click() expect(await row.getByRole('listitem').count()).toBeGreaterThan(0) @@ -70,8 +70,10 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => { await expect.poll(() => schema.textContent()).toContain('"properties"') const callIds = [ ...Array.from({ length: 3 }, (_, index) => `details-call-${index + 1}`), - // The authored schedule_update round sits beside its schedule_create sibling. + // The authored schedule_update round sits beside its schedule_create sibling, and the rounds of the current + // Schedule tools follow them. 'details-call-3b', + ...['c', 'd', 'e', 'f', 'g'].map(suffix => `details-call-3${suffix}`), ...Array.from({ length: 41 }, (_, index) => `details-call-${index + 4}`), ] const snapshots = await Promise.all(callIds.map(id => @@ -79,9 +81,12 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => { const snapshot = snapshots.join('\n') await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) await page.setViewportSize({ width: 360, height: 800 }) - const card = page.locator('[data-chat-call-id] [data-tool="schedule_create"]') - expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) - const reminders = page.locator('[data-tool="schedule_list"]') + const cards = page.locator('[data-chat-call-id] [data-tool="schedule_create"]') + expect(await cards.count()).toBe(2) + for (const card of await cards.all()) { + expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + } + const reminders = page.locator('[data-chat-call-id="details-call-6"] [data-tool="schedule_list"]') await scrollIntoView(reminders) const list = reminders.getByRole('list').first() await list.evaluate((element) => { diff --git a/apps/web/tests/workflow-run.e2e.ts b/apps/web/tests/workflow-run.e2e.ts index e43a7c7fb8..7fbd53a759 100644 --- a/apps/web/tests/workflow-run.e2e.ts +++ b/apps/web/tests/workflow-run.e2e.ts @@ -220,7 +220,7 @@ describe.skipIf(MODE === 'record')('web e2e: durable workflow run in Chat', () = await page.getByRole('button', { name: '1 subagent', exact: true }).hover() const catalog = page.getByRole('tree', { name: 'Subagent sessions' }) - await catalog.getByRole('treeitem', { name: /snapshot-flow child 1/ }).click() + await catalog.getByRole('treeitem', { name: /snapshot-flow child 1/ }).press('Enter') await page.getByText(CHILD_PROMPT, { exact: true }).waitFor({ timeout: 15_000 }) expect(await page.locator('[data-composer-input][contenteditable="true"]').count()).toBe(1) }, 60_000) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 8d08af9f01..d10fb6e877 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -49,6 +49,8 @@ "tests/code-card-layout.e2e.ts", "tests/code-language.snapshot.ts", "tests/scaffold.ts", + "tests/subagent-summary.e2e.ts", + "tests/subagent-result-notice.e2e.ts", "tests/clock.e2e.ts", "tests/connection-recovery.e2e.ts", "tests/server-restart.e2e.ts", @@ -106,6 +108,7 @@ "tests/cua-permissions.e2e.ts", "tests/schedule-header.e2e.ts", "tests/schedule-phone.e2e.ts", + "tests/schedule-pickers.e2e.ts", "tests/worktree-opt-in.e2e.ts", "tests/session-inspector.e2e.ts", "tests/shared-inspector.e2e.ts", @@ -211,6 +214,7 @@ "tests/agent-preset-authoring.e2e.ts", "tests/shipped-composition.e2e.ts", "tests/schedule-after.e2e.ts", + "tests/schedule-manual.e2e.ts", "tests/feedback-command.e2e.ts", "tests/feedback-release.e2e.ts", "tests/agent-team-panel.e2e.ts", diff --git a/benchmarks/agent-continuation/child-catalog.worker.ts b/benchmarks/agent-continuation/child-catalog.worker.ts index aedb279937..34808c2d85 100644 --- a/benchmarks/agent-continuation/child-catalog.worker.ts +++ b/benchmarks/agent-continuation/child-catalog.worker.ts @@ -81,7 +81,12 @@ async function run(root: string, mode: string): Promise ctx.subagents.listChildren(PARENT_ID) + const readCatalog = async () => { + using observation = await ctx.sessionQuery.observeSession(PARENT_ID) + const catalog = observation.projections?.values.subagentCatalog + if (catalog === undefined) throw new Error('child-catalog projection is unavailable') + return catalog + } const cpuStart = process.cpuUsage() const start = performance.now() const first = await readCatalog() diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 72dc6b08a6..19453e15a9 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -21,8 +21,8 @@ en: 20ef882e44b06a10 zh: c10c3934ed5570e9 /deepseek-harness-architecture/events: - en: 693407efb233f961 - zh: 37b9dd0677d4405c + en: ddebac7cfd41ec73 + zh: 51e6d0866a9e7839 /deepseek-harness-architecture/turn-flow: en: 1a79a70b62c04cdb zh: c86d765e21430405 @@ -30,8 +30,8 @@ en: b3b63d8fe7cab9fe zh: 3703fcf30b1639d0 /deepseek-harness-architecture/capability-seams: - en: a5bc20c3f2a1b370 - zh: 91773a281410b2f4 + en: 1d425c445bfcc931 + zh: 834d486f88e68edf /deepseek-harness-architecture/where-new-behavior-goes: en: ee73b1861378b099 zh: 9a182be609485f67 diff --git a/docs/architecture.md b/docs/architecture.md index e3f5cd24a3..446c50e5bd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -66,15 +66,17 @@ Electron starts the private Desktop Host in Electron Node mode. The Host invokes ## Events -Events are the extension points, and picking the right domain is the first decision in most changes. +Events provide extension points in three domains. - **Session events** are durable facts appended to the log and broadcast through `session/event`. Use one when the fact must survive a reload. - **Agent events** (`agent/*`) carry a live `Agent`: inbox, step, status, request, validation, continuation. Use one to observe or intercept work in flight. - **Capability events** attach policy and adapters to a seam (`fs/*`, `tools/*`, `telemetry/*`) without importing the loop. -AgentLoop initializes Agents with rollback and awaits serial `agent/created` before queued work. Unload retains resources through Agent teardown; [agent-loop](../packages/core/agent-loop/README.md#understand-the-implementation) defines ordering. +Subagent Activations own runtime tree membership. -The [event map](event-producer-consumer.md) lists every event's producers and consumers. +AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; unload retains resources through teardown ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). + +[Event producers and consumers](event-producer-consumer.md). ## Turn flow @@ -137,7 +139,7 @@ A **seam** is a swappable capability with three roles: a **Service Definition** Seams are why one provider swap changes the whole product. Filesystem and subprocess providers share one execution world, so pointing them at a remote sandbox moves Bash, PTY, and LSP with them, with no provider forks. [Subagent providers](subsystems/subagent.md) vary just as widely behind one interface, from a fresh child agent to a delegated turn in another product. -[Experimental Agent Teams](subsystems/agent-team.md) exposes opt-in `ctx.agentTeams` coordination with durable roster and task state plus direct inbox messaging over continuable subagents. +[Agent Teams](subsystems/agent-team.md) adds task policy and a shared task board when enabled for a root Session. Ordinary subagent controls own identity, messaging, discovery, interruption, and inbox waiting. ## Where new behavior goes diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 4ab73a419d..275e1c863d 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -68,15 +68,17 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 ## 事件 -事件就是扩展点,而选对事件域是大多数改动的第一个决定。 +事件在三个域内提供扩展点。 - **会话事件**是追加到日志并通过 `session/event` 广播的持久事实。当某个事实必须在重新加载后仍然存在时,使用它。 - **Agent 事件**(`agent/*`)携带活跃 `Agent`:inbox、步骤、状态、请求、验证、续跑。要观察或拦截进行中的工作时,使用它。 - **能力事件**无需导入循环即可向某个 seam(`fs/*`、`tools/*`、`telemetry/*`)附加策略和适配器。 -AgentLoop 初始化 Agent,失败则回滚,并在启动已排队工作前等待串行 `agent/created`。卸载在 Agent teardown 期间保留所需资源;[agent-loop](../packages/core/agent-loop/README.zh.md#understand-the-implementation)定义顺序。 +Subagent Activation 拥有运行时树成员关系。 -[事件映射](event-producer-consumer.zh.md)列出每个事件的生产方与消费方。 +AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;卸载在 teardown 期间保留所需资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 + +[事件生产者与消费者](event-producer-consumer.zh.md)。 @@ -141,7 +143,7 @@ Session 消费方只了解当前逻辑格式。仅 header 的 `stat` 与 `list` seam 正是替换一个提供方就能改变整个产品的原因。文件系统与进程提供方共享同一个执行世界,因此把它们指向远程沙箱,也就把 Bash、PTY 和 LSP 一并搬了过去,无需提供方专用 fork。[subagent 提供方](subsystems/subagent.zh.md)在同一个接口之后同样千差万别,从新建一个子 agent,到把一个轮次委派给另一个产品。 -[实验性 Agent Teams](subsystems/agent-team.zh.md) 通过显式启用的 `ctx.agentTeams`,在可继续 subagent 之上提供持久 roster、任务状态和直接 inbox 消息协作。 +[Agent Teams](subsystems/agent-team.zh.md)在根 Session 开启后提供任务策略和共享任务板。普通 subagent 控制工具负责身份、通信、发现、中断和收件箱等待。 ## 新行为的归属位置 diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index d056d158fd..e9bc77d1c8 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 0f507529bbc3047f - zh: 48e0f1914573169c + en: d54a3c89ec68592e + zh: 33dde19d27ec939e diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 27aca49bea..b6ec3a0846 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -31,6 +31,8 @@ flowchart LR pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] + pkg_client_ui_cli_account["client-ui-cli-account"] + svc_cliAccounts["ctx.cliAccounts
CLI app accounts on the Plugins page"] svc_profileContext["ctx.profileContext
Launcher-owned profile data"] pkg_client_connection["client-connection"] svc_connection["ctx.connection
Authenticated browser transport"] @@ -270,9 +272,9 @@ flowchart LR pkg_experimental_speech_to_text["experimental-speech-to-text"] svc_speechToText["ctx.speechToText
Experimental speech recognition providers"] pkg_experimental_speech_to_text_sensevoice["experimental-speech-to-text-sensevoice"] - pkg_experimental_agent_team["experimental-agent-team"] + pkg_agent_team["agent-team"] svc_agentTeams["ctx.agentTeams
Agent Teams coordination domain"] - pkg_experimental_tool_agent_team["experimental-tool-agent-team"] + pkg_tool_agent_team["tool-agent-team"] pkg_experimental_claude_code_mods["experimental-claude-code-mods"] svc_claudeCodeMods["ctx.claudeCodeMods
Claude Code mods bridge"] pkg_inspector["inspector"] @@ -323,6 +325,7 @@ flowchart LR pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_preset_registry --> svc_agentPresets + pkg_agent_team --> svc_agentTeams pkg_api_gateway --> svc_typertGateway pkg_api_job_controller --> svc_jobController pkg_api_remote_access --> svc_remoteAccess @@ -346,6 +349,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_cli_account --> svc_cliAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -362,7 +366,6 @@ flowchart LR pkg_deepseek_account --> svc_deepseekAccount pkg_deepseek_account_platform --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions - pkg_experimental_agent_team --> svc_agentTeams pkg_experimental_api_speech_to_text --> svc_speechController pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse pkg_experimental_browser_use_playwright_mcp --> svc_browserUse @@ -492,7 +495,7 @@ flowchart LR svc_agentDefaultModel --> pkg_headless svc_agentLoop --> pkg_base svc_agentLoop --> pkg_sdk_minimal - svc_agentTeams --> pkg_experimental_tool_agent_team + svc_agentTeams --> pkg_tool_agent_team svc_agents --> pkg_acp svc_agents --> pkg_agent_loop svc_agents --> pkg_subagent @@ -664,6 +667,7 @@ flowchart LR | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. | +| `ctx.cliAccounts` | `service` | [`client-ui-cli-account`](../packages/client/ui-cli-account) | - | - | - | Holds the accounts CLI app plugins register and serves them to the Plugins page through one Remote; links and notices stay in the browser that started the operation. | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Owns browser authentication and shared HTTP request dispatch; API adapters register endpoints and streams. | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Providers map remote and change request URLs, look up change requests by head branch, and read status in batches; watchers of one change request share one polling loop. | @@ -732,7 +736,7 @@ flowchart LR | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. | | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. | -| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in the original Session. | +| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in each task's target Session. | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. | | `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | Owns one authenticated OpenSSH connection, installed helper identity, independent program streams and disconnect cleanup for the paired remote providers. | | `ctx.subprocess` | `seam` | [`subprocess`](../packages/subprocess/subprocess) | [`subprocess-local`](../packages/subprocess/subprocess-local), [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | [`bash-local`](../packages/shell/bash-local), [`bash-sandbox`](../packages/shell/bash-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash), [`lsp-stdio`](../packages/lsp/lsp-stdio), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | - | The bash executors, the PTY shell backend, the LSP host, and the out-of-process ACP, Codex, and Claude Code subagent backends spawn through ctx.subprocess; the service owns process coordinates, tree/session lifetime, stdio dispositions, terminal mechanics, and kill escalation. | @@ -748,7 +752,7 @@ flowchart LR | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | The basic backend consumes post-step pressure and request-error recovery events; there is no model-facing compact tool. | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/experimental/tool-ralph) | - | Providers prepare local children or execute external tasks; one activation manager owns both lifecycles. The delegation tool selects a backend, control tools deliver local follow-ups, and workflows await activation results. | | `ctx.speechToText` | `seam` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | Routes explicit recognizers; the browser uses the authenticated Remote and keeps transcripts in the draft until submission. | -| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | Owns the implicit-root roster, direct peer inbox delivery, shared task DAG, and continuable-child lifecycle; tool-agent-team contributes model controls. | +| `ctx.agentTeams` | `core` | [`agent-team`](../packages/team/agent-team) | - | [`tool-agent-team`](../packages/team/tool-agent-team) | - | Owns the shared task DAG for a subagent tree; tool-agent-team contributes task controls. | | `ctx.claudeCodeMods` | `core` | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | - | - | - | Loads mods that defineMod plugins add, raises their hook chains from harness extension points, and draws the band above the prompt over its Remote. | | `ctx.inspector` | `core` | `inspector` | - | - | - | Owns the Worker-hosted CDP target and the transport-independent Host and Client observation and Cordis-tree query API. | | `ctx.jobs` | `seam` | [`jobs`](../packages/jobs/jobs) | [`jobs-local`](../packages/jobs/jobs-local) | [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`tool-terminal`](../packages/experimental/tool-terminal), [`tool-jobs`](../packages/jobs/tool-jobs), [`api-job-controller`](../packages/api/job-controller) | - | Producers (background bash/pwsh and PTY sends) register running work; record-declaring jobs additionally stream raw output for non-consuming observers; tool-jobs is the model-facing controller that reads, lists, and kills it; jobs-local is the process-local registry. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5aba6867b8..c76cb430e6 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -33,6 +33,8 @@ flowchart LR pkg_plugin_market["plugin-market"] svc_pluginMarket["ctx.pluginMarket
Plugin market index reader"] pkg_client_ui_plugin_market["client-ui-plugin-market"] + pkg_client_ui_cli_account["client-ui-cli-account"] + svc_cliAccounts["ctx.cliAccounts
CLI app accounts on the Plugins page"] svc_profileContext["ctx.profileContext
Launcher-owned profile data"] pkg_client_connection["client-connection"] svc_connection["ctx.connection
Authenticated browser transport"] @@ -272,9 +274,9 @@ flowchart LR pkg_experimental_speech_to_text["experimental-speech-to-text"] svc_speechToText["ctx.speechToText
Experimental speech recognition providers"] pkg_experimental_speech_to_text_sensevoice["experimental-speech-to-text-sensevoice"] - pkg_experimental_agent_team["experimental-agent-team"] + pkg_agent_team["agent-team"] svc_agentTeams["ctx.agentTeams
Agent Teams coordination domain"] - pkg_experimental_tool_agent_team["experimental-tool-agent-team"] + pkg_tool_agent_team["tool-agent-team"] pkg_experimental_claude_code_mods["experimental-claude-code-mods"] svc_claudeCodeMods["ctx.claudeCodeMods
Claude Code mods bridge"] pkg_inspector["inspector"] @@ -325,6 +327,7 @@ flowchart LR pkg_agent_default_model --> svc_agentDefaultModel pkg_agent_loop --> svc_agentLoop pkg_agent_preset_registry --> svc_agentPresets + pkg_agent_team --> svc_agentTeams pkg_api_gateway --> svc_typertGateway pkg_api_job_controller --> svc_jobController pkg_api_remote_access --> svc_remoteAccess @@ -348,6 +351,7 @@ flowchart LR pkg_client_file_upload --> svc_fileUploads pkg_client_modules --> svc_clientModules pkg_client_product_analytics --> svc_productAnalytics + pkg_client_ui_cli_account --> svc_cliAccounts pkg_client_ui_plugin_manager --> svc_pluginRegistryProbe pkg_command_feedback --> svc_sessionFeedback pkg_commands --> svc_commands @@ -364,7 +368,6 @@ flowchart LR pkg_deepseek_account --> svc_deepseekAccount pkg_deepseek_account_platform --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions - pkg_experimental_agent_team --> svc_agentTeams pkg_experimental_api_speech_to_text --> svc_speechController pkg_experimental_browser_use_chrome_devtools_mcp --> svc_browserUse pkg_experimental_browser_use_playwright_mcp --> svc_browserUse @@ -494,7 +497,7 @@ flowchart LR svc_agentDefaultModel --> pkg_headless svc_agentLoop --> pkg_base svc_agentLoop --> pkg_sdk_minimal - svc_agentTeams --> pkg_experimental_tool_agent_team + svc_agentTeams --> pkg_tool_agent_team svc_agents --> pkg_acp svc_agents --> pkg_agent_loop svc_agents --> pkg_subagent @@ -666,6 +669,7 @@ flowchart LR | `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 | | `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 | | `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 | +| `ctx.cliAccounts` | `service` | [`client-ui-cli-account`](../packages/client/ui-cli-account) | - | - | - | 保存 CLI 应用插件注册的账号,并通过一个 Remote 提供给插件页;链接和提示只留在发起操作的浏览器中。 | | `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 | | `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 负责浏览器认证与共享 HTTP 请求分发;API 适配器注册端点和流。 | | `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | 提供方映射远端与变更请求 URL、按 head 分支查找变更请求并批量读取状态;同一变更请求的监听方共享一个轮询循环。 | @@ -734,7 +738,7 @@ flowchart LR | `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | 拥有实时 Agent 句柄、创建/恢复工厂 seam,以及进程本地的发起方传播。 | | `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. | | `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 | -| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入原 Session。 | +| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入每个任务的目标 Session。 | | `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | 从会话日志折叠带修订版本的目标状态,并将实时延续激活保留在进程本地。 | | `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | 负责一条经过认证的 OpenSSH 连接、已安装辅助程序身份、独立程序流,以及配套远端提供方的断连清理。 | | `ctx.subprocess` | `seam` | [`subprocess`](../packages/subprocess/subprocess) | [`subprocess-local`](../packages/subprocess/subprocess-local), [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | [`bash-local`](../packages/shell/bash-local), [`bash-sandbox`](../packages/shell/bash-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash), [`lsp-stdio`](../packages/lsp/lsp-stdio), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | - | Bash 执行器、PTY shell 后端、LSP Host,以及进程外 ACP、Codex 和 Claude Code subagent 后端都通过 ctx.subprocess 执行 spawn;该服务负责进程坐标、进程树/会话生命周期、stdio 处置、终端机制和 kill 升级。 | @@ -750,7 +754,7 @@ flowchart LR | `ctx.compaction` | `seam` | [`compaction`](../packages/compaction/compaction) | [`compaction-basic`](../packages/compaction/compaction-basic) | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 基础后端消费步骤后的压力事件和请求错误恢复事件;不存在面向模型的压缩工具。 | | `ctx.subagents` | `seam` | [`subagent`](../packages/subagent/subagent) | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process), [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code), [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control), [`tool-ralph`](../packages/experimental/tool-ralph) | - | 提供方准备本地子级或执行外部任务;一个 activation 管理器持有两类生命周期。委派工具选择后端,控制工具投递本地后续消息,工作流等待 activation 结果。 | | `ctx.speechToText` | `seam` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text) | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | - | 路由显式选择的识别器;浏览器使用带认证的 Remote,并在提交前将转写保留在草稿中。 | -| `ctx.agentTeams` | `core` | [`experimental-agent-team`](../packages/experimental/agent-team) | - | [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | - | 负责隐式 Root roster、直接 peer inbox 投递、共享任务 DAG 与 continuable child 生命周期;tool-agent-team 提供模型控制工具。 | +| `ctx.agentTeams` | `core` | [`agent-team`](../packages/team/agent-team) | - | [`tool-agent-team`](../packages/team/tool-agent-team) | - | 负责子代理树共享的任务 DAG;tool-agent-team 提供任务控制工具。 | | `ctx.claudeCodeMods` | `core` | [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | - | - | - | 加载 defineMod 插件添加的模组,从 harness 扩展点触发其钩子链,并通过其 Remote 绘制提示框上方的横幅。 | | `ctx.inspector` | `core` | `inspector` | - | - | - | 负责 Worker 托管的 CDP target,以及独立于传输的 Host 和 Client observation 与 Cordis tree query API。 | | `ctx.jobs` | `seam` | [`jobs`](../packages/jobs/jobs) | [`jobs-local`](../packages/jobs/jobs-local) | [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`tool-terminal`](../packages/experimental/tool-terminal), [`tool-jobs`](../packages/jobs/tool-jobs), [`api-job-controller`](../packages/api/job-controller) | - | 生产方(后台 bash/pwsh 与 PTY 发送)登记正在运行的工作;声明 record 的 job 还为非消费观察者流式提供原始输出;tool-jobs 是面向模型的控制器,用于读取、列出和终止这些工作;jobs-local 是进程本地注册表。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3204940ad3..085f478bb7 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -111,7 +111,7 @@ export interface Config { - `inject`: `agents` · `sessions` · `llm` · `tools` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.md) · [`SessionId`](subsystems/core.md) · `Volatile` (`@deepseek-ai/cosmokit`) -- `source`: [`packages/core/agent-loop/src/index.ts:253`](../packages/core/agent-loop/src/index.ts) +- `source`: [`packages/core/agent-loop/src/index.ts:252`](../packages/core/agent-loop/src/index.ts) ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -171,6 +171,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-agent-team` + +- `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` +- `source`: [`packages/team/agent-team/src/types.ts:132`](../packages/team/agent-team/src/types.ts) + +```ts config-catalog +/** Team-service deployment limits. */ +export interface Config { + /** Maximum non-deleted tasks retained by one Team. */ + readonly maxTasks?: number +} +``` + + @@ -875,29 +892,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-experimental-agent-team` - -- `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` -- `source`: [`packages/experimental/agent-team/src/types.ts:153`](../packages/experimental/agent-team/src/types.ts) - -```ts config-catalog -/** Team-service deployment limits. */ -export interface Config { - /** Maximum immutable teammate names retained by one Team. */ - readonly maxMembers?: number - /** Maximum non-deleted tasks retained by one Team. */ - readonly maxTasks?: number - /** Maximum UTF-8 bytes in one complete sender-framed delivery. */ - readonly maxMessageBytes?: number - /** Maximum milliseconds for shared operation settlement and for each Team child drain. */ - readonly disposalTimeoutMs?: number -} -``` - - @@ -1113,11 +1107,14 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, operation bounds, and profile-local application grants. */ -export type Config = CuaConfig +export interface Config extends CuaConfig { + /** Interval in milliseconds between permission and position checks while the native guide is open. */ + permissionPollIntervalMs: number +} ``` @@ -1430,27 +1427,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-experimental-tool-agent-team` - -- `inject`: `agents` · `agentTeams` · `tools` · `systemPrompt` -- `source`: [`packages/experimental/tool-agent-team/src/index.ts:17`](../packages/experimental/tool-agent-team/src/index.ts) - -```ts config-catalog -/** Tool routing configuration. */ -export interface Config { - /** Register `interrupt_agent` and its policy guidance. Defaults to true; false leaves the domain API available. */ - readonly interrupt?: boolean - /** Continuable-subagent provider used for fresh teammates. */ - readonly freshProvider?: string - /** Continuable-subagent provider used for completed-prefix fork teammates. */ - readonly forkProvider?: string -} -``` - - @@ -1579,7 +1555,7 @@ export interface Config { ## `@deepseek-ai/dsh-fs-local` -- `source`: [`packages/fs/fs-local/src/index.ts:46`](../packages/fs/fs-local/src/index.ts) +- `source`: [`packages/fs/fs-local/src/index.ts:51`](../packages/fs/fs-local/src/index.ts) ```ts config-catalog /** Configuration for the local filesystem backend. */ @@ -1975,7 +1951,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:222`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2071,6 +2047,18 @@ export interface PiAiProviderProfile { * requests instead of being rejected by a request-size cap. */ maxRequestImageBytes?: number + /** + * Maximum retained image occurrences per request. A request carrying more + * fails with `IMAGE_OFFLOAD_REQUIRED` naming how many of the oldest + * occurrences to offload. + */ + maxRequestImages?: number + /** + * Oldest occurrences offloaded per count overflow (default 10, capped at + * {@link maxRequestImages}); an explicit value must not exceed it. Larger + * steps rewrite the request prefix less often. + */ + imageOffloadCountQuantum?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number /** @@ -2945,7 +2933,7 @@ export interface Config { ## `@deepseek-ai/dsh-schedule` - `inject`: `agents` · `sessions` · `storageDomain` · `sessionPersistence` -- `source`: [`packages/schedule/schedule/src/index.ts:83`](../packages/schedule/schedule/src/index.ts) +- `source`: [`packages/schedule/schedule/src/index.ts:80`](../packages/schedule/schedule/src/index.ts) ```ts config-catalog /** Configuration for the Host Schedule domain. */ @@ -2960,6 +2948,11 @@ export interface Config { * cap and the window wins, and the newest records survive. */ deliveryHistoryRecords?: number + /** + * Shortest spacing, in seconds, from the occurrence of one delivery to the next delivery of one task whose target + * creates a Session at every delivery; omission defaults to 60. Timed and manual deliveries both wait for it. + */ + newSessionIntervalSeconds?: number } ``` @@ -3567,7 +3560,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' - `inject`: `workingDirectory` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/subagent/subagent/src/index.ts:186`](../packages/subagent/subagent/src/index.ts) +- `source`: [`packages/subagent/subagent/src/index.ts:181`](../packages/subagent/subagent/src/index.ts) ```ts config-catalog /** Host configuration for continuable subagent capacity. */ @@ -3783,7 +3776,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:264`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:265`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -3922,6 +3915,20 @@ export type TokenMeterConfig = Record ``` + + + +## `@deepseek-ai/dsh-tool-agent-team` + +- `inject`: `agentTeams` · `subagents` · `tools` · `systemPrompt` +- `source`: [`packages/team/tool-agent-team/src/index.ts:18`](../packages/team/tool-agent-team/src/index.ts) + +```ts config-catalog +/** The Team tool plugin takes no configuration. */ +export type Config = Record +``` + + @@ -4017,7 +4024,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:26`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4030,6 +4037,8 @@ export interface Config { write?: boolean /** Register `edit` and its guidance. Defaults to true. */ edit?: boolean + /** Register `apply_patch` and its guidance beside `edit`. Defaults to false; shipped compositions set it on their `tool-fs` rows. */ + applyPatch?: boolean /** Default and maximum number of lines returned by one `read` call. */ readLimit?: number /** Maximum characters returned for a single line before truncation. */ @@ -4366,6 +4375,23 @@ export interface PresetSelectionConfig { ``` + + + +## `@deepseek-ai/dsh-tool-subagent-control` + +- `inject`: `tools` · `subagents` · `agents` · `systemPrompt` +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:26`](../packages/subagent/tool-subagent-control/src/index.ts) + +```ts config-catalog +/** Optional subagent control tools. */ +export interface Config { + /** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */ + interrupt?: boolean +} +``` + + @@ -4842,6 +4868,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) | | `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) | | `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-agent-team` | — | [`packages/client/ui-agent-team/src/index.ts`](../packages/client/ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-client-ui-approval` | — | [`packages/client/ui-approval/src/index.ts`](../packages/client/ui-approval/src/index.ts) | | `@deepseek-ai/dsh-client-ui-attachment` | — | [`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts) | | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | @@ -4909,7 +4936,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) | | `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) | | `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) | -| `@deepseek-ai/dsh-experimental-client-ui-agent-team` | — | [`packages/experimental/client-ui-agent-team/src/index.ts`](../packages/experimental/client-ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-claude-code-mods` | — | [`packages/experimental/client-ui-claude-code-mods/src/index.ts`](../packages/experimental/client-ui-claude-code-mods/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-stats` | — | [`packages/experimental/client-ui-stats/src/index.ts`](../packages/experimental/client-ui-stats/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-voice-input` | — | [`packages/experimental/client-ui-voice-input/src/index.ts`](../packages/experimental/client-ui-voice-input/src/index.ts) | @@ -4944,8 +4970,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co | `@deepseek-ai/dsh-tool-call-timeout-policy` | `tools` | [`packages/guard/timeout-policy/src/index.ts`](../packages/guard/timeout-policy/src/index.ts) | | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | -| `@deepseek-ai/dsh-tool-schedule` | `tools` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | -| `@deepseek-ai/dsh-tool-subagent-control` | `tools` · `subagents` · `agents` | [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) | +| `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | @@ -5002,7 +5027,6 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-cmdline` | — | [`packages/boot/cmdline/src/index.ts`](../packages/boot/cmdline/src/index.ts) | | `@deepseek-ai/dsh-cua-bundle` | — | [`packages/experimental/cua-bundle/src/index.ts`](../packages/experimental/cua-bundle/src/index.ts) | | `@deepseek-ai/dsh-deque` | — | [`packages/util/deque/src/index.ts`](../packages/util/deque/src/index.ts) | -| `@deepseek-ai/dsh-experimental-agent-team-profile` | — | [`packages/experimental/agent-team-profile/src/index.ts`](../packages/experimental/agent-team-profile/src/index.ts) | | `@deepseek-ai/dsh-experimental-badge-skill-bundle` | — | [`packages/experimental/badge-skill-bundle/src/index.ts`](../packages/experimental/badge-skill-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | @@ -5019,6 +5043,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. | `@deepseek-ai/dsh-experimental-webworker-packer` | — | [`packages/experimental/webworker-packer/src/index.ts`](../packages/experimental/webworker-packer/src/index.ts) | | `@deepseek-ai/dsh-experimental-webworker-runtime` | — | [`packages/experimental/webworker-runtime/src/index.ts`](../packages/experimental/webworker-runtime/src/index.ts) | | `@deepseek-ai/dsh-feishu` | — | [`packages/connector/feishu/src/index.ts`](../packages/connector/feishu/src/index.ts) | +| `@deepseek-ai/dsh-fs-patch` | — | [`packages/fs/fs-patch/src/index.ts`](../packages/fs/fs-patch/src/index.ts) | | `@deepseek-ai/dsh-home-paths` | — | [`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts) | | `@deepseek-ai/dsh-hook-protocol` | — | [`packages/experimental/hook-protocol/src/index.ts`](../packages/experimental/hook-protocol/src/index.ts) | | `@deepseek-ai/dsh-http-proxy` | — | [`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts) | diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 2171b480b2..542f0a7bd9 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -113,7 +113,7 @@ export interface Config { - `inject`: `agents` · `sessions` · `llm` · `tools` · `systemPrompt` · `sessionProjections` - `refs`: [`AgentOptions`](subsystems/core.zh.md) · [`SessionId`](subsystems/core.zh.md) · `Volatile` (`@deepseek-ai/cosmokit`) -- `source`: [`packages/core/agent-loop/src/index.ts:253`](../packages/core/agent-loop/src/index.ts) +- `source`: [`packages/core/agent-loop/src/index.ts:252`](../packages/core/agent-loop/src/index.ts) ```ts config-catalog /** Agent-loop plugin configuration. */ @@ -173,6 +173,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-agent-team` + +- `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` +- `source`: [`packages/team/agent-team/src/types.ts:132`](../packages/team/agent-team/src/types.ts) + +```ts config-catalog +/** Team-service deployment limits. */ +export interface Config { + /** Maximum non-deleted tasks retained by one Team. */ + readonly maxTasks?: number +} +``` + + @@ -877,29 +894,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-experimental-agent-team` - -- `inject`: `agents` · `sessions` · `sessionPersistence` · `sessionProjections` · `subagents` -- `source`: [`packages/experimental/agent-team/src/types.ts:153`](../packages/experimental/agent-team/src/types.ts) - -```ts config-catalog -/** Team-service deployment limits. */ -export interface Config { - /** Maximum immutable teammate names retained by one Team. */ - readonly maxMembers?: number - /** Maximum non-deleted tasks retained by one Team. */ - readonly maxTasks?: number - /** Maximum UTF-8 bytes in one complete sender-framed delivery. */ - readonly maxMessageBytes?: number - /** Maximum milliseconds for shared operation settlement and for each Team child drain. */ - readonly disposalTimeoutMs?: number -} -``` - - @@ -1115,11 +1109,14 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:16`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:18`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, operation bounds, and profile-local application grants. */ -export type Config = CuaConfig +export interface Config extends CuaConfig { + /** Interval in milliseconds between permission and position checks while the native guide is open. */ + permissionPollIntervalMs: number +} ``` @@ -1432,27 +1429,6 @@ export interface Config { ``` - - - -## `@deepseek-ai/dsh-experimental-tool-agent-team` - -- `inject`: `agents` · `agentTeams` · `tools` · `systemPrompt` -- `source`: [`packages/experimental/tool-agent-team/src/index.ts:17`](../packages/experimental/tool-agent-team/src/index.ts) - -```ts config-catalog -/** Tool routing configuration. */ -export interface Config { - /** Register `interrupt_agent` and its policy guidance. Defaults to true; false leaves the domain API available. */ - readonly interrupt?: boolean - /** Continuable-subagent provider used for fresh teammates. */ - readonly freshProvider?: string - /** Continuable-subagent provider used for completed-prefix fork teammates. */ - readonly forkProvider?: string -} -``` - - @@ -1581,7 +1557,7 @@ export interface Config { ## `@deepseek-ai/dsh-fs-local` -- `source`: [`packages/fs/fs-local/src/index.ts:46`](../packages/fs/fs-local/src/index.ts) +- `source`: [`packages/fs/fs-local/src/index.ts:51`](../packages/fs/fs-local/src/index.ts) ```ts config-catalog /** Configuration for the local filesystem backend. */ @@ -1977,7 +1953,7 @@ export interface Config extends ProtocolConfig, ModelListingConfig { - `inject`: `llm` - `refs`: `Api` (`@earendil-works/pi-ai`) · `CacheRetention` (`@earendil-works/pi-ai`) · `Model` (`@earendil-works/pi-ai`) · `ModelThinkingLevel` (`@earendil-works/pi-ai`) · `OpenAICompletionsCompat` (`@earendil-works/pi-ai`) · [`RetryPolicyConfig`](../packages/llm/llm/src/index.ts) · `ThinkingBudgets` (`@earendil-works/pi-ai`) · `Transport` (`@earendil-works/pi-ai`) · `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/llm/llm-pi-ai/src/config.ts:222`](../packages/llm/llm-pi-ai/src/config.ts) +- `source`: [`packages/llm/llm-pi-ai/src/config.ts:251`](../packages/llm/llm-pi-ai/src/config.ts) ```ts config-catalog /** Plugin configuration: the provider routes this instance owns. */ @@ -2073,6 +2049,18 @@ export interface PiAiProviderProfile { * requests instead of being rejected by a request-size cap. */ maxRequestImageBytes?: number + /** + * Maximum retained image occurrences per request. A request carrying more + * fails with `IMAGE_OFFLOAD_REQUIRED` naming how many of the oldest + * occurrences to offload. + */ + maxRequestImages?: number + /** + * Oldest occurrences offloaded per count overflow (default 10, capped at + * {@link maxRequestImages}); an explicit value must not exceed it. Larger + * steps rewrite the request prefix less often. + */ + imageOffloadCountQuantum?: number /** Total-pixel budget for each deterministic inline request version. */ requestImagePixelBudget?: number /** @@ -2947,7 +2935,7 @@ export interface Config { ## `@deepseek-ai/dsh-schedule` - `inject`: `agents` · `sessions` · `storageDomain` · `sessionPersistence` -- `source`: [`packages/schedule/schedule/src/index.ts:83`](../packages/schedule/schedule/src/index.ts) +- `source`: [`packages/schedule/schedule/src/index.ts:80`](../packages/schedule/schedule/src/index.ts) ```ts config-catalog /** Configuration for the Host Schedule domain. */ @@ -2962,6 +2950,11 @@ export interface Config { * cap and the window wins, and the newest records survive. */ deliveryHistoryRecords?: number + /** + * Shortest spacing, in seconds, from the occurrence of one delivery to the next delivery of one task whose target + * creates a Session at every delivery; omission defaults to 60. Timed and manual deliveries both wait for it. + */ + newSessionIntervalSeconds?: number } ``` @@ -3569,7 +3562,7 @@ export type JournalMode = 'wal' | 'delete' | 'truncate' | 'persist' - `inject`: `workingDirectory` · `sessionProjections` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/subagent/subagent/src/index.ts:186`](../packages/subagent/subagent/src/index.ts) +- `source`: [`packages/subagent/subagent/src/index.ts:181`](../packages/subagent/subagent/src/index.ts) ```ts config-catalog /** Host configuration for continuable subagent capacity. */ @@ -3785,7 +3778,7 @@ export interface Config { ## `@deepseek-ai/dsh-system-prompt` -- `source`: [`packages/core/system-prompt/src/index.ts:264`](../packages/core/system-prompt/src/index.ts) +- `source`: [`packages/core/system-prompt/src/index.ts:265`](../packages/core/system-prompt/src/index.ts) ```ts config-catalog /** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */ @@ -3924,6 +3917,20 @@ export type TokenMeterConfig = Record ``` + + + +## `@deepseek-ai/dsh-tool-agent-team` + +- `inject`: `agentTeams` · `subagents` · `tools` · `systemPrompt` +- `source`: [`packages/team/tool-agent-team/src/index.ts:18`](../packages/team/tool-agent-team/src/index.ts) + +```ts config-catalog +/** The Team tool plugin takes no configuration. */ +export type Config = Record +``` + + @@ -4019,7 +4026,7 @@ export interface Config { ## `@deepseek-ai/dsh-tool-fs` - `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory` -- `source`: [`packages/fs/tool-fs/src/index.ts:26`](../packages/fs/tool-fs/src/index.ts) +- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts) ```ts config-catalog /** Plugin config (all optional — `Config` supplies the defaults). */ @@ -4032,6 +4039,8 @@ export interface Config { write?: boolean /** Register `edit` and its guidance. Defaults to true. */ edit?: boolean + /** Register `apply_patch` and its guidance beside `edit`. Defaults to false; shipped compositions set it on their `tool-fs` rows. */ + applyPatch?: boolean /** Default and maximum number of lines returned by one `read` call. */ readLimit?: number /** Maximum characters returned for a single line before truncation. */ @@ -4368,6 +4377,23 @@ export interface PresetSelectionConfig { ``` + + + +## `@deepseek-ai/dsh-tool-subagent-control` + +- `inject`: `tools` · `subagents` · `agents` · `systemPrompt` +- `source`: [`packages/subagent/tool-subagent-control/src/index.ts:26`](../packages/subagent/tool-subagent-control/src/index.ts) + +```ts config-catalog +/** Optional subagent control tools. */ +export interface Config { + /** Register `interrupt_agent`. Defaults to true; false leaves the service API available. */ + interrupt?: boolean +} +``` + + @@ -4844,6 +4870,7 @@ export interface Config { | `@deepseek-ai/dsh-client-resources` | — | [`packages/client/resources/src/index.ts`](../packages/client/resources/src/index.ts) | | `@deepseek-ai/dsh-client-ui-action-cards` | — | [`packages/experimental/client-ui-action-cards/src/index.ts`](../packages/experimental/client-ui-action-cards/src/index.ts) | | `@deepseek-ai/dsh-client-ui-agent-preset` | — | [`packages/client/ui-agent-preset/src/index.ts`](../packages/client/ui-agent-preset/src/index.ts) | +| `@deepseek-ai/dsh-client-ui-agent-team` | — | [`packages/client/ui-agent-team/src/index.ts`](../packages/client/ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-client-ui-approval` | — | [`packages/client/ui-approval/src/index.ts`](../packages/client/ui-approval/src/index.ts) | | `@deepseek-ai/dsh-client-ui-attachment` | — | [`packages/client/ui-attachment/src/index.ts`](../packages/client/ui-attachment/src/index.ts) | | `@deepseek-ai/dsh-client-ui-brand-official` | — | [`packages/client/ui-brand-official/src/index.ts`](../packages/client/ui-brand-official/src/index.ts) | @@ -4911,7 +4938,6 @@ export interface Config { | `@deepseek-ai/dsh-deepseek-llm-api-extensions` | — | [`packages/llm/deepseek-llm-api-extensions/src/index.ts`](../packages/llm/deepseek-llm-api-extensions/src/index.ts) | | `@deepseek-ai/dsh-deliverable-file-references` | `systemPrompt` | [`packages/deliverables/deliverable-file-references/src/index.ts`](../packages/deliverables/deliverable-file-references/src/index.ts) | | `@deepseek-ai/dsh-experimental-auto-review` | `approval` · `llm` · `permissionPresets` · `sessions` · `tools` · `workingDirectory` | [`packages/experimental/auto-review/src/index.ts`](../packages/experimental/auto-review/src/index.ts) | -| `@deepseek-ai/dsh-experimental-client-ui-agent-team` | — | [`packages/experimental/client-ui-agent-team/src/index.ts`](../packages/experimental/client-ui-agent-team/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-claude-code-mods` | — | [`packages/experimental/client-ui-claude-code-mods/src/index.ts`](../packages/experimental/client-ui-claude-code-mods/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-stats` | — | [`packages/experimental/client-ui-stats/src/index.ts`](../packages/experimental/client-ui-stats/src/index.ts) | | `@deepseek-ai/dsh-experimental-client-ui-voice-input` | — | [`packages/experimental/client-ui-voice-input/src/index.ts`](../packages/experimental/client-ui-voice-input/src/index.ts) | @@ -4946,8 +4972,7 @@ export interface Config { | `@deepseek-ai/dsh-tool-call-timeout-policy` | `tools` | [`packages/guard/timeout-policy/src/index.ts`](../packages/guard/timeout-policy/src/index.ts) | | `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) | | `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) | -| `@deepseek-ai/dsh-tool-schedule` | `tools` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | -| `@deepseek-ai/dsh-tool-subagent-control` | `tools` · `subagents` · `agents` | [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) | +| `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) | | `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) | | `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) | | `@deepseek-ai/dsh-user-questions` | — | [`packages/interaction/user-questions/src/index.ts`](../packages/interaction/user-questions/src/index.ts) | @@ -5004,7 +5029,6 @@ export interface Config { | `@deepseek-ai/dsh-cmdline` | — | [`packages/boot/cmdline/src/index.ts`](../packages/boot/cmdline/src/index.ts) | | `@deepseek-ai/dsh-cua-bundle` | — | [`packages/experimental/cua-bundle/src/index.ts`](../packages/experimental/cua-bundle/src/index.ts) | | `@deepseek-ai/dsh-deque` | — | [`packages/util/deque/src/index.ts`](../packages/util/deque/src/index.ts) | -| `@deepseek-ai/dsh-experimental-agent-team-profile` | — | [`packages/experimental/agent-team-profile/src/index.ts`](../packages/experimental/agent-team-profile/src/index.ts) | | `@deepseek-ai/dsh-experimental-badge-skill-bundle` | — | [`packages/experimental/badge-skill-bundle/src/index.ts`](../packages/experimental/badge-skill-bundle/src/index.ts) | | `@deepseek-ai/dsh-experimental-browser-use-runtime` | — | [`packages/experimental/browser-use-runtime/src/index.ts`](../packages/experimental/browser-use-runtime/src/index.ts) | | `@deepseek-ai/dsh-experimental-cot-translation-bundle` | — | [`packages/experimental/cot-translation-bundle/src/index.ts`](../packages/experimental/cot-translation-bundle/src/index.ts) | @@ -5021,6 +5045,7 @@ export interface Config { | `@deepseek-ai/dsh-experimental-webworker-packer` | — | [`packages/experimental/webworker-packer/src/index.ts`](../packages/experimental/webworker-packer/src/index.ts) | | `@deepseek-ai/dsh-experimental-webworker-runtime` | — | [`packages/experimental/webworker-runtime/src/index.ts`](../packages/experimental/webworker-runtime/src/index.ts) | | `@deepseek-ai/dsh-feishu` | — | [`packages/connector/feishu/src/index.ts`](../packages/connector/feishu/src/index.ts) | +| `@deepseek-ai/dsh-fs-patch` | — | [`packages/fs/fs-patch/src/index.ts`](../packages/fs/fs-patch/src/index.ts) | | `@deepseek-ai/dsh-home-paths` | — | [`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts) | | `@deepseek-ai/dsh-hook-protocol` | — | [`packages/experimental/hook-protocol/src/index.ts`](../packages/experimental/hook-protocol/src/index.ts) | | `@deepseek-ai/dsh-http-proxy` | — | [`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts) | diff --git a/docs/development.i18n.yaml b/docs/development.i18n.yaml index 406a86b628..591bcdd5ce 100644 --- a/docs/development.i18n.yaml +++ b/docs/development.i18n.yaml @@ -21,14 +21,14 @@ en: 3221d1076554001f zh: 29f166be6a5c04d9 /development-guide/contributor-reference/typescript-project-layout: - en: eb79b6f8ea745a9f - zh: de676c78231c823a + en: 16d67911ecaa50d3 + zh: f5259b0fbf022db3 /development-guide/contributor-reference/environment-variables: en: dba2c72ee6ffa930 zh: b65c27fbb9129ec8 /development-guide/contributor-reference/git-integrations: - en: 2efb7c4e482413fc - zh: 75386476a283111a + en: 075658ecfc10da20 + zh: 69e664417bbde87e /development-guide/contributor-reference/ci-gates: en: dfa3a24d9070478f zh: fa889b3536ab58e2 @@ -45,5 +45,5 @@ en: 85b38f78d87fc88f zh: 00d5eb625e7dfb61 /development-guide/contributor-reference/documenting-types-verbatim-ts-type-equiv: - en: 9d578b6797be921b - zh: 823cbfcfd9a75c17 + en: 6b9b948e0b80cf76 + zh: 2642f4127ed9b719 diff --git a/docs/development.md b/docs/development.md index 406b6c1a7d..9aec6e601d 100644 --- a/docs/development.md +++ b/docs/development.md @@ -89,7 +89,7 @@ tsdown --env.DSH_BUILD_FACE client pnpm run build:web ``` -`pnpm run build:check` runs only `tsc -p tsconfig.host.json` and `tsc -p tsconfig.client.json` concurrently. Project mode checks each aggregate's repository-wide test and script program against the package declarations already on disk and never compiles a reference, so `build:check` neither detects nor rebuilds missing or stale `build:artifacts` output; missing output surfaces as compiler errors. `pnpm run build` runs both step sets as one [scheduled](../scripts/run-gates.ts) dependency graph: each aggregate check starts once its own face's package compilation finishes and overlaps the remaining artifact steps. In all three commands `DSH_GATE_CONCURRENCY` bounds concurrent steps (`1` runs them in dependency order) and `DSH_GATE_FAIL_FAST=1` stops the remaining steps at the first failure; otherwise a failure skips only its dependents, so independent errors are all reported. A failed step prints its own output, and any failure exits non-zero without writing the client build record. +`pnpm run build:check` runs only `tsc -p tsconfig.host.json` and `tsc -p tsconfig.client.json` concurrently. Project mode checks each aggregate's repository-wide test and script program against the package declarations already on disk and never compiles a reference, so `build:check` neither detects nor rebuilds missing or stale `build:artifacts` output; missing output surfaces as compiler errors. `pnpm run build` runs both step sets as one [scheduled](../scripts/run-gates.ts) dependency graph: each aggregate check starts once its own face's package compilation finishes and overlaps the remaining artifact steps. In all three commands `DSH_GATE_CONCURRENCY` bounds concurrent steps (`1` runs them in dependency order) and `DSH_GATE_FAIL_FAST=1` stops the remaining steps at the first failure; otherwise a failure skips only its dependents, so independent errors are all reported. A failed step prints its own output, and any failure exits non-zero without writing the client build record. Host TypeScript compiler processes receive an 8 GiB V8 old-space limit for the package graph and cold aggregate checks. Choose the command by what the change needs: @@ -155,6 +155,8 @@ Contributors can opt into the comprehensive local gate set with `pnpm run check: Outside CI (`CI` other than `true`), default worker counts follow the [local worker budget](../scripts/parallelism.ts): 12 for gate schedulers, `build`, `typecheck`, Oxlint, and publint, and 48 for Vitest forks and local coverage. `doc-sync`, `test:docs`, `hygiene`, and `check:all` run at most 8 gates at once, in CI as well. `os.availableParallelism()` reports host CPUs rather than a container's CPU quota, so uncapped defaults oversubscribe shared hosts. CI keeps the runner's CPU count. `DSH_GATE_CONCURRENCY`, `DSH_OXLINT_THREADS`, `DSH_COVERAGE_MAX_WORKERS`, and Vitest `--maxWorkers` override the defaults. +`run-gates` gives the CLI help generator one child at a time; direct `pnpm run verify-cli-help` uses the standalone worker budget. `DSH_CLI_HELP_CONCURRENCY` overrides that child limit with a positive integer validated before startup. Each invocation retains its private `DSH_HOME` and `DSH_AGENTS_HOME` and 30-second deadline. + ### CI gates The 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. Coverage partitions reuse file timings scoped to their platform and runner pool to balance work within the configured worker limit. Native Windows lanes run in the separate [CI Windows workflow](../.github/workflows/ci-windows.yml) and Python checks in the separate [CI Python workflow](../.github/workflows/ci-python.yml), each of which can be re-run independently. Required benchmarks run separately on standard GitHub-hosted Linux; the [benchmark runner reference](../benchmarks/AGENTS.md) owns routing and the job timeout. 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. @@ -216,4 +218,4 @@ The [subsystems](subsystems/README.md) pages paste source-equivalent declaration { "doc": "docs/subsystems/session.md", "symbol": "SessionEvent", "source": "packages/core/session/src/types.ts" } ``` -`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 type definition. The gate enforces a 1:1 correspondence by document, symbol, and projection between primary blocks and manifest entries; a paired `.zh.md` block reuses its unsuffixed sibling's entry only when the whole tracked fence sequence is byte-identical and ordered identically. `doc-typecheck` applies the same derivative rule to compilable fences, while skipping both source-equivalence fence kinds from compilation and 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 primary block, update the manifest in the same change. +`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 type definition. The gate enforces a 1:1 correspondence by document, symbol, and projection between primary blocks and manifest entries; a paired `.zh.md` block reuses its unsuffixed sibling's entry only when the whole tracked fence sequence is byte-identical and ordered identically. `doc-typecheck` applies the same derivative rule to compilable fences, while skipping both source-equivalence fence kinds from compilation and its opt-out ratio. Upgrade guides in version directories older than the root package version are frozen; their examples are excluded from current-API compilation. When you change a documented declaration or its JSDoc, the gate fails until you update the paste; when you add or remove a primary block, update the manifest in the same change. diff --git a/docs/development.zh.md b/docs/development.zh.md index 8dcedc8938..92f0b71b99 100644 --- a/docs/development.zh.md +++ b/docs/development.zh.md @@ -93,7 +93,7 @@ tsdown --env.DSH_BUILD_FACE client pnpm run build:web ``` -`pnpm run build:check` 只并发运行 `tsc -p tsconfig.host.json` 与 `tsc -p tsconfig.client.json`。project mode 依据磁盘上已有的包声明检查各 aggregate 的仓库级测试和脚本 program,从不编译 reference,因此 `build:check` 既不检测也不重建缺失或过期的 `build:artifacts` 产物;产物缺失时表现为编译器错误。`pnpm run build` 把两组步骤作为一张[调度](../scripts/run-gates.ts)依赖图运行:每个 aggregate 检查在本 face 的包编译完成后立即开始,与其余产物步骤重叠执行。三个命令中,`DSH_GATE_CONCURRENCY` 限制并发步骤数(`1` 按依赖顺序执行),`DSH_GATE_FAIL_FAST=1` 在第一个失败时停止其余步骤;否则失败只跳过其依赖方,因此会报告所有相互独立的错误。失败步骤打印自身输出,任一失败都以非零状态退出且不写 client build record。 +`pnpm run build:check` 只并发运行 `tsc -p tsconfig.host.json` 与 `tsc -p tsconfig.client.json`。project mode 依据磁盘上已有的包声明检查各 aggregate 的仓库级测试和脚本 program,从不编译 reference,因此 `build:check` 既不检测也不重建缺失或过期的 `build:artifacts` 产物;产物缺失时表现为编译器错误。`pnpm run build` 把两组步骤作为一张[调度](../scripts/run-gates.ts)依赖图运行:每个 aggregate 检查在本 face 的包编译完成后立即开始,与其余产物步骤重叠执行。三个命令中,`DSH_GATE_CONCURRENCY` 限制并发步骤数(`1` 按依赖顺序执行),`DSH_GATE_FAIL_FAST=1` 在第一个失败时停止其余步骤;否则失败只跳过其依赖方,因此会报告所有相互独立的错误。失败步骤打印自身输出,任一失败都以非零状态退出且不写 client build record。 Host TypeScript 编译进程的 V8 old-space 上限为 8 GiB,用于包依赖图和无缓存的 aggregate 检查。 按改动需要选择命令: @@ -160,6 +160,8 @@ pi-ai 检查会在内存中重新生成预期元数据。数据过期时,检 在 CI 之外(`CI` 不为 `true`),默认 worker 数遵循[本地 worker 预算](../scripts/parallelism.ts):门禁调度器、`build`、`typecheck`、Oxlint 与 publint 为 12,Vitest fork 与本地覆盖率为 48。`doc-sync`、`test:docs`、`hygiene` 与 `check:all` 最多同时运行 8 个门禁,CI 中同样如此。`os.availableParallelism()` 报告的是宿主 CPU 数而不是容器的 CPU 配额,因此不设上限的默认值会在共享主机上超额订阅。CI 仍使用 runner 的 CPU 数。`DSH_GATE_CONCURRENCY`、`DSH_OXLINT_THREADS`、`DSH_COVERAGE_MAX_WORKERS` 与 Vitest 的 `--maxWorkers` 可覆盖这些默认值。 +`run-gates` 让 CLI 帮助生成器每次只运行一个子进程;直接执行 `pnpm run verify-cli-help` 时使用独立运行的 worker 预算。`DSH_CLI_HELP_CONCURRENCY` 可用正整数覆盖该子进程上限,并在启动前校验。每次调用仍使用独立的 `DSH_HOME` 与 `DSH_AGENTS_HOME`,超时限制仍为 30 秒。 + ### CI 门禁 keyless [CI 工作流](../.github/workflows/ci.yml) 将独立门禁分组到若干宽粒度 lane,并在受支持的 Node 版本上运行一组较小的兼容性检查。产物消费方在各自 lane 内等待一次 build。覆盖率分区复用按平台和运行器池隔离的文件耗时,在配置的 worker 上限内均衡工作量。原生 Windows lane 运行在独立的 [CI Windows 工作流](../.github/workflows/ci-windows.yml)中,Python 检查运行在独立的 [CI Python 工作流](../.github/workflows/ci-python.yml)中,两者都可单独重新运行。必需 benchmark 在标准 GitHub 托管 Linux 上独立运行;[benchmark 运行器说明](../benchmarks/AGENTS.md)拥有路由及 job 超时。单独的真实 API 工作流按其配置的 worker 上限运行 `pnpm run test:e2e`。当前门禁和 job 清单以 [scripts/run-gates.ts](../scripts/run-gates.ts) 和工作流文件为准。 @@ -223,4 +225,4 @@ Web 命令后面的参数会传给 `dsh web`,例如 `pnpm run dev:web --no-ope { "doc": "docs/subsystems/session.md", "symbol": "SessionEvent", "source": "packages/core/session/src/types.ts" } ``` -`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `"projection": "public-api"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码约定和确切类型定义。该门禁按文档、符号和投影,在主块与 manifest 条目之间强制 1:1 对应;只有当配对 `.zh.md` 块的完整受跟踪围栏序列与其无后缀兄弟文件按字节一致且顺序相同时,才会复用后者的条目。`doc-typecheck` 对可编译围栏应用同一派生规则,同时跳过两种源码等价围栏的编译,并将其排除在 opt-out 比例的计算之外。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个主块时,请在同一个变更里更新 manifest。 +`pnpm run verify-type-equiv`(`doc-sync` 的一环)随后通过 TypeScript 解析器从源码提取该符号的声明及其附带的 JSDoc,并断言代码块同时匹配两者。对于不应把实现体写进目录的类,请使用 ` ```ts public-api ` 并设置 `"projection": "public-api"`;门禁检查的投影会保留公共字段、构造函数、访问器、方法以及类和成员的原始 JSDoc,同时省略实现体和私有或受保护成员。比对会忽略空白和非 JSDoc 注释,但要求保留每条原始 JSDoc(包括成员文档),让读者同时看到源码约定和确切类型定义。该门禁按文档、符号和投影,在主块与 manifest 条目之间强制 1:1 对应;只有当配对 `.zh.md` 块的完整受跟踪围栏序列与其无后缀兄弟文件按字节一致且顺序相同时,才会复用后者的条目。`doc-typecheck` 对可编译围栏应用同一派生规则,同时跳过两种源码等价围栏的编译,并将其排除在 opt-out 比例的计算之外。版本目录早于根包版本的升级指南已冻结,其中的示例不参与当前 API 的编译检查。当你改动一个已记录的类型声明或其 JSDoc 时,门禁会失败直到你更新粘贴内容;当你增删一个主块时,请在同一个变更里更新 manifest。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 94522af5d1..cc7a806a71 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -10,24 +10,24 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:199`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:671`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:684`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:700`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:680`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:707`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:686`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:693`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | @@ -48,9 +48,10 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `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`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | -| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | +| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | @@ -66,19 +67,19 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | | `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | -| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | -| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | +| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | +| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | -| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | -| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | -| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | +| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:161`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | +| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:137`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:143`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:153`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 38585aa8ab..6c437ea8b6 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -12,24 +12,24 @@ | Event | Mode | Declared in | Dispatchers | Listeners | | --- | --- | --- | --- | --- | -| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:199`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | +| `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | | `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `agent-team`, `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, `tool-agent-team`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), `tool-agent-team` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | | `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | | `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | | `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), `agent-team`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:691`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:671`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:698`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:677`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | -| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:684`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:700`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:680`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:707`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/removed` | `emit` | [`packages/api/session-controller/src/types.ts:686`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | +| `api-session/status` | `emit` | [`packages/api/session-controller/src/types.ts:693`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `app-boot/config-reload` | `emit` | [`packages/boot/app-boot/src/index.ts:55`](../packages/boot/app-boot/src/index.ts) | [`app-boot`](../packages/boot/app-boot) (`emit`) | [`settings`](../packages/settings/settings) | | `approval/request` | `waterfall` | [`packages/interaction/user-approval/src/types.ts:87`](../packages/interaction/user-approval/src/types.ts) | [`user-approval`](../packages/interaction/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `remotes`, `server` | | `authorization/settled` | `emit` | [`packages/credentials/authorization/src/index.ts:57`](../packages/credentials/authorization/src/index.ts) | [`authorization`](../packages/credentials/authorization) (`events.dispatch`) | - | @@ -50,9 +50,10 @@ | `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`) | `workspace-controller` | | `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) | | `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | -| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` | +| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` | | `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) | | `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - | @@ -68,19 +69,19 @@ | `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - | | `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` | | `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` | -| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | -| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | +| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | +| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | -| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | -| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:166`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | -| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:142`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:148`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | -| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:158`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | +| `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:161`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), `server` | +| `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:137`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:143`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`tool-subagent`](../packages/subagent/tool-subagent) | +| `subagent/start` | `emit` | [`packages/subagent/subagent/src/index.ts:153`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | diff --git a/docs/module-graph.md b/docs/module-graph.md index 339a685c9d..a6a34d46cd 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -63,6 +63,7 @@ flowchart TD pkg_fs["fs"] pkg_fs_local["fs-local"] pkg_fs_observation_policy["fs-observation-policy"] + pkg_fs_patch["fs-patch"] pkg_fs_sandbox["fs-sandbox"] pkg_tool_fs["tool-fs"] pkg_tool_fs_search["tool-fs-search"] @@ -160,6 +161,7 @@ flowchart TD pkg_client_shortcuts["client-shortcuts"] pkg_client_store["client-store"] pkg_client_ui_agent_preset["client-ui-agent-preset"] + pkg_client_ui_agent_team["client-ui-agent-team"] pkg_client_ui_approval["client-ui-approval"] pkg_client_ui_attachment["client-ui-attachment"] pkg_client_ui_brand_official["client-ui-brand-official"] @@ -269,8 +271,6 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] - pkg_experimental_agent_team["experimental-agent-team"] - pkg_experimental_agent_team_profile["experimental-agent-team-profile"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -279,7 +279,6 @@ flowchart TD pkg_experimental_browser_use_runtime["experimental-browser-use-runtime"] pkg_experimental_browser_use_stagehand_native["experimental-browser-use-stagehand-native"] pkg_experimental_claude_code_mods["experimental-claude-code-mods"] - pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] pkg_experimental_client_ui_claude_code_mods["experimental-client-ui-claude-code-mods"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] pkg_experimental_client_ui_forge["experimental-client-ui-forge"] @@ -307,7 +306,6 @@ flowchart TD pkg_experimental_speech_to_text_sensevoice["experimental-speech-to-text-sensevoice"] pkg_experimental_subagent_oar["experimental-subagent-oar"] pkg_experimental_terminal_bundle["experimental-terminal-bundle"] - pkg_experimental_tool_agent_team["experimental-tool-agent-team"] pkg_experimental_tool_subagent_oar["experimental-tool-subagent-oar"] pkg_experimental_tool_worktree["experimental-tool-worktree"] pkg_experimental_translator["experimental-translator"] @@ -458,6 +456,10 @@ flowchart TD pkg_subprocess_local["subprocess-local"] pkg_win32_process["win32-process"] end + subgraph group_team["packages/team"] + pkg_agent_team["agent-team"] + pkg_tool_agent_team["tool-agent-team"] + end subgraph group_telemetry["packages/telemetry"] pkg_otel["otel"] end @@ -1341,6 +1343,7 @@ flowchart TD pkg_tool_subagent_control --> pkg_llm pkg_tool_subagent_control --> pkg_session pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model @@ -1407,12 +1410,6 @@ flowchart TD pkg_session_reference --> pkg_subagent pkg_session_reference --> pkg_system_prompt pkg_session_reference --> pkg_typert_protocol - pkg_experimental_agent_team --> pkg_agent - pkg_experimental_agent_team --> pkg_llm - pkg_experimental_agent_team --> pkg_session - pkg_experimental_agent_team --> pkg_session_persistence - pkg_experimental_agent_team --> pkg_session_projection - pkg_experimental_agent_team --> pkg_subagent pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1437,6 +1434,13 @@ flowchart TD pkg_sdk_protocol --> pkg_session pkg_sdk_protocol --> pkg_subagent pkg_sdk_protocol --> pkg_user_questions + pkg_agent_team --> pkg_agent + pkg_agent_team --> pkg_llm + pkg_agent_team --> pkg_session + pkg_agent_team --> pkg_session_persistence + pkg_agent_team --> pkg_session_projection + pkg_agent_team --> pkg_subagent + pkg_agent_team --> pkg_typert_protocol pkg_workflow_ptc --> pkg_agent pkg_workflow_ptc --> pkg_llm pkg_workflow_ptc --> pkg_ptc_runtime @@ -1447,11 +1451,6 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory - pkg_experimental_tool_agent_team --> pkg_agent - pkg_experimental_tool_agent_team --> pkg_experimental_agent_team - pkg_experimental_tool_agent_team --> pkg_session - pkg_experimental_tool_agent_team --> pkg_system_prompt - pkg_experimental_tool_agent_team --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_brand @@ -1468,6 +1467,12 @@ flowchart TD pkg_sdk_client --> pkg_llm pkg_sdk_client --> pkg_sdk_protocol pkg_sdk_client --> pkg_session + pkg_tool_agent_team --> pkg_agent + pkg_tool_agent_team --> pkg_agent_team + pkg_tool_agent_team --> pkg_session + pkg_tool_agent_team --> pkg_subagent + pkg_tool_agent_team --> pkg_system_prompt + pkg_tool_agent_team --> pkg_tools pkg_client_test_runtime --> pkg_api_gateway pkg_client_test_runtime --> pkg_api_session_controller pkg_client_test_runtime --> pkg_api_workspace_controller @@ -1497,6 +1502,7 @@ flowchart TD pkg_tool_schedule --> pkg_llm pkg_tool_schedule --> pkg_schedule pkg_tool_schedule --> pkg_subagent + pkg_tool_schedule --> pkg_system_prompt pkg_tool_schedule --> pkg_tools pkg_sdk_jsonrpc_server --> pkg_agent pkg_sdk_jsonrpc_server --> pkg_attachment @@ -1541,6 +1547,7 @@ flowchart TD | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | | [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | +| [`fs-patch`](../packages/fs/fs-patch) | `fs` | — | | [`api-gateway`](../packages/api/gateway) | `api` | — | | [`api-job-controller`](../packages/api/job-controller) | `api` | — | | [`api-remote-access`](../packages/api/remote-access) | `api` | — | @@ -1559,6 +1566,7 @@ flowchart TD | [`client-shortcuts`](../packages/client/shortcuts) | `client` | — | | [`client-store`](../packages/client/store) | `client` | — | | [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — | +| [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — | | [`client-ui-approval`](../packages/client/ui-approval) | `client` | — | | [`client-ui-attachment`](../packages/client/ui-attachment) | `client` | — | | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | @@ -1627,9 +1635,7 @@ flowchart TD | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | `experimental` | — | | [`cua-bundle`](../packages/experimental/cua-bundle) | `experimental` | — | -| [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | — | | [`experimental-badge-skill-bundle`](../packages/experimental/badge-skill-bundle) | `experimental` | — | -| [`experimental-client-ui-agent-team`](../packages/experimental/client-ui-agent-team) | `experimental` | — | | [`experimental-client-ui-claude-code-mods`](../packages/experimental/client-ui-claude-code-mods) | `experimental` | — | | [`experimental-client-ui-stats`](../packages/experimental/client-ui-stats) | `experimental` | — | | [`experimental-client-ui-voice-input`](../packages/experimental/client-ui-voice-input) | `experimental` | — | @@ -1873,24 +1879,24 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | -| [`experimental-agent-team`](../packages/experimental/agent-team) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent) | | [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | -| [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | `experimental` | [`agent`](../packages/core/agent), [`experimental-agent-team`](../packages/experimental/agent-team), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | +| [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | -| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | +| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 9b5b3ee53b..c2440329b3 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -65,6 +65,7 @@ flowchart TD pkg_fs["fs"] pkg_fs_local["fs-local"] pkg_fs_observation_policy["fs-observation-policy"] + pkg_fs_patch["fs-patch"] pkg_fs_sandbox["fs-sandbox"] pkg_tool_fs["tool-fs"] pkg_tool_fs_search["tool-fs-search"] @@ -162,6 +163,7 @@ flowchart TD pkg_client_shortcuts["client-shortcuts"] pkg_client_store["client-store"] pkg_client_ui_agent_preset["client-ui-agent-preset"] + pkg_client_ui_agent_team["client-ui-agent-team"] pkg_client_ui_approval["client-ui-approval"] pkg_client_ui_attachment["client-ui-attachment"] pkg_client_ui_brand_official["client-ui-brand-official"] @@ -271,8 +273,6 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] - pkg_experimental_agent_team["experimental-agent-team"] - pkg_experimental_agent_team_profile["experimental-agent-team-profile"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -281,7 +281,6 @@ flowchart TD pkg_experimental_browser_use_runtime["experimental-browser-use-runtime"] pkg_experimental_browser_use_stagehand_native["experimental-browser-use-stagehand-native"] pkg_experimental_claude_code_mods["experimental-claude-code-mods"] - pkg_experimental_client_ui_agent_team["experimental-client-ui-agent-team"] pkg_experimental_client_ui_claude_code_mods["experimental-client-ui-claude-code-mods"] pkg_experimental_client_ui_cot_translation["experimental-client-ui-cot-translation"] pkg_experimental_client_ui_forge["experimental-client-ui-forge"] @@ -309,7 +308,6 @@ flowchart TD pkg_experimental_speech_to_text_sensevoice["experimental-speech-to-text-sensevoice"] pkg_experimental_subagent_oar["experimental-subagent-oar"] pkg_experimental_terminal_bundle["experimental-terminal-bundle"] - pkg_experimental_tool_agent_team["experimental-tool-agent-team"] pkg_experimental_tool_subagent_oar["experimental-tool-subagent-oar"] pkg_experimental_tool_worktree["experimental-tool-worktree"] pkg_experimental_translator["experimental-translator"] @@ -460,6 +458,10 @@ flowchart TD pkg_subprocess_local["subprocess-local"] pkg_win32_process["win32-process"] end + subgraph group_team["packages/team"] + pkg_agent_team["agent-team"] + pkg_tool_agent_team["tool-agent-team"] + end subgraph group_telemetry["packages/telemetry"] pkg_otel["otel"] end @@ -1343,6 +1345,7 @@ flowchart TD pkg_tool_subagent_control --> pkg_llm pkg_tool_subagent_control --> pkg_session pkg_tool_subagent_control --> pkg_subagent + pkg_tool_subagent_control --> pkg_system_prompt pkg_tool_subagent_control --> pkg_tools pkg_api_session_controller --> pkg_agent pkg_api_session_controller --> pkg_agent_default_model @@ -1409,12 +1412,6 @@ flowchart TD pkg_session_reference --> pkg_subagent pkg_session_reference --> pkg_system_prompt pkg_session_reference --> pkg_typert_protocol - pkg_experimental_agent_team --> pkg_agent - pkg_experimental_agent_team --> pkg_llm - pkg_experimental_agent_team --> pkg_session - pkg_experimental_agent_team --> pkg_session_persistence - pkg_experimental_agent_team --> pkg_session_projection - pkg_experimental_agent_team --> pkg_subagent pkg_experimental_subagent_oar --> pkg_llm pkg_experimental_subagent_oar --> pkg_session pkg_experimental_subagent_oar --> pkg_subagent @@ -1439,6 +1436,13 @@ flowchart TD pkg_sdk_protocol --> pkg_session pkg_sdk_protocol --> pkg_subagent pkg_sdk_protocol --> pkg_user_questions + pkg_agent_team --> pkg_agent + pkg_agent_team --> pkg_llm + pkg_agent_team --> pkg_session + pkg_agent_team --> pkg_session_persistence + pkg_agent_team --> pkg_session_projection + pkg_agent_team --> pkg_subagent + pkg_agent_team --> pkg_typert_protocol pkg_workflow_ptc --> pkg_agent pkg_workflow_ptc --> pkg_llm pkg_workflow_ptc --> pkg_ptc_runtime @@ -1449,11 +1453,6 @@ flowchart TD pkg_workflow_ptc --> pkg_tools pkg_workflow_ptc --> pkg_workflow pkg_workflow_ptc --> pkg_working_directory - pkg_experimental_tool_agent_team --> pkg_agent - pkg_experimental_tool_agent_team --> pkg_experimental_agent_team - pkg_experimental_tool_agent_team --> pkg_session - pkg_experimental_tool_agent_team --> pkg_system_prompt - pkg_experimental_tool_agent_team --> pkg_tools pkg_schedule --> pkg_agent pkg_schedule --> pkg_api_session_controller pkg_schedule --> pkg_brand @@ -1470,6 +1469,12 @@ flowchart TD pkg_sdk_client --> pkg_llm pkg_sdk_client --> pkg_sdk_protocol pkg_sdk_client --> pkg_session + pkg_tool_agent_team --> pkg_agent + pkg_tool_agent_team --> pkg_agent_team + pkg_tool_agent_team --> pkg_session + pkg_tool_agent_team --> pkg_subagent + pkg_tool_agent_team --> pkg_system_prompt + pkg_tool_agent_team --> pkg_tools pkg_client_test_runtime --> pkg_api_gateway pkg_client_test_runtime --> pkg_api_session_controller pkg_client_test_runtime --> pkg_api_workspace_controller @@ -1499,6 +1504,7 @@ flowchart TD pkg_tool_schedule --> pkg_llm pkg_tool_schedule --> pkg_schedule pkg_tool_schedule --> pkg_subagent + pkg_tool_schedule --> pkg_system_prompt pkg_tool_schedule --> pkg_tools pkg_sdk_jsonrpc_server --> pkg_agent pkg_sdk_jsonrpc_server --> pkg_attachment @@ -1543,6 +1549,7 @@ flowchart TD | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | `llm` | — | | [`llm`](../packages/llm/llm) | `llm` | — | | [`scope`](../packages/core/scope) | `core` | — | +| [`fs-patch`](../packages/fs/fs-patch) | `fs` | — | | [`api-gateway`](../packages/api/gateway) | `api` | — | | [`api-job-controller`](../packages/api/job-controller) | `api` | — | | [`api-remote-access`](../packages/api/remote-access) | `api` | — | @@ -1561,6 +1568,7 @@ flowchart TD | [`client-shortcuts`](../packages/client/shortcuts) | `client` | — | | [`client-store`](../packages/client/store) | `client` | — | | [`client-ui-agent-preset`](../packages/client/ui-agent-preset) | `client` | — | +| [`client-ui-agent-team`](../packages/client/ui-agent-team) | `client` | — | | [`client-ui-approval`](../packages/client/ui-approval) | `client` | — | | [`client-ui-attachment`](../packages/client/ui-attachment) | `client` | — | | [`client-ui-brand-official`](../packages/client/ui-brand-official) | `client` | — | @@ -1629,9 +1637,7 @@ flowchart TD | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | | [`client-ui-plugin-recommendations`](../packages/experimental/client-ui-plugin-recommendations) | `experimental` | — | | [`cua-bundle`](../packages/experimental/cua-bundle) | `experimental` | — | -| [`experimental-agent-team-profile`](../packages/experimental/agent-team-profile) | `experimental` | — | | [`experimental-badge-skill-bundle`](../packages/experimental/badge-skill-bundle) | `experimental` | — | -| [`experimental-client-ui-agent-team`](../packages/experimental/client-ui-agent-team) | `experimental` | — | | [`experimental-client-ui-claude-code-mods`](../packages/experimental/client-ui-claude-code-mods) | `experimental` | — | | [`experimental-client-ui-stats`](../packages/experimental/client-ui-stats) | `experimental` | — | | [`experimental-client-ui-voice-input`](../packages/experimental/client-ui-voice-input) | `experimental` | — | @@ -1875,24 +1881,24 @@ flowchart TD | [`subagent-fork-in-process`](../packages/subagent/subagent-fork-in-process) | `subagent` | [`agent`](../packages/core/agent), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent) | | [`subagent-spawn-in-process`](../packages/subagent/subagent-spawn-in-process) | `subagent` | [`subagent`](../packages/subagent/subagent) | | [`tool-subagent`](../packages/subagent/tool-subagent) | `subagent` | [`agent`](../packages/core/agent), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | -| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | +| [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`api-session-controller`](../packages/api/session-controller) | `api` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`api-gateway`](../packages/api/gateway), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-file-upload`](../packages/client/file-upload), [`commands`](../packages/interaction/commands), [`credentials`](../packages/credentials/credentials), [`file-reference`](../packages/context/file-reference), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`native-command`](../packages/util/native-command), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`settings`](../packages/settings/settings), [`skill`](../packages/skill/skill), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol), [`typert-registry`](../packages/typert/registry), [`util-time`](../packages/util/time), [`util-values`](../packages/util/values), [`util-workspace-path`](../packages/util/workspace-path), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) | | [`plugin-market`](../packages/boot/plugin-market) | `boot` | [`plugin-manager`](../packages/boot/plugin-manager), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`headless`](../packages/bundle/headless) | `bundle` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval) | | [`compaction-basic`](../packages/compaction/compaction-basic) | `compaction` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`compaction`](../packages/compaction/compaction), [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`token-meter`](../packages/llm/token-meter) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compaction`](../packages/compaction/compaction), [`llm`](../packages/llm/llm), [`output-retention`](../packages/util/output-retention), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`session-title`](../packages/session/session-title), [`spill`](../packages/spill/spill), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`typert-protocol`](../packages/typert/protocol) | -| [`experimental-agent-team`](../packages/experimental/agent-team) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent) | | [`experimental-subagent-oar`](../packages/experimental/subagent-oar) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-tool-subagent-oar`](../packages/experimental/tool-subagent-oar) | `experimental` | [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | | [`hooks-claude-code`](../packages/experimental/hooks-claude-code) | `experimental` | [`agent`](../packages/core/agent), [`hook-protocol`](../packages/experimental/hook-protocol), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-ralph`](../packages/experimental/tool-ralph) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow) | | [`sdk-protocol`](../packages/sdk/protocol) | `sdk` | [`commands`](../packages/interaction/commands), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| [`agent-team`](../packages/team/agent-team) | `team` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`workflow-ptc`](../packages/workflow/workflow-ptc) | `workflow` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`ptc-runtime`](../packages/ptc-runtime/ptc-runtime), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`workflow`](../packages/workflow/workflow), [`working-directory`](../packages/session/working-directory) | -| [`experimental-tool-agent-team`](../packages/experimental/tool-agent-team) | `experimental` | [`agent`](../packages/core/agent), [`experimental-agent-team`](../packages/experimental/agent-team), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`schedule`](../packages/schedule/schedule) | `schedule` | [`agent`](../packages/core/agent), [`api-session-controller`](../packages/api/session-controller), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`storage-domain`](../packages/storage/storage-domain), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-time`](../packages/util/time), [`workspace`](../packages/workspace/workspace) | | [`sdk-client`](../packages/sdk/client) | `sdk` | [`llm`](../packages/llm/llm), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session) | +| [`tool-agent-team`](../packages/team/tool-agent-team) | `team` | [`agent`](../packages/core/agent), [`agent-team`](../packages/team/agent-team), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`client-test-runtime`](../packages/test-support/client-runtime) | `test-support` | [`api-gateway`](../packages/api/gateway), [`api-session-controller`](../packages/api/session-controller), [`api-workspace-controller`](../packages/api/workspace-controller), [`attachment`](../packages/attachment/attachment), [`client-connection`](../packages/client/connection), [`client-hmr`](../packages/client/hmr), [`client-modules`](../packages/client/modules), [`client-store`](../packages/client/store), [`client-ui-chat`](../packages/client/ui-chat), [`client-ui-context-menu`](../packages/client/ui-context-menu), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-renderer`](../packages/client/ui-renderer), [`client-ui-session`](../packages/client/ui-session), [`client-ui-settings`](../packages/client/ui-settings), [`client-ui-slots`](../packages/client/ui-slots), [`client-web`](../packages/client/web), [`remote-mock`](../packages/test-support/remote-mock), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`typert-protocol`](../packages/typert/protocol) | | [`subagent-dsh-sdk`](../packages/subagent/subagent-dsh-sdk) | `subagent` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`sdk-client`](../packages/sdk/client), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`subprocess`](../packages/subprocess/subprocess) | -| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`tools`](../packages/core/tools) | +| [`tool-schedule`](../packages/schedule/tool-schedule) | `schedule` | [`llm`](../packages/llm/llm), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`schedule`](../packages/schedule/schedule), [`scope`](../packages/core/scope), [`sdk-protocol`](../packages/sdk/protocol), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`user-approval`](../packages/interaction/user-approval), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index dce8443743..8f7366da1c 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 1387c4505dde2faf zh: 48570fa1c13d6910 /session-persistence-event-catalog/persistence-type-fingerprints: - en: 31c6dab0878b05a8 - zh: 176d0f7cbdc3fce3 + en: d334560286daab57 + zh: ddece2494dd2131c /session-persistence-event-catalog/event-envelope: en: 56414ffd00cdc32a zh: 6dc11eb013e95e41 @@ -27,8 +27,8 @@ en: 49891ca9be5ac123 zh: 49891ca9be5ac123 /session-persistence-event-catalog/events/agent-preset/agent-preset-selected-log-only: - en: 9eb4e8ec6b503d83 - zh: 6d96288a30d92b81 + en: 50a6b116a29bc6b0 + zh: 7fce128060557296 /session-persistence-event-catalog/events/approval: en: 9d2ec4c4c3664b9f zh: 9d2ec4c4c3664b9f @@ -174,8 +174,8 @@ en: e5b55405bd2b69f5 zh: e5b55405bd2b69f5 /session-persistence-event-catalog/events/schedule/schedule-change-log-only: - en: e73c202fb99159b6 - zh: b1f43bbd116f83da + en: 6f7f856e4e6275a9 + zh: 92b4fa43a0d7305d /session-persistence-event-catalog/events/session: en: a1ac8f2660a4f61e zh: a1ac8f2660a4f61e @@ -225,17 +225,20 @@ en: a640800a38b3c874 zh: a640800a38b3c874 /session-persistence-event-catalog/events/team/team-member-log-only: - en: a2fe5b8582ef5f46 - zh: 42bfffcde3f3d886 + en: de16dcf2046b402c + zh: b6c73eb866413523 /session-persistence-event-catalog/events/team/team-message-delivered-log-only: - en: 4a716b14e33eab18 - zh: dcde26e4dc40b62e + en: 9c9d9238de0eeb89 + zh: 1f52e5da217dae3d /session-persistence-event-catalog/events/team/team-message-queued-log-only: - en: 05bf873244099da5 - zh: 8a0b62912087f4aa + en: 184b700f0a0363ae + zh: 74b7939bf1bface1 +/session-persistence-event-catalog/events/team/team-mode-log-only: + en: 9481b9f0697707e4 + zh: 83aa2d33782a7b00 /session-persistence-event-catalog/events/team/team-task-log-only: - en: 5ffeb64225feda2a - zh: d58129e189a726fb + en: 16a961e45e7ff021 + zh: c61e51809823dc17 /session-persistence-event-catalog/events/todo: en: 308d4bb4b6b96e35 zh: 308d4bb4b6b96e35 @@ -684,8 +687,11 @@ en: 49351fa0be662888 zh: 49351fa0be662888 /session-persistence-event-catalog/resolved-persistence-types/recall: - en: 5c5a7a7e6517bdf0 - zh: 5c5a7a7e6517bdf0 + en: c04491605decd774 + zh: c04491605decd774 +/session-persistence-event-catalog/resolved-persistence-types/refusal: + en: e55aa9d6983aecde + zh: e55aa9d6983aecde /session-persistence-event-catalog/resolved-persistence-types/rejected: en: b982810b4d04978d zh: b982810b4d04978d @@ -816,8 +822,11 @@ en: 6795a23aa9bc8d2e zh: 6795a23aa9bc8d2e /session-persistence-event-catalog/resolved-persistence-types/team-message-queued: - en: d683235390472024 - zh: d683235390472024 + en: efe4678972a1a64e + zh: efe4678972a1a64e +/session-persistence-event-catalog/resolved-persistence-types/team-mode: + en: 91a387e367e07f73 + zh: 91a387e367e07f73 /session-persistence-event-catalog/resolved-persistence-types/team-task: en: 7aa9286372341561 zh: 7aa9286372341561 @@ -1011,17 +1020,17 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: fd75d1f4b9bd643c - zh: dde892ea9752f298 + en: 054dbd6367e1403d + zh: 5b071d10ae1ec245 /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: c6171fd8144d74b1 - zh: 2f3dd34cc8d7ed92 + en: 58bc64eb0f7fb589 + zh: 8cc8279eb5786ef5 /session-persistence-event-catalog/resolved-persistence-types/epochheader: en: 3bdc8ecd0bdf0c9c zh: 0fe5b75c174ebab4 /session-persistence-event-catalog/resolved-persistence-types/everyscheduledispatchchange: - en: 54c487394ce0db1d - zh: 48d7c9affbe841cb + en: cbd5eb354b025918 + zh: 953ffea4b40b88cf /session-persistence-event-catalog/resolved-persistence-types/feedbackrecord: en: 3b6931556cfe6b9e zh: ce5a5b1d92ce9eac @@ -1125,11 +1134,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: 06b510217b6056c4 - zh: 5b3a1e022f96de57 + en: a3754a186db0e1bb + zh: e9467b50a27889d5 /session-persistence-event-catalog/resolved-persistence-types/message: - en: 7a8ec632289bc7f9 - zh: 5c90cb4f3d5d0a67 + en: 0be581a4095c3493 + zh: 2c815426f3d3717a /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1140,14 +1149,14 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: 65fb012fcc0fa7db - zh: b829c586714e45e2 + en: 702995c31653ab91 + zh: cf60875749663bd3 /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: ddeed90cb6112496 - zh: cefb41765c45b22f + en: 1ec5fd7b1b8050a9 + zh: ee4a3f61be48cd17 /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: 8e96551640079569 - zh: a06d587638d42237 + en: 9e25f2f1513f7b15 + zh: 2723b6aa3d8b723e /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 5f9154ca34235ab9 zh: a833105910ebfa82 @@ -1155,8 +1164,8 @@ en: 6e301c0ea35d9e0e zh: 6fbf1d318db9a4e0 /session-persistence-event-catalog/resolved-persistence-types/oneshotscheduledispatchchange: - en: a3300babe57b6b67 - zh: 4aaf06a149b399c3 + en: c1eb536fc54d2f9a + zh: 50f6b4ce47c8482a /session-persistence-event-catalog/resolved-persistence-types/oneshotsubagentdescriptordata: en: 9ba0cfd5ee9d6a38 zh: 1414fd7468c42651 @@ -1191,14 +1200,14 @@ en: c9fa5343ea99733b zh: d6de41351c57a73f /session-persistence-event-catalog/resolved-persistence-types/schedulechange: - en: 16be53be76c16720 - zh: 38fd164dde86ccac + en: b20a355fde48f699 + zh: 5d0fd858e2dbff06 /session-persistence-event-catalog/resolved-persistence-types/schedulecreatechange: - en: c2d3053c1ce07725 - zh: 0a3201d7c483c7c1 + en: f99a99a41572d9a8 + zh: b29532cdd77e5fd0 /session-persistence-event-catalog/resolved-persistence-types/scheduledeletechange: - en: 35c0b15c285d045e - zh: 8ccce6ea60dd5742 + en: 96e9a9877d2ad882 + zh: be0fd7e1d142afa3 /session-persistence-event-catalog/resolved-persistence-types/sessionheader: en: 0536dab0d2eed6ad zh: 54396338c9917818 @@ -1206,11 +1215,11 @@ en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: 1f9f610fa0e05abf - zh: 11560710a1b871de + en: a537c3568f3f07db + zh: 20c97f3c3fd82e8b /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 465fe144e60dd62f - zh: 29e1029426106c3b + en: efa083dfdcf04208 + zh: eed525395ff9f2e8 /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 9531468264499498 zh: 9da23c0ad2776563 @@ -1236,11 +1245,11 @@ en: 725539dcd5c335ed zh: 5ca08d3667f84ff9 /session-persistence-event-catalog/resolved-persistence-types/subagentdescriptordata: - en: c56821e57987ae9e - zh: 0364f59a472d51da + en: 2b9c68682eec6f78 + zh: 8ef5e64326c1eae6 /session-persistence-event-catalog/resolved-persistence-types/subagentsettledmessagesource: - en: d34acab659e74957 - zh: 25cabc6c9fb44a7e + en: e6d9113dc09f4098 + zh: 3426e4f2f3cc5612 /session-persistence-event-catalog/resolved-persistence-types/surfaceop: en: 737806b6ec54263d zh: b4e44293950ddf8c @@ -1248,26 +1257,26 @@ en: 94876079d6696df9 zh: d25c7ad9f5054eb7 /session-persistence-event-catalog/resolved-persistence-types/systempromptmessagesource: - en: a3eabd0e9fc565dd - zh: fa763aefdbc1bdb8 + en: 967c82dcda03d0d4 + zh: ad590611be701d97 /session-persistence-event-catalog/resolved-persistence-types/teammemberphase: - en: 2bf8f06fe328ab33 - zh: ded602f18e0deadf + en: bf78ae1a14d64469 + zh: 0d5c34aff23a133c /session-persistence-event-catalog/resolved-persistence-types/teammembersnapshot: - en: 8a37845006830548 - zh: b8e7caf6189b92df + en: 1815ad87650025e6 + zh: d2a0dceabcc2090e /session-persistence-event-catalog/resolved-persistence-types/teammessagesnapshot: - en: 9b94faac43ba068f - zh: a83582be6a6a3c1a + en: d7ba2fe5b24c90cb + zh: b26f7e1ef0eccce0 /session-persistence-event-catalog/resolved-persistence-types/teammessagesource: - en: 269f0a4fcbea1c0c - zh: 5f2c50c03c951995 + en: 2ca6c43fc056fd37 + zh: 3d5b5f2917f326fc /session-persistence-event-catalog/resolved-persistence-types/teamtasksnapshot: - en: cfa8230ef5d661b2 - zh: cb40ce86d6778f09 + en: 0c6aac89e3dcb25c + zh: d772017667ffc2a1 /session-persistence-event-catalog/resolved-persistence-types/teamtaskstatus: - en: 9bff57038f472770 - zh: 4eec0e793ae16d53 + en: b6bd8e9986773217 + zh: ed177c2f090964af /session-persistence-event-catalog/resolved-persistence-types/textblock: en: 7ad0f4915397b511 zh: bcaa8bd449927989 @@ -1320,14 +1329,14 @@ en: 778debd61e0284a2 zh: 2cc82ad9e80f18b1 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: 953127f7cf1e0866 - zh: 3613ef1aafd8191a + en: bcd450bc3ade2a1a + zh: e442be61e4391383 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: a15a08beb2b824da - zh: 4fd8dc6b9680c4cf + en: 6f29a4e108379f9a + zh: 2bf0f494b8fcd2b2 /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: 85e537b82f1da7d8 - zh: 73a1b9d4b5d29ab0 + en: e4fc10ce549b51ad + zh: cb29ffcb8003b355 /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: d0a3f9aab18c3de5 zh: 76ac69a835ca4e29 @@ -1350,11 +1359,11 @@ en: 0223d7ffb67ac272 zh: c2a8221caab6d350 /session-persistence-event-catalog/resolved-persistence-types/number~2: - en: 2786fef560851bb4 - zh: 5d787475356b2606 + en: 4147b170f52814af + zh: e78991ac1c41ebec /session-persistence-event-catalog/resolved-persistence-types/string: - en: 1e484bd12747db9f - zh: 1e6fc6aa9066a702 + en: c178efefdf01cade + zh: 200b1ab00ed8bfd3 /session-persistence-event-catalog/resolved-persistence-types/string~2: en: 0089620bf4638263 zh: 1922bef1713094bb @@ -1392,8 +1401,11 @@ en: 9e296094df7462ba zh: e7e3255a3ada9279 /session-persistence-event-catalog/resolved-persistence-types/union-3-variants~4: - en: 5fc89a7ec1cecd78 - zh: dc66aa8e4aae1847 + en: 4ac5570e2b5181be + zh: 447832dc281d0caf +/session-persistence-event-catalog/resolved-persistence-types/union-5-variants: + en: f60d7d997e33f12d + zh: ec049a1c1ab9f8b3 /session-persistence-event-catalog/resolved-persistence-types/union-6-variants: en: ca99faddb359b6bb zh: 5c7ac9b445d9e5be @@ -1410,8 +1422,8 @@ en: c861888d6239b700 zh: a9b2271d3c6b8737 /session-persistence-event-catalog/resolved-persistence-types/agentpreset: - en: 1afbe8196f161601 - zh: a320a36a8928817c + en: 1282a0b3d5fa8d4d + zh: aa533aea643dbefb /session-persistence-event-catalog/resolved-persistence-types/allowedmodels: en: 6178321110ceb69d zh: 0a9d94cab9d57487 @@ -1491,8 +1503,11 @@ en: 9748b4f0facfe9f8 zh: 83ae2cd2cd02b804 /session-persistence-event-catalog/resolved-persistence-types/displayname-providerid-subjectid-tenantid: - en: d2c98ed9b98325ae - zh: bf8c2f7967cf9cc8 + en: c6fbe4268a4430db + zh: 8fec9d6def3c775c +/session-persistence-event-catalog/resolved-persistence-types/enabled: + en: b8b8f28b5bfcd153 + zh: 602d970c3c090522 /session-persistence-event-catalog/resolved-persistence-types/end-start: en: 4b7a8793663d3fef zh: 249459c825d330c3 @@ -1512,11 +1527,11 @@ en: 4cb1c48095df98dc zh: 5a03e44761af559e /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 7d1610d20e987988 - zh: 1297cba0f2a2c73d + en: c21561adcf9398a5 + zh: fac8b21392750aae /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: 4f9635604ed5b84d - zh: 74810a2d049907e6 + en: 081d257a87d8fb2d + zh: 49bdba3da8d5f7e4 /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1533,11 +1548,11 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 8b5c65ce7b57514f - zh: 231494d71e5d635a + en: 7c2c00c4635970ca + zh: 19818a2c43b4c57d /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: 5a3be677a8dc51ff - zh: c5fc8b80f73e72d9 + en: 67b7eda689a3a115 + zh: 5ffdf39f3ee061b2 /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: en: 8e86cd838e3e4a49 zh: f5fec2a8adf1f3cc @@ -1905,17 +1920,17 @@ en: 3216b23c131d0070 zh: 73ca171c6014f16e /session-persistence-event-catalog/resolved-persistence-types/member-teamid-version: - en: 82b0989dad6bbfc0 - zh: 0789b63f1d59b2ed + en: 815fc4d70ba0375b + zh: ae9f6d2a163ff62b /session-persistence-event-catalog/resolved-persistence-types/message-step-turn: en: 86fe91fe83eeb08a zh: 2ebf2f1904829753 /session-persistence-event-catalog/resolved-persistence-types/message-teamid-version: - en: f778769acb264dd5 - zh: eba9b81d04e9f57b + en: edb364403e9e9f84 + zh: d1298ec2e67a0eeb /session-persistence-event-catalog/resolved-persistence-types/messageid-targetid-teamid-version: - en: 91a948ede28ebcb5 - zh: 8a2b0ac6bb68a09e + en: 42a1e343b5e87854 + zh: ae777d3cd40835a6 /session-persistence-event-catalog/resolved-persistence-types/mode-source: en: 3028b222670ce5ad zh: cae4c9437e560d61 @@ -1947,8 +1962,8 @@ en: 5360af614fe753e3 zh: 96427c489cc71de6 /session-persistence-event-catalog/resolved-persistence-types/task-teamid-version: - en: a2fcd46e54b14120 - zh: d9a6e0e50bbff9ad + en: 4952b12d354b8aaf + zh: b8c2ef51b7ab082e /session-persistence-event-catalog/resolved-persistence-types/todos: en: 8ab873d30e062fd5 zh: a138832c6e299ebb @@ -1956,11 +1971,11 @@ en: 374b8adee8d571fa zh: b21057efc58e6490 /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: da6e084997b20cdc - zh: 1780f6fcf3496de1 + en: 2ce26699bb57cf69 + zh: a5fc9ea510a3d458 /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 1a79ed1a97145a14 - zh: d6f658a85c1e65f7 + en: ae0b65d2268c758b + zh: 8244a6d65cfb01f3 /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -2004,11 +2019,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: b9c35ef9a9e1d585 - zh: 7b8ad008c8b7389c + en: f5c7b6c1d3610861 + zh: 2baec8a404127ce8 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: b0a3c504326f42f9 - zh: f13a1c1ca28f7da3 + en: fe3390ea4e6769e3 + zh: 5a25cbdf990ef85f /session-persistence-event-catalog/resolved-persistence-types/type-disabled: en: 585627a50ece4e5f zh: 157837aee3da0ac3 @@ -2082,11 +2097,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: 5a42c1482248e385 - zh: c7ba7d071e4756de + en: d26d1cd97d87f4a6 + zh: 992f1290578da1f4 /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: d88fd740ff167f04 - zh: fe6598a1bf4cd9bf + en: 211b5793ff00bed6 + zh: e8382b4f9adb08fd /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2112,8 +2127,11 @@ en: 2a00c9dbe70dcd8e zh: 96573157cd613c91 /session-persistence-event-catalog/resolved-persistence-types/type-team-message-queued: - en: 3baf69fe52f2d751 - zh: 185be1b973fac77e + en: 735e6acfb6180948 + zh: de7626c523ae57a2 +/session-persistence-event-catalog/resolved-persistence-types/type-team-mode: + en: 0b50dd6b99450d8e + zh: a9f8d2b85e2092af /session-persistence-event-catalog/resolved-persistence-types/type-team-task: en: 872aad5b748d70d5 zh: 396f986a703b76fd @@ -2163,11 +2181,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: a1d9300dd7a7b043 - zh: 3cb1e0e6834e9765 + en: 1f43a7944fa86bcf + zh: faa883c372923440 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: 44035d460a9d926b - zh: 8006b6dbfc58d5ae + en: 28e1108b02b392dc + zh: 0dde507cef7d790e /session-persistence-event-catalog/resolved-persistence-types/type-web-deepseek-search-llm-request: en: 99c8837344178a47 zh: bf746f5678346596 diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 96128feabb..16c1cb90f8 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -23,7 +23,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e) | +| `event:agent/inbox/spliced` | event | `ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -36,7 +36,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f` | [`{ type: "developer/message" }`](#persistence-type-sha256-70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f) | +| `event:developer/message` | event | `70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a` | [`{ type: "developer/message" }`](#persistence-type-sha256-70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -58,7 +58,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c) | +| `event:session/title-llm-request` | event | `d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -68,6 +68,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:team/member` | event | `4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc` | [`{ type: "team/member" }`](#persistence-type-sha256-4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc) | | `event:team/message/delivered` | event | `48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb` | [`{ type: "team/message/delivered" }`](#persistence-type-sha256-48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb) | | `event:team/message/queued` | event | `21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d` | [`{ type: "team/message/queued" }`](#persistence-type-sha256-21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d) | +| `event:team/mode` | event | `920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75` | [`{ type: "team/mode" }`](#persistence-type-sha256-920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75) | | `event:team/task` | event | `d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a` | [`{ type: "team/task" }`](#persistence-type-sha256-d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a) | | `event:todo/write` | event | `b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26` | [`{ type: "todo/write" }`](#persistence-type-sha256-b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26) | | `event:tool-workflow/agent-end` | event | `babf9ee4d1af62bf6c3a8103737f7a5e4e78ce179be835ce05a38803e15884b7` | [`{ type: "tool-workflow/agent-end" }`](#persistence-type-sha256-babf9ee4d1af62bf6c3a8103737f7a5e4e78ce179be835ce05a38803e15884b7) | @@ -80,7 +81,7 @@ The [format references](persistence-changes/historical-formats/README.md) cover | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451` | [`{ type: "user/message" }`](#persistence-type-sha256-5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451) | +| `event:user/message` | event | `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | [`{ type: "user/message" }`](#persistence-type-sha256-dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -198,15 +199,14 @@ Source: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/type * The session's agent preset was chosen after creation, while the session * was still blank. Log-only: it records the composition later turns ran * under, so a resumed or forked session rebuilds the same one instead of - * the header's creation-time value. In a child Session, an occurrence - * before its first own `subagent/descriptor` marks an independent spawn - * selection that cold resume restores instead of joining the parent's - * composition (`dsh-subagent` README, "Restoring child composition"). + * the header's creation-time value. Subagent restoration reads this saved + * selection independently of its creator (`dsh-subagent` README, + * "Restoring child composition"). */ 'agent-preset/selected': { agentPreset: string } ``` -Source: [`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) +Source: [`packages/preset/agent-preset-registry/src/session.ts:30`](../packages/preset/agent-preset-registry/src/session.ts) ### `approval/*` @@ -805,15 +805,15 @@ Source: [`packages/sandbox/sandbox-policy/src/session-mode.ts:33`](../packages/s ```ts persistence-catalog /** - * Versioned Schedule mutation. The owning package validates the complete - * session-local transition stream before accepting a candidate event. + * Historical version-1 Session-local reminder mutation. New tasks live in Host storage; + * these events remain inert and never populate the Host task store. */ 'schedule/change': ScheduleChange ``` Types: [ScheduleChange](subsystems/schedule.md) -Source: [`packages/schedule/schedule/src/types.ts:371`](../packages/schedule/schedule/src/types.ts) +Source: [`packages/schedule/schedule/src/types.ts:625`](../packages/schedule/schedule/src/types.ts) ### `session/*` @@ -1009,13 +1009,13 @@ Source: [`packages/core/session/src/types.ts:338`](../packages/core/session/src/ #### `team/member` — log-only ```ts persistence-catalog -/** Whole teammate lifecycle value, stored only in the Team Lead Session. */ +/** Historical teammate lifecycle value; new teammates are continuable entries in the Lead's subagent catalog. */ 'team/member': { version: 2; teamId: TeamId; member: TeamMemberSnapshot } ``` Types: [TeamId](subsystems/agent-team.md) · [TeamMemberSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/team/agent-team/src/types.ts:173`](../packages/team/agent-team/src/types.ts) @@ -1033,7 +1033,7 @@ Source: [`packages/experimental/agent-team/src/types.ts:230`](../packages/experi Types: [TeamId](subsystems/agent-team.md) · [TeamMessageId](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/team/agent-team/src/types.ts:179`](../packages/team/agent-team/src/types.ts) @@ -1046,7 +1046,18 @@ Source: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experi Types: [TeamId](subsystems/agent-team.md) · [TeamMessageSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/team/agent-team/src/types.ts:177`](../packages/team/agent-team/src/types.ts) + + + +#### `team/mode` — log-only + +```ts persistence-catalog +/** User-selected Team mode; child Agents use the selection of their runtime root. */ +'team/mode': { enabled: boolean } +``` + +Source: [`packages/team/agent-team/src/types.ts:171`](../packages/team/agent-team/src/types.ts) @@ -1059,7 +1070,7 @@ Source: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experi Types: [TeamId](subsystems/agent-team.md) · [TeamTaskSnapshot](subsystems/agent-team.md) -Source: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +Source: [`packages/team/agent-team/src/types.ts:175`](../packages/team/agent-team/src/types.ts) ### `todo/*` @@ -2355,6 +2366,14 @@ SHA-256: `383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f` `"recall"` + + +### `"refusal"` + +SHA-256: `4a561c111a78d4520e850c93795369ea169ff86abd082aee86c8fd38121a65aa` + +`"refusal"` + ### `"rejected"` @@ -2707,6 +2726,14 @@ SHA-256: `4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159` `"team/message/queued"` + + +### `"team/mode"` + +SHA-256: `d8a476d2c6fd30df6ec0e799f91716d1518c780d23b4121dce545abfcfb7c5a5` + +`"team/mode"` + ### `"team/task"` @@ -3383,7 +3410,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web | `body` | required | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | required | `string` | - + @@ -3391,7 +3418,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:55`](../packages/web ### `DeveloperMessage` -SHA-256: `64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428` +SHA-256: `01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796` Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3400,7 +3427,7 @@ Sources: [`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -3435,7 +3462,7 @@ Sources: [`packages/core/session/src/types.ts:246`](../packages/core/session/src SHA-256: `e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344` -Sources: [`packages/schedule/schedule/src/types.ts:244`](../packages/schedule/schedule/src/types.ts) +Sources: [`packages/schedule/schedule/src/types.ts:220`](../packages/schedule/schedule/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4099,7 +4126,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -4107,15 +4134,15 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `c78b9097bfae83cd08f0a98a92730236ba80ac61d712046959e4fc7f28aa1f36` +SHA-256: `e272493e3ea0b33b2e1d64b6a80e9d8bd3d1d466cc115f2facbdd598f8644a39` Sources: [`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428) -- [`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce) +- [`DeveloperMessage`](#persistence-type-sha256-01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796) +- [`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4192,7 +4219,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4200,7 +4227,7 @@ One of: ### `MessageSource` -SHA-256: `7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a` +SHA-256: `b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72` Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) @@ -4279,7 +4306,7 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `session-reference` | `"recall"` | `references`: [`{ capturedFormatVersion?, capturedThroughSeq, compacted, inputIndex, … }[]`](#persistence-type-sha256-df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18); `version`: `1` | [`SessionReferenceSource`](#persistence-type-sha256-f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f) | | `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099) | | `skill-invocation` | `"instructions"` | `name`: `string` | [`SkillInvocationSource`](#persistence-type-sha256-672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db) | -| `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a) | +| `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-848639f8787f035b480ec53cb5686850897c5e8006d87ca231cd8a9ee8634936) | | `system-prompt` | not declared | none | [`SystemPromptMessageSource`](#persistence-type-sha256-65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad) | | `team-message` | not declared | `messageId`: `string`; `senderId`: `string`; `senderName`: `string`; `teamId`: `string` | [`TeamMessageSource`](#persistence-type-sha256-2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0) | | `time-context` | `"catalog"` | none | [`{ kind: "time-context", form: "catalog" }`](#persistence-type-sha256-85fe96bf15d5c7559eec3bae4d6cf1a76fda9f5be05a29c2830cff560cab0c0d) | @@ -4325,13 +4352,13 @@ Sources: [`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | not declared | none | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `ff2cbb53582d1827b02622482246979942f59e07e0393b76a161251423549e72` +SHA-256: `95b5cf90ea1f57da3319184d6f5f3811d0f651aa9113591c10e81c3d1e9b9f70` -Array of [`Message`](#persistence-type-sha256-c78b9097bfae83cd08f0a98a92730236ba80ac61d712046959e4fc7f28aa1f36). +Array of [`Message`](#persistence-type-sha256-e272493e3ea0b33b2e1d64b6a80e9d8bd3d1d466cc115f2facbdd598f8644a39). @@ -4380,7 +4407,7 @@ Sources: [`packages/core/agent/src/types.ts:79`](../packages/core/agent/src/type SHA-256: `8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af` -Sources: [`packages/schedule/schedule/src/types.ts:237`](../packages/schedule/schedule/src/types.ts) +Sources: [`packages/schedule/schedule/src/types.ts:213`](../packages/schedule/schedule/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4593,7 +4620,7 @@ One of: SHA-256: `2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f` -Sources: [`packages/schedule/schedule/src/types.ts:256`](../packages/schedule/schedule/src/types.ts) +Sources: [`packages/schedule/schedule/src/types.ts:232`](../packages/schedule/schedule/src/types.ts) One of: @@ -4612,7 +4639,7 @@ One of: SHA-256: `eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4` -Sources: [`packages/schedule/schedule/src/types.ts:223`](../packages/schedule/schedule/src/types.ts) +Sources: [`packages/schedule/schedule/src/types.ts:199`](../packages/schedule/schedule/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4630,7 +4657,7 @@ Sources: [`packages/schedule/schedule/src/types.ts:223`](../packages/schedule/sc SHA-256: `18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0` -Sources: [`packages/schedule/schedule/src/types.ts:230`](../packages/schedule/schedule/src/types.ts) +Sources: [`packages/schedule/schedule/src/types.ts:206`](../packages/schedule/schedule/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4699,7 +4726,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4707,7 +4734,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54` +SHA-256: `601327bedca5f98a0fa4c27133bd35749f3af2baaaacf53badf074e59cea5d25` Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4715,7 +4742,7 @@ Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/sess |---|---|---| | `maxTokens` | required | `number` | | `messageSeqs` | required | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | required | [`Message[]`](#persistence-type-sha256-ff2cbb53582d1827b02622482246979942f59e07e0393b76a161251423549e72) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-95b5cf90ea1f57da3319184d6f5f3811d0f651aa9113591c10e81c3d1e9b9f70) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -4884,7 +4911,7 @@ One of: - [`ContinuableSubagentDescriptorData`](#persistence-type-sha256-6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f) - [`OneShotSubagentDescriptorData`](#persistence-type-sha256-5f758f3de5f00c18968a7c6d347083aac5c9ae13f6a79c78f6611b23c4973564) - + @@ -4892,7 +4919,7 @@ One of: ### `SubagentSettledMessageSource` -SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` +SHA-256: `848639f8787f035b480ec53cb5686850897c5e8006d87ca231cd8a9ee8634936` Sources: [`packages/subagent/subagent/src/continuation-messages.ts:29`](../packages/subagent/subagent/src/continuation-messages.ts) @@ -4901,6 +4928,7 @@ Sources: [`packages/subagent/subagent/src/continuation-messages.ts:29`](../packa | `form` | required | `"notice"` | | `kind` | required | `"subagent-settled"` | | `senderSessionId` | required | `string` | +| `stopReason` | optional | [`union (5 variants)`](#persistence-type-sha256-866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0) | | `summary` | required | `string` | @@ -4957,7 +4985,7 @@ Sources: [`packages/llm/llm/src/message.ts:35`](../packages/llm/llm/src/message. - + @@ -4965,7 +4993,7 @@ Sources: [`packages/llm/llm/src/message.ts:35`](../packages/llm/llm/src/message. SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` -Sources: [`packages/experimental/agent-team/src/types.ts:45`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:47`](../packages/team/agent-team/src/types.ts) One of: @@ -4975,7 +5003,7 @@ One of: - + @@ -4983,7 +5011,7 @@ One of: SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` -Sources: [`packages/experimental/agent-team/src/types.ts:48`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:50`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -4997,7 +5025,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:48`](../packages/experi - + @@ -5005,7 +5033,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:48`](../packages/experi SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` -Sources: [`packages/experimental/agent-team/src/types.ts:129`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:108`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5017,7 +5045,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:129`](../packages/exper - + @@ -5025,7 +5053,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:129`](../packages/exper SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` -Sources: [`packages/experimental/agent-team/src/types.ts:138`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:117`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5037,7 +5065,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:138`](../packages/exper - + @@ -5045,7 +5073,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:138`](../packages/exper SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` -Sources: [`packages/experimental/agent-team/src/types.ts:75`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:64`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -5060,7 +5088,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:75`](../packages/experi - + @@ -5068,7 +5096,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:75`](../packages/experi SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` -Sources: [`packages/experimental/agent-team/src/types.ts:72`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:61`](../packages/team/agent-team/src/types.ts) One of: @@ -5390,7 +5418,7 @@ Sources: [`packages/core/session/src/types.ts:238`](../packages/core/session/src | `interrupted` | not declared | none | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | not declared | none | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5398,7 +5426,7 @@ Sources: [`packages/core/session/src/types.ts:238`](../packages/core/session/src ### `UserMessage` -SHA-256: `4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce` +SHA-256: `613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1` Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5407,19 +5435,19 @@ Sources: [`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72) | Source compatibility: `source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. Attribution-only additions: `action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `7c203f3d4dfa6638ff2601247cc7ca5d46731d2c614aa61217475b9eb1fbd0b3` +SHA-256: `690583582246babf6120f16eefd849dd760c5ec84619014951af403a1b3032c0` -Array of [`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce). +Array of [`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1). @@ -5537,12 +5565,6 @@ Array of `number`. - - - - - - @@ -5575,6 +5597,12 @@ Array of `number`. + + + + + + @@ -5611,7 +5639,7 @@ Array of `number`. SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -Sources: [`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +Sources: [`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -5755,6 +5783,20 @@ One of: - `"in_progress"` - `"pending"` + + +### `union (5 variants)` + +SHA-256: `866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0` + +One of: + +- `"aborted"` +- `"completed"` +- `"error"` +- `"max-tokens"` +- `"refusal"` + ### `union (6 variants)` @@ -5820,7 +5862,7 @@ Sources: [`packages/plan/plan-mode/src/index.ts:53`](../packages/plan/plan-mode/ SHA-256: `6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406` -Sources: [`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) +Sources: [`packages/preset/agent-preset-registry/src/session.ts:30`](../packages/preset/agent-preset-registry/src/session.ts) | Property | Presence | Type | |---|---|---| @@ -6234,6 +6276,18 @@ Sources: [`packages/experimental/liveshare/src/host/viewer-principal.ts:29`](../ | `subjectId` | required | `string` | | `tenantId` | required | `string` | + + +### `{ enabled }` + +SHA-256: `c2a13242efc3bea4b36a843ddf1524ff4d33c765a71b582fa1fdbfa4fa148434` + +Sources: [`packages/team/agent-team/src/types.ts:171`](../packages/team/agent-team/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `enabled` | required | `boolean` | + ### `{ end, start }` @@ -6330,18 +6384,18 @@ Sources: [`packages/core/session/src/types.ts:398`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `53d4f8256bc58109468ea358ac54d437760cd765012360cafe72a401e6a41d4a` +SHA-256: `65377a76c6a58f785d95b89f89f2e13d289cb88a70ea74939d0ec08f429f0a6e` Sources: [`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6425,17 +6479,17 @@ Sources: [`packages/core/session/src/types.ts:435`](../packages/core/session/src |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `d4d960185026266ed7bd127be1e252234689e8b4890c7c2677a644ba58f35401` +SHA-256: `e1880c67e735e228f3555df8a55a492db2c0b0c71bc8859e938e184a46c7db51` Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-7c203f3d4dfa6638ff2601247cc7ca5d46731d2c614aa61217475b9eb1fbd0b3) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-690583582246babf6120f16eefd849dd760c5ec84619014951af403a1b3032c0) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -7858,7 +7912,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:61`](../packages/web SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` -Sources: [`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:173`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7886,7 +7940,7 @@ Sources: [`packages/core/session/src/types.ts:338`](../packages/core/session/src SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` -Sources: [`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:177`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -7900,7 +7954,7 @@ Sources: [`packages/experimental/agent-team/src/types.ts:234`](../packages/exper SHA-256: `0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1` -Sources: [`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:179`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8046,7 +8100,7 @@ Sources: [`packages/compaction/compaction-image-offload/src/projection.ts:25`](. SHA-256: `a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c` -Sources: [`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +Sources: [`packages/team/agent-team/src/types.ts:175`](../packages/team/agent-team/src/types.ts) | Property | Presence | Type | |---|---|---| @@ -8094,17 +8148,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e` +SHA-256: `ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-d4d960185026266ed7bd127be1e252234689e8b4890c7c2677a644ba58f35401) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-e1880c67e735e228f3555df8a55a492db2c0b0c71bc8859e938e184a46c7db51) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8345,17 +8399,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f` +SHA-256: `70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-53d4f8256bc58109468ea358ac54d437760cd765012360cafe72a401e6a41d4a) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-65377a76c6a58f785d95b89f89f2e13d289cb88a70ea74939d0ec08f429f0a6e) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8755,17 +8809,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c` +SHA-256: `d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-601327bedca5f98a0fa4c27133bd35749f3af2baaaacf53badf074e59cea5d25) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8917,6 +8971,22 @@ SHA-256: `21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d` | `time` | required | `number` | | `type` | required | `"team/message/queued"` | + + + + +### `{ type: "team/mode" }` + +SHA-256: `920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75` + +| Property | Presence | Type | +|---|---|---| +| `data` | required | [`{ enabled }`](#persistence-type-sha256-c2a13242efc3bea4b36a843ddf1524ff4d33c765a71b582fa1fdbfa4fa148434) | +| `ignorable` | optional | `true` | +| `seq` | required | `number` | +| `time` | required | `number` | +| `type` | required | `"team/mode"` | + @@ -9188,17 +9258,17 @@ Sources: [`packages/llm/llm/src/types.ts:502`](../packages/llm/llm/src/types.ts) | `type` | required | `"usage"` | | `usage` | required | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451` +SHA-256: `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index c890b50507..5e045309fd 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -25,7 +25,7 @@ | `JsonlHeaderLine` | header | `18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f` | [`HeaderLine`](#persistence-type-sha256-18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f) | | `SessionEventEnvelope` | envelope | `5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc` | [`union (3 variants)`](#persistence-type-sha256-5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc) | | `event:agent-preset/selected` | event | `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | [`{ type: "agent-preset/selected" }`](#persistence-type-sha256-a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b) | -| `event:agent/inbox/spliced` | event | `cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e) | +| `event:agent/inbox/spliced` | event | `ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482) | | `event:approval/asked` | event | `3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1` | [`{ type: "approval/asked" }`](#persistence-type-sha256-3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1) | | `event:approval/decided` | event | `bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3` | [`{ type: "approval/decided" }`](#persistence-type-sha256-bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3) | | `event:approval/policy` | event | `26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78` | [`{ type: "approval/policy" }`](#persistence-type-sha256-26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78) | @@ -38,7 +38,7 @@ | `event:compaction/start` | event | `db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965` | [`{ type: "compaction/start" }`](#persistence-type-sha256-db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965) | | `event:compaction/summary` | event | `e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602` | [`{ type: "compaction/summary" }`](#persistence-type-sha256-e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602) | | `event:deliverables/presented` | event | `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | [`{ type: "deliverables/presented" }`](#persistence-type-sha256-13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176) | -| `event:developer/message` | event | `70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f` | [`{ type: "developer/message" }`](#persistence-type-sha256-70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f) | +| `event:developer/message` | event | `70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a` | [`{ type: "developer/message" }`](#persistence-type-sha256-70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a) | | `event:feedback/message-delete` | event | `3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796` | [`{ type: "feedback/message-delete" }`](#persistence-type-sha256-3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796) | | `event:feedback/message-put` | event | `b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf` | [`{ type: "feedback/message-put" }`](#persistence-type-sha256-b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf) | | `event:feedback/record` | event | `b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8` | [`{ type: "feedback/record" }`](#persistence-type-sha256-b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8) | @@ -60,7 +60,7 @@ | `event:session-log-deepseek/delivery-accepted` | event | `d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9` | [`{ type: "session-log-deepseek/delivery-accepted" }`](#persistence-type-sha256-d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9) | | `event:session/end-seed` | event | `5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e` | [`{ type: "session/end-seed" }`](#persistence-type-sha256-5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e) | | `event:session/title` | event | `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | [`{ type: "session/title" }`](#persistence-type-sha256-1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5) | -| `event:session/title-llm-request` | event | `2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c) | +| `event:session/title-llm-request` | event | `d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca) | | `event:step/end` | event | `e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05` | [`{ type: "step/end" }`](#persistence-type-sha256-e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05) | | `event:step/start` | event | `4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986` | [`{ type: "step/start" }`](#persistence-type-sha256-4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986) | | `event:subagent/catalog` | event | `53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac) | @@ -70,6 +70,7 @@ | `event:team/member` | event | `4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc` | [`{ type: "team/member" }`](#persistence-type-sha256-4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc) | | `event:team/message/delivered` | event | `48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb` | [`{ type: "team/message/delivered" }`](#persistence-type-sha256-48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb) | | `event:team/message/queued` | event | `21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d` | [`{ type: "team/message/queued" }`](#persistence-type-sha256-21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d) | +| `event:team/mode` | event | `920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75` | [`{ type: "team/mode" }`](#persistence-type-sha256-920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75) | | `event:team/task` | event | `d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a` | [`{ type: "team/task" }`](#persistence-type-sha256-d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a) | | `event:todo/write` | event | `b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26` | [`{ type: "todo/write" }`](#persistence-type-sha256-b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26) | | `event:tool-workflow/agent-end` | event | `babf9ee4d1af62bf6c3a8103737f7a5e4e78ce179be835ce05a38803e15884b7` | [`{ type: "tool-workflow/agent-end" }`](#persistence-type-sha256-babf9ee4d1af62bf6c3a8103737f7a5e4e78ce179be835ce05a38803e15884b7) | @@ -82,7 +83,7 @@ | `event:tool/result` | event | `7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397` | [`{ type: "tool/result" }`](#persistence-type-sha256-7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397) | | `event:turn/end` | event | `0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce` | [`{ type: "turn/end" }`](#persistence-type-sha256-0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce) | | `event:turn/start` | event | `aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8` | [`{ type: "turn/start" }`](#persistence-type-sha256-aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8) | -| `event:user/message` | event | `5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451` | [`{ type: "user/message" }`](#persistence-type-sha256-5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451) | +| `event:user/message` | event | `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | [`{ type: "user/message" }`](#persistence-type-sha256-dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450) | | `event:web/deepseek-search-llm-request` | event | `0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52` | [`{ type: "web/deepseek-search-llm-request" }`](#persistence-type-sha256-0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52) | | `event:working-directory/change` | event | `124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3` | [`{ type: "working-directory/change" }`](#persistence-type-sha256-124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3) | | `event:workspace/changes` | event | `e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72` | [`{ type: "workspace/changes" }`](#persistence-type-sha256-e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72) | @@ -200,15 +201,14 @@ export type SessionEvent = { * The session's agent preset was chosen after creation, while the session * was still blank. Log-only: it records the composition later turns ran * under, so a resumed or forked session rebuilds the same one instead of - * the header's creation-time value. In a child Session, an occurrence - * before its first own `subagent/descriptor` marks an independent spawn - * selection that cold resume restores instead of joining the parent's - * composition (`dsh-subagent` README, "Restoring child composition"). + * the header's creation-time value. Subagent restoration reads this saved + * selection independently of its creator (`dsh-subagent` README, + * "Restoring child composition"). */ 'agent-preset/selected': { agentPreset: string } ``` -来源:[`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) +来源:[`packages/preset/agent-preset-registry/src/session.ts:30`](../packages/preset/agent-preset-registry/src/session.ts) ### `approval/*` @@ -807,15 +807,15 @@ export type SessionEvent = { ```ts persistence-catalog /** - * Versioned Schedule mutation. The owning package validates the complete - * session-local transition stream before accepting a candidate event. + * Historical version-1 Session-local reminder mutation. New tasks live in Host storage; + * these events remain inert and never populate the Host task store. */ 'schedule/change': ScheduleChange ``` 类型:[ScheduleChange](subsystems/schedule.zh.md) -来源:[`packages/schedule/schedule/src/types.ts:371`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:625`](../packages/schedule/schedule/src/types.ts) ### `session/*` @@ -1011,13 +1011,13 @@ export type SessionEvent = { #### `team/member` — log-only ```ts persistence-catalog -/** Whole teammate lifecycle value, stored only in the Team Lead Session. */ +/** Historical teammate lifecycle value; new teammates are continuable entries in the Lead's subagent catalog. */ 'team/member': { version: 2; teamId: TeamId; member: TeamMemberSnapshot } ``` 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMemberSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:173`](../packages/team/agent-team/src/types.ts) @@ -1035,7 +1035,7 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMessageId](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:179`](../packages/team/agent-team/src/types.ts) @@ -1048,7 +1048,18 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamMessageSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:177`](../packages/team/agent-team/src/types.ts) + + + +#### `team/mode` — log-only + +```ts persistence-catalog +/** User-selected Team mode; child Agents use the selection of their runtime root. */ +'team/mode': { enabled: boolean } +``` + +来源:[`packages/team/agent-team/src/types.ts:171`](../packages/team/agent-team/src/types.ts) @@ -1061,7 +1072,7 @@ export type SessionEvent = { 类型:[TeamId](subsystems/agent-team.zh.md) · [TeamTaskSnapshot](subsystems/agent-team.zh.md) -来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:175`](../packages/team/agent-team/src/types.ts) ### `todo/*` @@ -2357,6 +2368,14 @@ SHA-256: `383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f` `"recall"` + + +### `"refusal"` + +SHA-256: `4a561c111a78d4520e850c93795369ea169ff86abd082aee86c8fd38121a65aa` + +`"refusal"` + ### `"rejected"` @@ -2709,6 +2728,14 @@ SHA-256: `4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159` `"team/message/queued"` + + +### `"team/mode"` + +SHA-256: `d8a476d2c6fd30df6ec0e799f91716d1518c780d23b4121dce545abfcfb7c5a5` + +`"team/mode"` + ### `"team/task"` @@ -3385,7 +3412,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` | `body` | 必需 | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | 必需 | `string` | - + @@ -3393,7 +3420,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` ### `DeveloperMessage` -SHA-256: `64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428` +SHA-256: `01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796` 来源:[`packages/llm/llm/src/message.ts:157`](../packages/llm/llm/src/message.ts) @@ -3402,7 +3429,7 @@ SHA-256: `64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -3437,7 +3464,7 @@ SHA-256: `9a930283b91d493d6347146f2475bb107294b379415ca02162354f46a64164f7` SHA-256: `e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344` -来源:[`packages/schedule/schedule/src/types.ts:244`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:220`](../packages/schedule/schedule/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4101,7 +4128,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -4109,15 +4136,15 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `c78b9097bfae83cd08f0a98a92730236ba80ac61d712046959e4fc7f28aa1f36` +SHA-256: `e272493e3ea0b33b2e1d64b6a80e9d8bd3d1d466cc115f2facbdd598f8644a39` 来源:[`packages/llm/llm/src/message.ts:196`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428) -- [`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce) +- [`DeveloperMessage`](#persistence-type-sha256-01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796) +- [`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4194,7 +4221,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4202,7 +4229,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a` +SHA-256: `b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72` 来源:[`packages/llm/llm/src/message.ts:136`](../packages/llm/llm/src/message.ts) @@ -4281,7 +4308,7 @@ SHA-256: `7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a` | `session-reference` | `"recall"` | `references`: [`{ capturedFormatVersion?, capturedThroughSeq, compacted, inputIndex, … }[]`](#persistence-type-sha256-df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18); `version`: `1` | [`SessionReferenceSource`](#persistence-type-sha256-f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f) | | `skill-catalog` | `"catalog"` | `entries`: [`{ description, name }[]`](#persistence-type-sha256-aba175fb20ffc71112c55efe70458ff5d7dbfb83501892b4ba8d077f0ea5d7ba) | [`SkillCatalogSource`](#persistence-type-sha256-65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099) | | `skill-invocation` | `"instructions"` | `name`: `string` | [`SkillInvocationSource`](#persistence-type-sha256-672c4aa2a9b736e3d6e5da6346d2e2ed5e3573f2d0baafa18e7407c9f3fee3db) | -| `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a) | +| `subagent-settled` | `"notice"` | `senderSessionId`: `string`; `summary`: `string` | [`SubagentSettledMessageSource`](#persistence-type-sha256-848639f8787f035b480ec53cb5686850897c5e8006d87ca231cd8a9ee8634936) | | `system-prompt` | 未声明 | 无 | [`SystemPromptMessageSource`](#persistence-type-sha256-65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad) | | `team-message` | 未声明 | `messageId`: `string`; `senderId`: `string`; `senderName`: `string`; `teamId`: `string` | [`TeamMessageSource`](#persistence-type-sha256-2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0) | | `time-context` | `"catalog"` | 无 | [`{ kind: "time-context", form: "catalog" }`](#persistence-type-sha256-85fe96bf15d5c7559eec3bae4d6cf1a76fda9f5be05a29c2830cff560cab0c0d) | @@ -4327,13 +4354,13 @@ SHA-256: `7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a` | `webhook` | `"notice"` | `deliveryId`: `string`; `provider`: `string`; `ruleId`: `string`; `source`: `string`; `summary`: `string` | [`{ kind: "webhook", form: "notice" }`](#persistence-type-sha256-9edc162949abf93bd5ff049191b345454ba104f583937ce5580fb50f067d2b94) | | `working-directory` | 未声明 | 无 | [`{ kind: "working-directory" }`](#persistence-type-sha256-2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5) | - + ### `Message[]` -SHA-256: `ff2cbb53582d1827b02622482246979942f59e07e0393b76a161251423549e72` +SHA-256: `95b5cf90ea1f57da3319184d6f5f3811d0f651aa9113591c10e81c3d1e9b9f70` -[`Message`](#persistence-type-sha256-c78b9097bfae83cd08f0a98a92730236ba80ac61d712046959e4fc7f28aa1f36) 的数组。 +[`Message`](#persistence-type-sha256-e272493e3ea0b33b2e1d64b6a80e9d8bd3d1d466cc115f2facbdd598f8644a39) 的数组。 @@ -4382,7 +4409,7 @@ SHA-256: `f09e5e7acf5ff5ccd193ff2eeec015fa2ff7c29d98bc465f8c3302058d47e29b` SHA-256: `8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af` -来源:[`packages/schedule/schedule/src/types.ts:237`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:213`](../packages/schedule/schedule/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4595,7 +4622,7 @@ SHA-256: `fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd` SHA-256: `2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f` -来源:[`packages/schedule/schedule/src/types.ts:256`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:232`](../packages/schedule/schedule/src/types.ts) 以下类型之一: @@ -4614,7 +4641,7 @@ SHA-256: `2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f` SHA-256: `eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4` -来源:[`packages/schedule/schedule/src/types.ts:223`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:199`](../packages/schedule/schedule/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4632,7 +4659,7 @@ SHA-256: `eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4` SHA-256: `18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0` -来源:[`packages/schedule/schedule/src/types.ts:230`](../packages/schedule/schedule/src/types.ts) +来源:[`packages/schedule/schedule/src/types.ts:206`](../packages/schedule/schedule/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4701,7 +4728,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4709,7 +4736,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54` +SHA-256: `601327bedca5f98a0fa4c27133bd35749f3af2baaaacf53badf074e59cea5d25` 来源:[`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4717,7 +4744,7 @@ SHA-256: `7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54` |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-ff2cbb53582d1827b02622482246979942f59e07e0393b76a161251423549e72) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-95b5cf90ea1f57da3319184d6f5f3811d0f651aa9113591c10e81c3d1e9b9f70) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -4886,7 +4913,7 @@ SHA-256: `86d1d0e9cfebb240421187e3dc37fb71cc38a1501885cf32f8f9adef7b0a2bde` - [`ContinuableSubagentDescriptorData`](#persistence-type-sha256-6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f) - [`OneShotSubagentDescriptorData`](#persistence-type-sha256-5f758f3de5f00c18968a7c6d347083aac5c9ae13f6a79c78f6611b23c4973564) - + @@ -4894,7 +4921,7 @@ SHA-256: `86d1d0e9cfebb240421187e3dc37fb71cc38a1501885cf32f8f9adef7b0a2bde` ### `SubagentSettledMessageSource` -SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` +SHA-256: `848639f8787f035b480ec53cb5686850897c5e8006d87ca231cd8a9ee8634936` 来源:[`packages/subagent/subagent/src/continuation-messages.ts:29`](../packages/subagent/subagent/src/continuation-messages.ts) @@ -4903,6 +4930,7 @@ SHA-256: `4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a` | `form` | 必需 | `"notice"` | | `kind` | 必需 | `"subagent-settled"` | | `senderSessionId` | 必需 | `string` | +| `stopReason` | 可选 | [`union (5 variants)`](#persistence-type-sha256-866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0) | | `summary` | 必需 | `string` | @@ -4959,7 +4987,7 @@ SHA-256: `65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad` - + @@ -4967,7 +4995,7 @@ SHA-256: `65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad` SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` -来源:[`packages/experimental/agent-team/src/types.ts:45`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:47`](../packages/team/agent-team/src/types.ts) 以下类型之一: @@ -4977,7 +5005,7 @@ SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` - + @@ -4985,7 +5013,7 @@ SHA-256: `dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd` SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` -来源:[`packages/experimental/agent-team/src/types.ts:48`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:50`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -4999,7 +5027,7 @@ SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` - + @@ -5007,7 +5035,7 @@ SHA-256: `6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25` SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` -来源:[`packages/experimental/agent-team/src/types.ts:129`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:108`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5019,7 +5047,7 @@ SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` - + @@ -5027,7 +5055,7 @@ SHA-256: `2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e` SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` -来源:[`packages/experimental/agent-team/src/types.ts:138`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:117`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5039,7 +5067,7 @@ SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` - + @@ -5047,7 +5075,7 @@ SHA-256: `2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0` SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` -来源:[`packages/experimental/agent-team/src/types.ts:75`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:64`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -5062,7 +5090,7 @@ SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` - + @@ -5070,7 +5098,7 @@ SHA-256: `51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357` SHA-256: `b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943` -来源:[`packages/experimental/agent-team/src/types.ts:72`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:61`](../packages/team/agent-team/src/types.ts) 以下类型之一: @@ -5392,7 +5420,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5400,7 +5428,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce` +SHA-256: `613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1` 来源:[`packages/llm/llm/src/message.ts:162`](../packages/llm/llm/src/message.ts) @@ -5409,19 +5437,19 @@ SHA-256: `4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. 仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `7c203f3d4dfa6638ff2601247cc7ca5d46731d2c614aa61217475b9eb1fbd0b3` +SHA-256: `690583582246babf6120f16eefd849dd760c5ec84619014951af403a1b3032c0` -[`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce) 的数组。 +[`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1) 的数组。 @@ -5539,12 +5567,6 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` - - - - - - @@ -5577,6 +5599,12 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` + + + + + + @@ -5613,7 +5641,7 @@ SHA-256: `5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78` SHA-256: `4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b` -来源:[`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:21`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:33`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/agent-team/src/types.ts:9`](../packages/experimental/agent-team/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) +来源:[`packages/api/session-controller/src/types.ts:388`](../packages/api/session-controller/src/types.ts) · [`packages/attachment/attachment/src/brand.ts:6`](../packages/attachment/attachment/src/brand.ts) · [`packages/compaction/compaction/src/brand.ts:4`](../packages/compaction/compaction/src/brand.ts) · [`packages/core/session/src/types.ts:21`](../packages/core/session/src/types.ts) · [`packages/experimental/webhook/src/brand.ts:12`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:6`](../packages/experimental/webhook/src/brand.ts) · [`packages/experimental/webhook/src/brand.ts:9`](../packages/experimental/webhook/src/brand.ts) · [`packages/feedback/message-feedback/src/types.ts:14`](../packages/feedback/message-feedback/src/types.ts) · [`packages/goal/goal/src/types.ts:17`](../packages/goal/goal/src/types.ts) · [`packages/interaction/commands/src/brand.ts:31`](../packages/interaction/commands/src/brand.ts) · [`packages/interaction/user-approval/src/types.ts:17`](../packages/interaction/user-approval/src/types.ts) · [`packages/jobs/jobs/src/brand.ts:19`](../packages/jobs/jobs/src/brand.ts) · [`packages/llm/llm-retry/src/brand.ts:4`](../packages/llm/llm-retry/src/brand.ts) · [`packages/llm/llm/src/brand.ts:16`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:31`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:43`](../packages/llm/llm/src/brand.ts) · [`packages/llm/llm/src/brand.ts:67`](../packages/llm/llm/src/brand.ts) · [`packages/schedule/schedule/src/types.ts:14`](../packages/schedule/schedule/src/types.ts) · [`packages/session/session-title/src/index.ts:42`](../packages/session/session-title/src/index.ts) · [`packages/session/session-title/src/types.ts:17`](../packages/session/session-title/src/types.ts) · [`packages/team/agent-team/src/types.ts:20`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:32`](../packages/team/agent-team/src/types.ts) · [`packages/team/agent-team/src/types.ts:8`](../packages/team/agent-team/src/types.ts) · [`packages/workflow/workflow/src/types.ts:13`](../packages/workflow/workflow/src/types.ts) `string` @@ -5757,6 +5785,20 @@ SHA-256: `fd0d91a1f9dd2efb8959bdf5e07f8f0a98b1cdfa38ce8d4732ebde0b44c3abd4` - `"in_progress"` - `"pending"` + + +### `union (5 variants)` + +SHA-256: `866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0` + +以下类型之一: + +- `"aborted"` +- `"completed"` +- `"error"` +- `"max-tokens"` +- `"refusal"` + ### `union (6 variants)` @@ -5822,7 +5864,7 @@ SHA-256: `20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5` SHA-256: `6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406` -来源:[`packages/preset/agent-preset-registry/src/session.ts:31`](../packages/preset/agent-preset-registry/src/session.ts) +来源:[`packages/preset/agent-preset-registry/src/session.ts:30`](../packages/preset/agent-preset-registry/src/session.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -6236,6 +6278,18 @@ SHA-256: `0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623` | `subjectId` | 必需 | `string` | | `tenantId` | 必需 | `string` | + + +### `{ enabled }` + +SHA-256: `c2a13242efc3bea4b36a843ddf1524ff4d33c765a71b582fa1fdbfa4fa148434` + +来源:[`packages/team/agent-team/src/types.ts:171`](../packages/team/agent-team/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `enabled` | 必需 | `boolean` | + ### `{ end, start }` @@ -6332,18 +6386,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `53d4f8256bc58109468ea358ac54d437760cd765012360cafe72a401e6a41d4a` +SHA-256: `65377a76c6a58f785d95b89f89f2e13d289cb88a70ea74939d0ec08f429f0a6e` 来源:[`packages/core/session/src/types.ts:317`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6427,17 +6481,17 @@ SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `d4d960185026266ed7bd127be1e252234689e8b4890c7c2677a644ba58f35401` +SHA-256: `e1880c67e735e228f3555df8a55a492db2c0b0c71bc8859e938e184a46c7db51` 来源:[`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-7c203f3d4dfa6638ff2601247cc7ca5d46731d2c614aa61217475b9eb1fbd0b3) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-690583582246babf6120f16eefd849dd760c5ec84619014951af403a1b3032c0) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -7860,7 +7914,7 @@ SHA-256: `9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee` SHA-256: `b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1` -来源:[`packages/experimental/agent-team/src/types.ts:230`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:173`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7888,7 +7942,7 @@ SHA-256: `6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5` SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` -来源:[`packages/experimental/agent-team/src/types.ts:234`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:177`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7902,7 +7956,7 @@ SHA-256: `ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403` SHA-256: `0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1` -来源:[`packages/experimental/agent-team/src/types.ts:236`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:179`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8048,7 +8102,7 @@ SHA-256: `477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028` SHA-256: `a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c` -来源:[`packages/experimental/agent-team/src/types.ts:232`](../packages/experimental/agent-team/src/types.ts) +来源:[`packages/team/agent-team/src/types.ts:175`](../packages/team/agent-team/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -8096,17 +8150,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e` +SHA-256: `ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-d4d960185026266ed7bd127be1e252234689e8b4890c7c2677a644ba58f35401) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-e1880c67e735e228f3555df8a55a492db2c0b0c71bc8859e938e184a46c7db51) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8347,17 +8401,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f` +SHA-256: `70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-53d4f8256bc58109468ea358ac54d437760cd765012360cafe72a401e6a41d4a) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-65377a76c6a58f785d95b89f89f2e13d289cb88a70ea74939d0ec08f429f0a6e) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8757,17 +8811,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c` +SHA-256: `d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-601327bedca5f98a0fa4c27133bd35749f3af2baaaacf53badf074e59cea5d25) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8919,6 +8973,22 @@ SHA-256: `21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d` | `time` | 必需 | `number` | | `type` | 必需 | `"team/message/queued"` | + + + + +### `{ type: "team/mode" }` + +SHA-256: `920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75` + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `data` | 必需 | [`{ enabled }`](#persistence-type-sha256-c2a13242efc3bea4b36a843ddf1524ff4d33c765a71b582fa1fdbfa4fa148434) | +| `ignorable` | 可选 | `true` | +| `seq` | 必需 | `number` | +| `time` | 必需 | `number` | +| `type` | 必需 | `"team/mode"` | + @@ -9190,17 +9260,17 @@ SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451` +SHA-256: `dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-changes/2026-10-19-session-team-mode.i18n.yaml b/docs/persistence-changes/2026-10-19-session-team-mode.i18n.yaml new file mode 100644 index 0000000000..d69a435040 --- /dev/null +++ b/docs/persistence-changes/2026-10-19-session-team-mode.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-19-session-team-mode.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-10-19-session-team-mode.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-10-19-session-team-mode: + en: a882cc1bc383bf80 + zh: 33f40913b70ad97b +/2026-10-19-session-team-mode/summary: + en: 665465829d68c487 + zh: 2d5bd37335c79aad +/2026-10-19-session-team-mode/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-10-19-session-team-mode/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-10-19-session-team-mode/compatibility: + en: c0ca565e19ad32a7 + zh: 548c334b7e15b464 +/2026-10-19-session-team-mode/verification: + en: 7f3a3e4b1ffb9f85 + zh: dd9258af01f40937 +/2026-10-19-session-team-mode/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-19-session-team-mode.md b/docs/persistence-changes/2026-10-19-session-team-mode.md new file mode 100644 index 0000000000..ca350836a8 --- /dev/null +++ b/docs/persistence-changes/2026-10-19-session-team-mode.md @@ -0,0 +1,48 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-10-19-session-team-mode + +English | [中文](2026-10-19-session-team-mode.zh.md) + +## Summary + +Records the root Session’s Agent Teams selection with the required team/mode event. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-19-session-team-mode +baseline: false +changes: + - root: "event:team/mode" + previous: null + after: "920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75" + decision: same-version +``` + + +## Compatibility + +Existing V4 logs remain readable. Without a selection, historical tasks enable Team; without historical tasks it remains disabled. Readers predating team/mode refuse the unknown required discriminator, so they cannot silently restore the wrong mode. Ordinary forks ignore inherited mode selections and start disabled. No existing payload or Session header version changes. + + +## Verification + +197 focused Team, tool, model-menu and client tests passed; the Web mode and task-board scenario passed 8 tests. The authored team-session-mode headless and TypeScript SDK snapshots exercise on/off commands; Python SDK raw-event projection retains both selections. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-10-19-session-team-mode.schema.json b/docs/persistence-changes/2026-10-19-session-team-mode.schema.json new file mode 100644 index 0000000000..4e854f51d3 --- /dev/null +++ b/docs/persistence-changes/2026-10-19-session-team-mode.schema.json @@ -0,0 +1,15 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:team/mode","kind":"event","event":"team/mode","surface":false,"digest":"920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75"} + ], + "types": [], + "nodes": { + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "920d87e22b7409bc": {"kind":"object","properties":[{"name":"data","type":"c2a13242efc3bea4","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d8a476d2c6fd30df","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "c2a13242efc3bea4": {"kind":"object","properties":[{"name":"enabled","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "d8a476d2c6fd30df": {"kind":"literal","value":"team/mode"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true} + } +} diff --git a/docs/persistence-changes/2026-10-19-session-team-mode.zh.md b/docs/persistence-changes/2026-10-19-session-team-mode.zh.md new file mode 100644 index 0000000000..6ea99093a6 --- /dev/null +++ b/docs/persistence-changes/2026-10-19-session-team-mode.zh.md @@ -0,0 +1,48 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-10-19-session-team-mode + +[English](2026-10-19-session-team-mode.md) | 中文 + +## 概述 + +通过必读的 team/mode 事件记录根 Session 的智能体团队选择。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-19-session-team-mode +baseline: false +changes: + - root: "event:team/mode" + previous: null + after: "920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75" + decision: same-version +``` + + +## 兼容性 + +已有 V4 日志仍可读取。没有显式选择时,历史任务使 Team 开启;没有历史任务时保持关闭。旧读取器拒绝未知的必读 team/mode 判别值,避免静默恢复错误模式。普通分叉忽略继承的模式选择,初始保持关闭。不修改已有载荷或 Session 头部版本。 + + +## 验证 + +197 个 Team、工具、模型菜单和客户端定向测试通过;Web 开关与任务板场景的 8 个测试通过。team-session-mode 的 headless 和 TypeScript SDK 人工编写快照覆盖开关命令;Python SDK 原始事件投影保留两次选择。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.i18n.yaml b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.i18n.yaml new file mode 100644 index 0000000000..e1d1916155 --- /dev/null +++ b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-10-27-subagent-settlement-attribution.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/persistence-changes/2026-10-27-subagent-settlement-attribution.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-10-27-subagent-settlement-attribution: + en: d2a2da526a11227c + zh: 047e8cc6da20118f +/2026-10-27-subagent-settlement-attribution/summary: + en: fb422315a6c3e9e7 + zh: bce866c511613c73 +/2026-10-27-subagent-settlement-attribution/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-10-27-subagent-settlement-attribution/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-10-27-subagent-settlement-attribution/compatibility: + en: e18e26f07dcc315e + zh: 7120bc3f3e9b90b5 +/2026-10-27-subagent-settlement-attribution/verification: + en: 42d56d2378276e50 + zh: 16c96c5c3d018964 +/2026-10-27-subagent-settlement-attribution/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.md b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.md new file mode 100644 index 0000000000..0f5994a749 --- /dev/null +++ b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-10-27-subagent-settlement-attribution + +English | [中文](2026-10-27-subagent-settlement-attribution.zh.md) + +## Summary + +Adds optional stopReason attribution to persisted subagent settlement notices while keeping the Session format version unchanged. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-27-subagent-settlement-attribution +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca" + decision: same-version + - root: "event:user/message" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450" + decision: same-version +``` + + +## Compatibility + +New readers accept historical notices without stopReason and must not infer it from the English summary. Writers always record the exact captured execution stopReason. Older readers preserve additional source metadata and continue using the existing kind, notice form, summary, senderSessionId, and unchanged content; native V4 source admission validates the producer kind rather than rejecting additional attribution fields. The new metadata affects presentation only, not replay, authority, or recovery. No migration or Session version bump is required. + + +## Verification + +Focused Vitest runs passed: continuation-messages.spec.ts (14 tests), external-activation.spec.ts (19 tests), continuation-messages-adapter.spec.ts (1 test), and continuation.spec.ts (166 tests), all under packages/subagent/subagent/tests. Command: node node_modules/vitest/vitest.mjs run followed by the listed owner paths. Coverage includes all five terminal reasons, historical attribution without inference, external cleanup failure retaining the captured execution reason, cold resume, and unchanged DeepSeek Messages wire content. Historical Session generations remain unchanged; affected current-format snapshot expectations include stopReason. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.schema.json b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.schema.json new file mode 100644 index 0000000000..3299e5d126 --- /dev/null +++ b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.schema.json @@ -0,0 +1,259 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450"} + ], + "types": [], + "nodes": { + "01c161379a3c3394": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"b120362fd216a16a","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "02b2c23f2d94b028": {"kind":"object","properties":[{"name":"kind","type":"c5687b1313206a6f","optional":false}],"indices":[]}, + "05205074b24d8340": {"kind":"literal","value":"action-cards"}, + "0657d3ca5ac4e7bf": {"kind":"primitive","type":"number"}, + "07e1a58c58b593f5": {"kind":"object","properties":[{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "09655b34d7f3cf1e": {"kind":"literal","value":"system-prompt"}, + "09f3f8dc417f2782": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"8af841fc9b265ade","optional":false},{"name":"source","type":"65a8400e451e667e","optional":false}],"indices":[]}, + "0a92c5bdfa06c2e2": {"kind":"object","properties":[{"name":"displayName","type":"4cd48f3e5108bd6e","optional":true},{"name":"providerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subjectId","type":"4cd48f3e5108bd6e","optional":false},{"name":"tenantId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "0ed8d1108fe7a5e1": {"kind":"object","properties":[{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "0eeb17e1df89b1eb": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "0f46153645c29784": {"kind":"object","properties":[{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "0fe52387f6505270": {"kind":"literal","value":"plan-mode"}, + "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "12d5808fac1996b9": {"kind":"object","properties":[{"name":"attachment","type":"b0b0eb1b16490f6b","optional":false},{"name":"offloaded","type":"dacf3d5f3e4ff619","optional":true},{"name":"type","type":"fb8b6a2e53cb9cf4","optional":false}],"indices":[]}, + "1379f0b72275994d": {"kind":"literal","value":"developer/message"}, + "16d0507cb94b4cfc": {"kind":"literal","value":"relay"}, + "1922cd79a70806c1": {"kind":"literal","value":"skill-invocation"}, + "1938c8c20f1cba7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1e0b0b66b6f0c53f": {"kind":"literal","value":"aborted"}, + "1e709346005826eb": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "1ebc6f9ff3aa9e3a": {"kind":"literal","value":"completed"}, + "1f0133217eeeffd8": {"kind":"literal","value":"tool-call"}, + "1f1385dbc3e875c0": {"kind":"literal","value":"repeat-tool-reminder"}, + "1fdad624334d3548": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "2152caf1a71e588e": {"kind":"object","properties":[{"name":"kind","type":"2e4debca12f2c449","optional":false},{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "2235d957bf4b7c6c": {"kind":"object","properties":[{"name":"kind","type":"7b1ce60193fa8b69","optional":false}],"indices":[]}, + "224aa11d4d5f88c4": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "23af3759678a30de": {"kind":"literal","value":"dsh-session-title-llm"}, + "24b10f7cdae64928": {"kind":"literal","value":"runtime-context"}, + "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "2765e9119edf5816": {"kind":"literal","value":"model"}, + "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "28936c614bd4e7e2": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "290f32bfd81ff85a": {"kind":"object","properties":[{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "297fbd8067d7815a": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "2aad1179f9576314": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "2ab12a0e345658f9": {"kind":"array","element":"83da72c6857601c7"}, + "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, + "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, + "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, + "312aee2f0c42aabb": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "31907de956375182": {"kind":"object","properties":[{"name":"compactionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"6b23ed9ce1b397e6","optional":false},{"name":"sourceCommandId","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, + "3247e566f4340029": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "335e242de1fcc17b": {"kind":"union","types":["bcf0caf62d964b2f","e438a9d4fb883b3e"]}, + "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, + "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3bd652ebfa8726b3": {"kind":"union","types":["0657d3ca5ac4e7bf","938f7c7357bc403e"]}, + "3bdb8dc6989655b0": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "3c2535ca0a2062f1": {"kind":"literal","value":"reasoning"}, + "3e2ece4967cfebe9": {"kind":"literal","value":"next-step"}, + "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, + "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "43e311235aa537df": {"kind":"object","properties":[{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"83d6916021eede8f","optional":false}],"indices":[]}, + "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a561c111a78d452": {"kind":"literal","value":"refusal"}, + "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4b259f7f8f0a44ad": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"isError","type":"aa93010d0e521ad7","optional":true},{"name":"role","type":"a13d8f379222ece8","optional":false},{"name":"source","type":"d9c462b9f62fdd3e","optional":false},{"name":"toolCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4cd48f3e5108bd6e": {"kind":"primitive","type":"string"}, + "4d60dddaa65d3da8": {"kind":"object","properties":[{"name":"actor","type":"0a92c5bdfa06c2e2","optional":false},{"name":"kind","type":"6ba7edb6447b6a3e","optional":false},{"name":"shareId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "4e44c9118152f682": {"kind":"literal","value":"text"}, + "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, + "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, + "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, + "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "58015da1c1950a66": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "587bb11da730e06a": {"kind":"literal","value":"session/title-llm-request"}, + "589d0d91239681f8": {"kind":"literal","value":"developer"}, + "58f94390b982f8a5": {"kind":"literal","value":"image/png"}, + "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "5cdbf342b7748d15": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "5d03ba38734809bc": {"kind":"array","element":"0657d3ca5ac4e7bf"}, + "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "601327bedca5f98a": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"95b5cf90ea1f57da","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "613660455704fb82": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"b120362fd216a16a","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "65377a76c6a58f78": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"01c161379a3c3394","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, + "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, + "672c4aa2a9b736e3": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1922cd79a70806c1","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "68141cbe3994a5ff": {"kind":"literal","value":"max-tokens"}, + "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "690583582246babf": {"kind":"array","element":"613660455704fb82"}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ba7edb6447b6a3e": {"kind":"literal","value":"share-viewer"}, + "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "6ea608bdc8a7a63d": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "6ebcc2dbec9f2dab": {"kind":"literal","value":"skill-catalog"}, + "6f22a9d02b9a1f11": {"kind":"object","properties":[{"name":"baseline","type":"dacf3d5f3e4ff619","optional":true},{"name":"baselineIdentity","type":"4cd48f3e5108bd6e","optional":true},{"name":"changes","type":"2ab12a0e345658f9","optional":false},{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"fbd2c74b346a1595","optional":false}],"indices":[]}, + "6f44f32be9bcd9a8": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, + "70ea8e7943c5e2d7": {"kind":"object","properties":[{"name":"data","type":"65377a76c6a58f78","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, + "7382c4fc95fe8c5d": {"kind":"literal","value":"remove"}, + "7554565be416b034": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "756b5e23a5cb2c7f": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "78a9be340090b735": {"kind":"literal","value":"tmux-context"}, + "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, + "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, + "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, + "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, + "814d9434e1ddf907": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"3c2535ca0a2062f1","optional":false}],"indices":[]}, + "82470020b5bfcb1a": {"kind":"literal","value":"agent-message"}, + "824a4aad44a54e24": {"kind":"union","types":["4d60dddaa65d3da8","deebfc7c62177ea8"]}, + "825ca23416b1ea9d": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "829a2fb3be6efd4b": {"kind":"literal","value":"agent/inbox/spliced"}, + "83079c8a3f733ac3": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8338ee303e2bd448": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, + "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "848639f8787f035b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"866f7b2dbdc5b421","optional":true},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "85d6d96ff8842974": {"kind":"literal","value":"answered"}, + "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, + "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, + "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "87b1a33564b9a4d6": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "88841202942c7683": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8a046b52331959aa": {"kind":"object","properties":[{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "8af841fc9b265ade": {"kind":"literal","value":"system"}, + "8c1c4f72755a78ea": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "8c627d7a45fa406c": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8f324cea3916c051": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, + "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "938f7c7357bc403e": {"kind":"primitive","type":"null"}, + "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95b5cf90ea1f57da": {"kind":"array","element":"e272493e3ea0b33b"}, + "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, + "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, + "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "96f4a9c81fc0f940": {"kind":"union","types":["3e2ece4967cfebe9","62ecb62dc0fe1b5e"]}, + "99135d8a39379779": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "99e7e7d7fed55ae6": {"kind":"literal","value":"tool-jobs"}, + "99f0e98184709ad1": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "9ac52f0f84fec2eb": {"kind":"literal","value":"model-selection"}, + "9edc162949abf93b": {"kind":"object","properties":[{"name":"deliveryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"db6c5246911d47a7","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"ruleId","type":"4cd48f3e5108bd6e","optional":false},{"name":"source","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "9f65c43e340bba31": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "a13d8f379222ece8": {"kind":"literal","value":"tool"}, + "a15a19ef63cf5d1b": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "a16e567c8cd2c55c": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "a2066bd52f61218b": {"kind":"object","properties":[{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "a2be0f0cb59f0d4a": {"kind":"literal","value":"error"}, + "a3c6f1ea38e9a61d": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a4afec59b75aad5d": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "a720757f704a2512": {"kind":"literal","value":"tool-registry"}, + "a9059a81430b3207": {"kind":"literal","value":"hooks-claude-code"}, + "aa2bf9e82b9fdeb9": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "aa93010d0e521ad7": {"kind":"primitive","type":"boolean"}, + "aae343bc3d663c83": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "aba175fb20ffc711": {"kind":"array","element":"83079c8a3f733ac3"}, + "ada310bf0bdb8fed": {"kind":"object","properties":[{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "ade057f4fdc387ae": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "aec150797b655c5f": {"kind":"literal","value":"catalog"}, + "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b120362fd216a16a": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "b2a5c8c008a31e3d": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, + "b3681c026a0b98e9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "b4ec0af39fd52ed9": {"kind":"object","properties":[{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b52f215a6cd69105": {"kind":"array","element":"8064c03c87c357fd"}, + "b613f83572fe2fbf": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b6f94c17dd9bbd7c": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "b70f3e81fe11b7a5": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false}],"indices":[]}, + "b765ee31033cea46": {"kind":"literal","value":"set"}, + "b79641a9d25e7566": {"kind":"object","properties":[{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, + "ba2a1a8f194b1bb2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "ba4c40b4381e0dcd": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "baccc97ec34be6c4": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "bb94f3217aa56c88": {"kind":"literal","value":"hooks-codex"}, + "bbc5696e3f13c758": {"kind":"opaque","reason":"unknown"}, + "bcf0caf62d964b2f": {"kind":"object","properties":[{"name":"endSeq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"op","type":"f6cb462f808309e3","optional":false},{"name":"startSeq","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "bf16d2e98a7f1389": {"kind":"literal","value":"subagent-settled"}, + "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, + "c5228b7a55498d84": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "c55827fba7018198": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"9645cf93769a6dfb","optional":false},{"name":"outcome","type":"85d6d96ff8842974","optional":false}],"indices":[]}, + "c5687b1313206a6f": {"kind":"literal","value":"cordis-host-runner"}, + "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, + "cb1c8959e1726f82": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d95c624eddecdacf": {"kind":"object","properties":[{"name":"data","type":"601327bedca5f98a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, + "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, + "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, + "dacf3d5f3e4ff619": {"kind":"literal","value":true}, + "db06ef35b27a3842": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "db6c5246911d47a7": {"kind":"literal","value":"webhook"}, + "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, + "dcb07e04496586d2": {"kind":"object","properties":[{"name":"data","type":"613660455704fb82","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, + "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "ddce54a3873dc571": {"kind":"object","properties":[{"name":"data","type":"e1880c67e735e228","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, + "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "de25352d2dc41963": {"kind":"literal","value":"user/message"}, + "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, + "deaae5cd30987d4f": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "deebfc7c62177ea8": {"kind":"object","properties":[{"name":"kind","type":"95a3ffccbf3c8afc","optional":false}],"indices":[]}, + "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, + "e1880c67e735e228": {"kind":"object","properties":[{"name":"inserted","type":"690583582246babf","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "e272493e3ea0b33b": {"kind":"union","types":["01c161379a3c3394","09f3f8dc417f2782","4b259f7f8f0a44ad","613660455704fb82","fa87537f4a9c1e25"]}, + "e438a9d4fb883b3e": {"kind":"literal","value":"append"}, + "e7f4cbb3a57f4cbd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "e8de0f457fed5b9f": {"kind":"literal","value":"notice"}, + "ebb768d85ec87fb6": {"kind":"literal","value":"image/webp"}, + "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f19bee84bf3d2090": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "f230c0b583e23b25": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "f29d63336e8266d8": {"kind":"object","properties":[{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, + "f2da0f27c1e6add5": {"kind":"object","properties":[{"name":"attachment","type":"f19bee84bf3d2090","optional":false},{"name":"type","type":"277b61f9c6f81704","optional":false}],"indices":[]}, + "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f56c5b59ca016131": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"7f13860ee89a2d35","optional":false},{"name":"references","type":"df843efd87c78cf8","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, + "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, + "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f68c335306535a00": {"kind":"literal","value":"user-approval"}, + "f6afe41e3926f422": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "f6cb462f808309e3": {"kind":"literal","value":"replace"}, + "f7283223aacdc39b": {"kind":"object","properties":[{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, + "f88f1b7b6bb733f6": {"kind":"literal","value":1}, + "f97f47b0eb87905e": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fa87537f4a9c1e25": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"95c0e88fcf0bafb2","optional":false},{"name":"source","type":"719c51f67074f970","optional":false}],"indices":[]}, + "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, + "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, + "fcf427290c6213c2": {"kind":"primitive","type":"never"}, + "fcf81d3c58c13593": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, + "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} + } +} diff --git a/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.zh.md b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.zh.md new file mode 100644 index 0000000000..4ea60a4c94 --- /dev/null +++ b/docs/persistence-changes/2026-10-27-subagent-settlement-attribution.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-10-27-subagent-settlement-attribution + +[English](2026-10-27-subagent-settlement-attribution.md) | 中文 + +## 概述 + +为持久化的子代理结算通知增加可选 stopReason 归属信息,保持 Session 格式版本不变。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-10-27-subagent-settlement-attribution +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482" + decision: same-version + - root: "event:developer/message" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca" + decision: same-version + - root: "event:user/message" + previous: "2026-10-13-liveshare-share-viewer-principal" + after: "dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450" + decision: same-version +``` + + +## 兼容性 + +新读取方接受缺少 stopReason 的历史通知,不得从英文摘要推断该字段。写入方始终记录已捕获执行的确切 stopReason。旧读取方保留额外的 source 元数据,继续使用已有 kind、notice form、summary、senderSessionId 和未改变的内容;原生 V4 source 准入校验生产方 kind,不拒绝额外归属字段。新元数据只影响展示,不影响回放、权限或恢复。无需迁移或提升 Session 版本。 + + +## 验证 + +定向 Vitest 运行通过:continuation-messages.spec.ts(14 个测试)、external-activation.spec.ts(19 个测试)、continuation-messages-adapter.spec.ts(1 个测试)和 continuation.spec.ts(166 个测试),均位于 packages/subagent/subagent/tests。命令为 node node_modules/vitest/vitest.mjs run,后接上述测试文件路径。覆盖全部五种终止原因、历史归属信息不作推断、外部清理失败保留已捕获的执行原因、冷恢复,以及不变的 DeepSeek Messages 线协议内容。历史 Session 代际保持不变;受影响的当前格式快照预期包含 stopReason。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index e9e8287e17..fcd95ef300 100644 --- a/docs/persistence-changes/historical-formats/README.i18n.yaml +++ b/docs/persistence-changes/historical-formats/README.i18n.yaml @@ -15,8 +15,8 @@ en: 14c57f30e676f6e3 zh: b1a0ccf26fab3727 /session-persistence-formats/format-references: - en: 5912b107ada0bfc4 - zh: b997083d6fed3f07 + en: a660985fd2941e51 + zh: 0d4aed6be93be922 /session-persistence-formats/scope-and-evidence: en: b220062139ddac1e zh: 7c4c0efe05dafa9c diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index e0a594594d..24b42751fa 100644 --- a/docs/persistence-changes/historical-formats/README.md +++ b/docs/persistence-changes/historical-formats/README.md @@ -32,7 +32,7 @@ The index is generated from validated snapshots and the current writer constant. | 1 | PR #3349 | [V1](v1.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 65 / 626 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 66 / 631 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index 4202dfcc4e..ef48b880a4 100644 --- a/docs/persistence-changes/historical-formats/README.zh.md +++ b/docs/persistence-changes/historical-formats/README.zh.md @@ -32,7 +32,7 @@ description: "查找从 V0 到工作区写入器版本的每个 Session 格式 | 1 | PR #3349 | [V1](v1.zh.md) | [JSON](v1.schema.json) | 54 / 415 | | 2 | `dsh-v0.1.3-alpha.2` | [V2](v2.zh.md) | [JSON](v2.schema.json) | 56 / 435 | | 3 | PR #4320 | [V3](v3.zh.md) | [JSON](v3.schema.json) | 60 / 467 | -| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 65 / 626 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 66 / 631 | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index aa46bc962e..3a30b6f025 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -5,7 +5,7 @@ {"key":"JsonlHeaderLine","kind":"header","digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f"}, {"key":"SessionEventEnvelope","kind":"envelope","digest":"5776e5553ff2dfe3f5bc202dbb1e7c9f93e35a531aebb7764c23b2b6153b2ccc"}, {"key":"event:agent-preset/selected","kind":"event","event":"agent-preset/selected","surface":false,"digest":"a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b"}, - {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e"}, + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482"}, {"key":"event:approval/asked","kind":"event","event":"approval/asked","surface":false,"digest":"3bfeb47b58606f4661904bc723da612782214c463d01e6d61cd6d6193d7374e1"}, {"key":"event:approval/decided","kind":"event","event":"approval/decided","surface":false,"digest":"bb1ab3d08f49a9f3b265f844cd78d5c49813062a7b34b54904b426f85d0ff6e3"}, {"key":"event:approval/policy","kind":"event","event":"approval/policy","surface":false,"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78"}, @@ -18,7 +18,7 @@ {"key":"event:compaction/start","kind":"event","event":"compaction/start","surface":false,"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965"}, {"key":"event:compaction/summary","kind":"event","event":"compaction/summary","surface":false,"digest":"e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602"}, {"key":"event:deliverables/presented","kind":"event","event":"deliverables/presented","surface":false,"digest":"13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176"}, - {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a"}, {"key":"event:feedback/message-delete","kind":"event","event":"feedback/message-delete","surface":false,"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796"}, {"key":"event:feedback/message-put","kind":"event","event":"feedback/message-put","surface":false,"digest":"b5086d249e8502e9ead1d39156bb8d559bde7951cac0f14ce150345b4e42a2bf"}, {"key":"event:feedback/record","kind":"event","event":"feedback/record","surface":false,"digest":"b54940ff095c17e874c5be03815f4c2145a256cf3a1d34dae4ab2f7769dfffe8"}, @@ -40,7 +40,7 @@ {"key":"event:session-log-deepseek/delivery-accepted","kind":"event","event":"session-log-deepseek/delivery-accepted","surface":false,"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9"}, {"key":"event:session/end-seed","kind":"event","event":"session/end-seed","surface":false,"digest":"5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e"}, {"key":"event:session/title","kind":"event","event":"session/title","surface":false,"digest":"1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5"}, - {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca"}, {"key":"event:step/end","kind":"event","event":"step/end","surface":false,"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05"}, {"key":"event:step/start","kind":"event","event":"step/start","surface":false,"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986"}, {"key":"event:subagent/catalog","kind":"event","event":"subagent/catalog","surface":false,"digest":"53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac"}, @@ -50,6 +50,7 @@ {"key":"event:team/member","kind":"event","event":"team/member","surface":false,"digest":"4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc"}, {"key":"event:team/message/delivered","kind":"event","event":"team/message/delivered","surface":false,"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb"}, {"key":"event:team/message/queued","kind":"event","event":"team/message/queued","surface":false,"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d"}, + {"key":"event:team/mode","kind":"event","event":"team/mode","surface":false,"digest":"920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75"}, {"key":"event:team/task","kind":"event","event":"team/task","surface":false,"digest":"d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a"}, {"key":"event:todo/write","kind":"event","event":"todo/write","surface":false,"digest":"b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26"}, {"key":"event:tool-workflow/agent-end","kind":"event","event":"tool-workflow/agent-end","surface":false,"digest":"babf9ee4d1af62bf6c3a8103737f7a5e4e78ce179be835ce05a38803e15884b7"}, @@ -62,13 +63,14 @@ {"key":"event:tool/result","kind":"event","event":"tool/result","surface":true,"digest":"7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397"}, {"key":"event:turn/end","kind":"event","event":"turn/end","surface":false,"digest":"0f8512903d94f57a4748fa1a2092e64342856796684e6b8343db685b192745ce"}, {"key":"event:turn/start","kind":"event","event":"turn/start","surface":false,"digest":"aa0957eca50aeb28bcd2e6930b95809926edacb550c8c340ba526ba6b861b3d8"}, - {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450"}, {"key":"event:web/deepseek-search-llm-request","kind":"event","event":"web/deepseek-search-llm-request","surface":false,"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52"}, {"key":"event:working-directory/change","kind":"event","event":"working-directory/change","surface":false,"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3"}, {"key":"event:workspace/changes","kind":"event","event":"workspace/changes","surface":false,"digest":"e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72"} ], "types": [ {"digest":"0116b1f89c05221d56b0ba35c83d302bf4857bc7277d247e9bbaf74b27d2c66e","names":[],"sources":[]}, + {"digest":"01c161379a3c3394a642807843e108ef911a8b7dbffd6d7de43f4484c88b0796","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:157"]}, {"digest":"0203243b72fc867afc81aff5f4cf2167e564ed342534eb612fc92f295cf07789","names":[],"sources":[]}, {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:211"]}, @@ -90,7 +92,7 @@ {"digest":"0af3ecfb8c60d416fc40a7cc4fb2c4851a8e46608b2b38ab9e510670c971aa1f","names":[],"sources":[]}, {"digest":"0b6d718c693fdf7f06dcccb0bcbbabe78cc63514eafc62d6b2a3899735279d6f","names":["packages/goal/goal/src/types.ts#GoalRef"],"sources":["packages/goal/goal/src/types.ts:20"]}, {"digest":"0b9b8facbe2c19773b3fb0ecc824ccbcc603d41b8f18069faa3807d449572fce","names":[],"sources":[]}, - {"digest":"0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1","names":[],"sources":["packages/experimental/agent-team/src/types.ts:236"]}, + {"digest":"0bcfaf5566d271028429ac7b562cb59053c9d78b8ae14708c35fac835108d1b1","names":[],"sources":["packages/team/agent-team/src/types.ts:179"]}, {"digest":"0bdaf9cb63594be4ef034b68901fffe792fe09d6d5f6bac42d7f56f6e7834fb9","names":[],"sources":[]}, {"digest":"0c4205180f75b9ee1e0d878bd9a9851628b5dc18448486389d9c5fdc3f1ccda3","names":[],"sources":[]}, {"digest":"0c556c9b9f2a96238a6b9bbb99e748206cbff2ed6203041c9571f04ae5802f52","names":[],"sources":[]}, @@ -122,7 +124,7 @@ {"digest":"16d0507cb94b4cfc84a87446b1ba7652d6ec1d65ee1684789e747e30d542800e","names":[],"sources":[]}, {"digest":"17aae616ef020b8b9f011ec398ec935450fb06d3e2a0722c456f63aeaf5ff728","names":[],"sources":[]}, {"digest":"17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3","names":[],"sources":["packages/core/session/src/types.ts:435"]}, - {"digest":"18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0","names":["packages/schedule/schedule/src/types.ts#ScheduleDeleteChange"],"sources":["packages/schedule/schedule/src/types.ts:230"]}, + {"digest":"18dc21f12bbac8ade8377e6fbb54179e20c3d955d73fba3244c57fb6bf001df0","names":["packages/schedule/schedule/src/types.ts#ScheduleDeleteChange"],"sources":["packages/schedule/schedule/src/types.ts:206"]}, {"digest":"18ee62b8900a4c3d046700f05d7a4d49d6cab2a660a020c87481d1603dd8bd4f","names":["packages/session/session-persistence-jsonl/src/format.ts#HeaderLine"],"sources":["packages/session/session-persistence-jsonl/src/format.ts:83"]}, {"digest":"18fcdd273a2f2f9d813a3be5e71df5903a963a5c88e46b90b14de6e2db890da0","names":[],"sources":[]}, {"digest":"18fce9540bb20897a66275499faee6b8296c97e9901fa1ff45a191772448ad1a","names":[],"sources":[]}, @@ -153,7 +155,7 @@ {"digest":"1fdad624334d354820dfb3a26e28d0bc9fc1b62a33f87bab63f715b3f4391bfd","names":[],"sources":[]}, {"digest":"20a57544bbf204dacd1ae6beb2ab29444365c3c869f2afdf489dcdcbc3d9c8c5","names":[],"sources":["packages/plan/plan-mode/src/index.ts:53"]}, {"digest":"2142e391b9ccb60d487afcf373ce74db98d952f69e8289eddb352a7e16e996c5","names":[],"sources":[]}, - {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/experimental/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/experimental/agent-team/src/types.ts:138"]}, + {"digest":"2152caf1a71e588e4df2358a806dea24936c1c47131134f01a12939d12cdc0c0","names":["packages/team/agent-team/src/types.ts#TeamMessageSource"],"sources":["packages/team/agent-team/src/types.ts:117"]}, {"digest":"21fb6a90d5068f6a0003b7ab316ed2f56342477146a65c00db0f13c4d8df667d","names":[],"sources":[]}, {"digest":"2235d957bf4b7c6cf959231d480f0ba1f3a6d72d82981493fb6c7c963021d3d5","names":[],"sources":["packages/session/working-directory/src/index.ts:29"]}, {"digest":"224aa11d4d5f88c450822d01b99e6ca5e3a9c7f26a5ede10bae33384a09ef4dc","names":[],"sources":[]}, @@ -181,10 +183,9 @@ {"digest":"2c64d4bc7264fd3f8bed47e96ab8a593bce05a1e4e1c436dcd244a3b7e0c2a9d","names":[],"sources":[]}, {"digest":"2d11ca7b0d4493e244b74eba093227866b33249841e59a1e9bf56afed38604c3","names":[],"sources":["packages/web/web-search-deepseek/src/provider.ts:71"]}, {"digest":"2da725e554cd89301d829ed9dc45a572c3cd1b93b5e91d0d71f007976d8a0863","names":[],"sources":[]}, - {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:256"]}, + {"digest":"2e3523541e942ef6cc9fbc5b91f242e0ca4c6ada479b79b96025b797f6e41f3f","names":["packages/schedule/schedule/src/types.ts#ScheduleChange"],"sources":["packages/schedule/schedule/src/types.ts:232"]}, {"digest":"2e4debca12f2c449f96dc6574f3fbf2fb346193443114a241d01a236362ec48c","names":[],"sources":[]}, - {"digest":"2e505098f9209e52eebd577f1a6f9d4e773ec4d78987aff28a7c786442b9f54c","names":[],"sources":[]}, - {"digest":"2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e","names":["packages/experimental/agent-team/src/types.ts#TeamMessageSnapshot"],"sources":["packages/experimental/agent-team/src/types.ts:129"]}, + {"digest":"2eafefdc6f79a4922d68a787a09eaf4dd2b2369c3777fba4c05e800b5678ac8e","names":["packages/team/agent-team/src/types.ts#TeamMessageSnapshot"],"sources":["packages/team/agent-team/src/types.ts:108"]}, {"digest":"2f1e6a7ebace43d727ae138ddcd352eb3813960009e5805b8c5ac84300c97716","names":["packages/attachment/attachment/src/types.ts#ImageMediaType"],"sources":["packages/attachment/attachment/src/types.ts:8"]}, {"digest":"2f3f201c8846e19c20bb75c02280e3d4eb3c57509e4715f0c0a4d1d4f91a7a06","names":[],"sources":[]}, {"digest":"2fe5026daf14bd4ff2b7bfb7cf9791c302d9cbba06802178b6dfec00b892698f","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchStartEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:12"]}, @@ -226,7 +227,6 @@ {"digest":"3ee93b06f3a125850337602bcdf155d2538c43a5c944ec55b1b3c365152d6796","names":[],"sources":[]}, {"digest":"3f74ba74acd10644c1ed6947a411d8088bd2cfac74f61bb8540f96d68e31f004","names":[],"sources":[]}, {"digest":"3fdf9582c3b5597df104d32d97dab6c6ee3a93794f3034ec6ada6272404ea27f","names":["packages/schedule/schedule/src/types.ts#LegacyAfterScheduleRecord"],"sources":["packages/schedule/schedule/src/types.ts:161"]}, - {"digest":"4035903993dfee62cca2142c0ca51ab57075909ddee2817d0620daa97ac4d4ce","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:162"]}, {"digest":"408927267422a7b2beb6df354ff7c1406d929a5646554f48adf85eb8372f811c","names":[],"sources":[]}, {"digest":"4208123b50df5006b181481ab45fcf1cde807b88d3fd4d340090bc2e202fac41","names":[],"sources":[]}, {"digest":"42e0916e0dda5f6d1e7bb05d8514717147c036a79c9f36085683469516c1fd3f","names":[],"sources":[]}, @@ -245,6 +245,7 @@ {"digest":"48f9c19417a1abbedfa59f4667bba36b93ac2db407adf5e84cb3ba0de30942cb","names":[],"sources":[]}, {"digest":"4991dfc415c9efebc36fa6969e1798c7d2e42396cc1e6e0ac7d7c89c5c5c4aea","names":[],"sources":[]}, {"digest":"49dab019d00e8c26f27ad2ccff7b604d69e323ae4d17e0d2a7b6b8a830b1ade2","names":[],"sources":[]}, + {"digest":"4a561c111a78d4520e850c93795369ea169ff86abd082aee86c8fd38121a65aa","names":[],"sources":[]}, {"digest":"4a9bef9f27a942520cc2279ca7dd3082556e4bff543f66b5c0333e1bbed1cd86","names":["packages/subagent/subagent/src/continuation-messages.ts#AgentMessageSource"],"sources":["packages/subagent/subagent/src/continuation-messages.ts:14"]}, {"digest":"4ae007ed190a72c92138b22d059b83208079c7551ca13fb59ae8cf5e23693964","names":[],"sources":[]}, {"digest":"4aed17ec726b5397c29f6cb4bcd7905dc1a12bb6140f1657f073cd24380f2af8","names":[],"sources":[]}, @@ -252,12 +253,11 @@ {"digest":"4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731","names":["packages/llm/llm/src/message.ts#ToolResultMessage"],"sources":["packages/llm/llm/src/message.ts:173"]}, {"digest":"4b7ddaf3710b88ff9b8df66304f5f97bf03688fd19730eedc2e9535203c820ea","names":[],"sources":[]}, {"digest":"4bb451330ff699f36b45539ceb0eb2606ead72084e2c5bb637c36cc80e2252db","names":[],"sources":["packages/core/session/src/types.ts:198"]}, - {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/agent-team/src/types.ts#TeamId","packages/experimental/agent-team/src/types.ts#TeamMessageId","packages/experimental/agent-team/src/types.ts#TeamTaskId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:388","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/agent-team/src/types.ts:21","packages/experimental/agent-team/src/types.ts:33","packages/experimental/agent-team/src/types.ts:9","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/workflow/workflow/src/types.ts:13"]}, + {"digest":"4cd48f3e5108bd6ebedf7301c3638839b8b2b9db8dbd493974177fbdeb91a01b","names":["packages/api/session-controller/src/types.ts#SessionRequestId","packages/attachment/attachment/src/brand.ts#AttachmentId","packages/compaction/compaction/src/brand.ts#CompactionId","packages/core/session/src/types.ts#SessionId","packages/experimental/webhook/src/brand.ts#WebhookDeliveryId","packages/experimental/webhook/src/brand.ts#WebhookRuleId","packages/experimental/webhook/src/brand.ts#WebhookSourceId","packages/feedback/message-feedback/src/types.ts#MessageFeedbackVersion","packages/goal/goal/src/types.ts#GoalId","packages/interaction/commands/src/brand.ts#CommandId","packages/interaction/user-approval/src/types.ts#ApprovalRequestId","packages/jobs/jobs/src/brand.ts#JobId","packages/llm/llm-retry/src/brand.ts#RetryId","packages/llm/llm/src/brand.ts#MessageId","packages/llm/llm/src/brand.ts#ProviderRequestId","packages/llm/llm/src/brand.ts#ReasoningEffortId","packages/llm/llm/src/brand.ts#ToolCallId","packages/schedule/schedule/src/types.ts#ScheduleId","packages/session/session-title/src/index.ts#SessionTitleProviderId","packages/session/session-title/src/types.ts#SessionTitleProviderId","packages/team/agent-team/src/types.ts#TeamId","packages/team/agent-team/src/types.ts#TeamMessageId","packages/team/agent-team/src/types.ts#TeamTaskId","packages/workflow/workflow/src/types.ts#WorkflowRunId"],"sources":["packages/api/session-controller/src/types.ts:388","packages/attachment/attachment/src/brand.ts:6","packages/compaction/compaction/src/brand.ts:4","packages/core/session/src/types.ts:21","packages/experimental/webhook/src/brand.ts:12","packages/experimental/webhook/src/brand.ts:6","packages/experimental/webhook/src/brand.ts:9","packages/feedback/message-feedback/src/types.ts:14","packages/goal/goal/src/types.ts:17","packages/interaction/commands/src/brand.ts:31","packages/interaction/user-approval/src/types.ts:17","packages/jobs/jobs/src/brand.ts:19","packages/llm/llm-retry/src/brand.ts:4","packages/llm/llm/src/brand.ts:16","packages/llm/llm/src/brand.ts:31","packages/llm/llm/src/brand.ts:43","packages/llm/llm/src/brand.ts:67","packages/schedule/schedule/src/types.ts:14","packages/session/session-title/src/index.ts:42","packages/session/session-title/src/types.ts:17","packages/team/agent-team/src/types.ts:20","packages/team/agent-team/src/types.ts:32","packages/team/agent-team/src/types.ts:8","packages/workflow/workflow/src/types.ts:13"]}, {"digest":"4d60dddaa65d3da8d4cd014d85ce3d2c2875664dd0433e331d8e9d395289686b","names":["packages/experimental/liveshare/src/host/viewer-principal.ts#ShareViewerPrincipal"],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:24"]}, {"digest":"4e011753f8263f436efaabfbb3b4db53a98fc55342c5ded2daf7208b217be159","names":[],"sources":[]}, {"digest":"4e44c9118152f6829634bfd508e47669ab0497caffa380c94b4be91f9390d35d","names":[],"sources":[]}, {"digest":"4e887768586528565381dadbddee6cef555874148089f4579e0b4b1ad096fc9c","names":["packages/llm/llm/src/types.ts#TextBlock"],"sources":["packages/llm/llm/src/types.ts:69","packages/web/web-search-deepseek/src/provider.ts:66"]}, - {"digest":"4e97c3d85c0fc817ee58873c38c25a2474abaaa0af4839311b50b68db3b8cf1a","names":["packages/subagent/subagent/src/continuation-messages.ts#SubagentSettledMessageSource"],"sources":["packages/subagent/subagent/src/continuation-messages.ts:29"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, @@ -265,7 +265,7 @@ {"digest":"50cf02d875f8a1f1411f4a6fbcffab9120ccef5f74a47331fbf29480e5f68f48","names":[],"sources":[]}, {"digest":"511801b0a6470d98566e8385d3dffddb2b67f79fcf73ed6056f46c3cc0a245a7","names":[],"sources":[]}, {"digest":"516da4cdd6d2f1e5ce488e648578ca51f40e458f707b803e5b24de870e799415","names":[],"sources":[]}, - {"digest":"51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357","names":["packages/experimental/agent-team/src/types.ts#TeamTaskSnapshot"],"sources":["packages/experimental/agent-team/src/types.ts:75"]}, + {"digest":"51edec100659da3a9bd9c3f6ba1180f5e64ec9a1585e5057080df45c180bd357","names":["packages/team/agent-team/src/types.ts#TeamTaskSnapshot"],"sources":["packages/team/agent-team/src/types.ts:64"]}, {"digest":"525254db03b1d1e6b74cf55aced52817568331ac1f96c0818728910b6692e336","names":[],"sources":[]}, {"digest":"529e0ccd0e34079ab4ff21ed87f810cee0388246263bf22e8aba5986b56fae05","names":[],"sources":["packages/util/values/src/index.ts:4"]}, {"digest":"52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734","names":[],"sources":[]}, @@ -273,7 +273,6 @@ {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:279"]}, {"digest":"53750b9abf61efb7992b0aadc3e247ec927449c63266df28230fd1139f5590ac","names":[],"sources":[]}, {"digest":"53cf1704ae0709c7678bcf070c83c619fc48ca1b5c173b74cfa8702f22a8e492","names":[],"sources":[]}, - {"digest":"53d4f8256bc58109468ea358ac54d437760cd765012360cafe72a401e6a41d4a","names":[],"sources":["packages/core/session/src/types.ts:317"]}, {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:363"]}, {"digest":"557e148d30b79ee48645850832b30c717d7c3b64641deb5d6133b8b4e91ee0b8","names":[],"sources":[]}, {"digest":"5654685d7557ec747e74887237065e626a5bdfa426ca43f7fbb0b6fee9b0916c","names":[],"sources":[]}, @@ -290,7 +289,6 @@ {"digest":"5abab3a27fd2736660ecddd94b28d6bbf114986dd894880153bd1be3ccacb563","names":[],"sources":[]}, {"digest":"5b232a9b9bfcc0fc6794dab7865bcf203a65785c5de5aa647a51228bff628413","names":[],"sources":[]}, {"digest":"5b6fb1f226ff56402db08a6aae82af76100b14056271875f69ec526a1ae05d51","names":[],"sources":["packages/interaction/commands/src/types.ts:112"]}, - {"digest":"5bb231bc5afdb532a6898a20604e76bf0c1db438bfcdc17d4847dceaddc02451","names":[],"sources":[]}, {"digest":"5bb69b88517f6214f2af4d1a6d2b771e271ad3ad695cc9c2c272069ae698c9bc","names":[],"sources":[]}, {"digest":"5bc66269cfaf614c0ecda8ecb469f23101a7609793fc2b693ac23c4aecdb575e","names":[],"sources":[]}, {"digest":"5bd310104cfe448e530beb11422d2f791e2e32e8e95fdc528a15f9ca693dae75","names":[],"sources":[]}, @@ -307,16 +305,18 @@ {"digest":"5f2117d1856a5ab43c28371faa978ebfaa48f8c7d734ea3fc94842210df83dca","names":["packages/llm/llm/src/types.ts#LlmFailure"],"sources":["packages/llm/llm/src/types.ts:48"]}, {"digest":"5f26a6c20b37632f8f57729d171c671def4683d994ac6257a8dffcd855101627","names":[],"sources":[]}, {"digest":"5f758f3de5f00c18968a7c6d347083aac5c9ae13f6a79c78f6611b23c4973564","names":["packages/subagent/subagent/src/descriptor.ts#OneShotSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:61"]}, + {"digest":"601327bedca5f98a0fa4c27133bd35749f3af2baaaacf53badf074e59cea5d25","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"6085488d223aeffdef51d7ae17655fc26ab22ee13cbed82a50e62e2b6fb5b918","names":[],"sources":[]}, {"digest":"611cae9a3539733aa0c42f66035a7d90f19dcbbdfb5d9e3b628b13705253942d","names":[],"sources":[]}, {"digest":"611d82d2dc50df706cf08a0fc04bc8eaf78083391fe6f10313de943e615dd2da","names":["packages/jobs/jobs/src/types.ts#JobSettledData"],"sources":["packages/jobs/jobs/src/types.ts:40"]}, + {"digest":"613660455704fb82a825b5b766e000aa64b5b4d44b4f10e55cffe968d4ec6ab1","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:162"]}, {"digest":"616f93a5047de668e1c30d57b1786abd76beeb4123599637ec1dc5290320ede5","names":[],"sources":[]}, {"digest":"6292bcbedaa97feaec5b48a03bb8144b581b93309d9d6c905f26da7a6a7a0a4f","names":[],"sources":[]}, {"digest":"62e6a429ff3f390a46ac39fb468692032f42936ca0db19b53454184189401379","names":[],"sources":[]}, {"digest":"62ecb62dc0fe1b5e70217f8a80c39256a40ee3a1917be14e5ca899d20c35f7fd","names":[],"sources":[]}, {"digest":"6487b10ba7542f3c447b1e41a1c6a590b7bfafe0b9b66b49f34028da85bb970f","names":["packages/subagent/subagent/src/descriptor.ts#ContinuableSubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:72"]}, - {"digest":"64ef542b1bfc988382d337f2ea85aab8ad76ea55341cf082163919d315688428","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:157"]}, - {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/experimental/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/experimental/agent-team/src/types.ts:48"]}, + {"digest":"65377a76c6a58f785d95b89f89f2e13d289cb88a70ea74939d0ec08f429f0a6e","names":[],"sources":["packages/core/session/src/types.ts:317"]}, + {"digest":"6598cd6da253948d6b207c6374a45335804c79b576866d6215649c2d1bc85e25","names":["packages/team/agent-team/src/types.ts#TeamMemberSnapshot"],"sources":["packages/team/agent-team/src/types.ts:50"]}, {"digest":"65a8400e451e667e5b6e34df72ceb81fca8c12330330fa72083ad40279b189ad","names":["packages/llm/llm/src/message.ts#SystemPromptMessageSource"],"sources":["packages/llm/llm/src/message.ts:35"]}, {"digest":"65d583e66518c5236015e0846470fb32efcf92375ed306aef14e50a9d2cd2099","names":["packages/skill/tool-skill/src/index.ts#SkillCatalogSource"],"sources":["packages/skill/tool-skill/src/index.ts:35"]}, {"digest":"66ba70f6f068da443f969a0b947a013c3addd776b9b60a0a393759c19825e9a2","names":["packages/llm/llm/src/types.ts#ToolSchema"],"sources":["packages/llm/llm/src/types.ts:517"]}, @@ -325,6 +325,7 @@ {"digest":"68141cbe3994a5ffcd064c07c75996538437fd9dbf77ce8a2927e89ec577fabe","names":[],"sources":[]}, {"digest":"688e853dc149f0d30b31765c12ec7e3be74169bdf1a4c6463a10b945d50cc1b8","names":[],"sources":[]}, {"digest":"68f44f59e91c41395076cb77265981a601680ec8a381bbbeb6ab754ffdc94573","names":[],"sources":[]}, + {"digest":"690583582246babf6120f16eefd849dd760c5ec84619014951af403a1b3032c0","names":[],"sources":[]}, {"digest":"69081694be231d56fd9580ba14645fd5e35373202605d5c5c841a9435b5fa3b1","names":[],"sources":[]}, {"digest":"693f4952fb5565da96c06bace8924b098ac2fbc915fde0ff8019701183abc057","names":[],"sources":["packages/llm/llm/src/types.ts:168"]}, {"digest":"69d238a6e9b08d67f601b1825962963d8d3523cb69ebf6208c697dc5d058c199","names":[],"sources":[]}, @@ -339,7 +340,7 @@ {"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]}, {"digest":"6cda0d6d3b4336d83998fe580628426df81c2afbab5d768b8813b56d569120e8","names":[],"sources":[]}, {"digest":"6cf082d0fb6034dea61636787ff0ddf43b6e59aad71e644435a479bc9b83ad65","names":[],"sources":[]}, - {"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:31"]}, + {"digest":"6e52dd55a1d48954ed5464ec46fe34d9eb65f709baabc9561e7a279910b0c406","names":[],"sources":["packages/preset/agent-preset-registry/src/session.ts:30"]}, {"digest":"6ea608bdc8a7a63d3d23b84c49721325094db88d136482e43a820945295eee3e","names":[],"sources":[]}, {"digest":"6ebcc2dbec9f2dabca9f668ae6d39e877899b180740570f453409db339221df3","names":[],"sources":[]}, {"digest":"6f091fe32ab24407236090ca9d710bbaf59bb57466e9f3b8f1f6e4862bc863c6","names":[],"sources":[]}, @@ -349,7 +350,7 @@ {"digest":"6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20","names":["packages/llm/llm-retry/src/types.ts#LlmRetryStartedEventData"],"sources":["packages/llm/llm-retry/src/types.ts:43"]}, {"digest":"6f9e00383836275e46c0a9915767f9bb561be5fc30aae490174908a93e99a912","names":[],"sources":[]}, {"digest":"70b082fe78991edf13cf66e1b4d06cd2dcff9cacfd76f8cfb996bfb61939e7b2","names":[],"sources":[]}, - {"digest":"70d2acdec1ebcfea56d02f7233ebb9ec0f7f494447fb952884c22c3afdc01d6f","names":[],"sources":[]}, + {"digest":"70ea8e7943c5e2d76905bcc2e694e8c3d5b138aaae3609f3e261b8d369a6e35a","names":[],"sources":[]}, {"digest":"7180844e1066230c5e891f1b9ccd942423b0fe48aac6ded7eef2a285b288a732","names":[],"sources":[]}, {"digest":"719c51f67074f97034a6c94297fe1f4b5d3c8d392c57586dab732aa5398c7a91","names":["packages/llm/llm/src/message.ts#ModelMessageSource"],"sources":["packages/llm/llm/src/message.ts:24"]}, {"digest":"71bb3254ec8f1e491ce63b762a7b5f18709de23aa4e8abcc8b886f4b6ce051dd","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:28"]}, @@ -367,20 +368,17 @@ {"digest":"7a651f3b672c52fb615f22c0ce9cb3cc5b22aad92e6bbeefb0808fd7b9233a50","names":[],"sources":[]}, {"digest":"7af85bf70d4eafce63e739adae38ea85501e68df3a0e22f97f3a0be90fd9e4cb","names":[],"sources":[]}, {"digest":"7b1ce60193fa8b69292e5843858d9cee7dc565dcb40d33c136e5d7e8b8d4296a","names":[],"sources":[]}, - {"digest":"7c203f3d4dfa6638ff2601247cc7ca5d46731d2c614aa61217475b9eb1fbd0b3","names":[],"sources":[]}, {"digest":"7c6129b6961cf4b2a030f36c78d2b0a5be38617651a9b81322e054ee512bee06","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackDelete"],"sources":["packages/feedback/message-feedback/src/types.ts:46"]}, {"digest":"7c9f44e90a0058f4cc532ae20dad0c10afa6eba22e70a6c79fc79490bad64397","names":[],"sources":[]}, {"digest":"7d226b9fd95b4ba213d4237c22e930a91c3c769c95ca7f92977b9d625ba13438","names":["packages/goal/goal/src/domain.ts#GoalChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:44"]}, {"digest":"7d54a5a5e629e2e7783bfac72683bcc5e969e9f43426b9289826aaf294ff6344","names":["packages/feedback/command-feedback/src/types.ts#FeedbackRecord"],"sources":["packages/feedback/command-feedback/src/types.ts:27"]}, {"digest":"7d65acf0a3a43a8f445ce5d3320b42eca492739fc931b2a7516bfb8368dc2c68","names":["packages/llm/llm/src/types.ts#ContentBlockType"],"sources":["packages/llm/llm/src/types.ts:155"]}, {"digest":"7df62978a2b7de8540e714152297743e0a622209a46a5ac9513fc0fad73ca23b","names":[],"sources":[]}, - {"digest":"7e9f1072c17f7aa86547c9c8b02766c1006d866a1859a3d677a336e932f70d1a","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:136"]}, {"digest":"7eaef7a763ba5b949b8464bc8add8980a3a5ab566014b69787aeba71e5dfe07b","names":[],"sources":[]}, {"digest":"7f13860ee89a2d35ce09f958e85a04566cd59cb1de1d73a9619a9b631961dc71","names":[],"sources":[]}, {"digest":"7f7fd5a6b0064f597534b29ff62ef26e786dffccf5e14f654a7d4fcea2c35f04","names":[],"sources":[]}, {"digest":"7f9365bae9fcb73e1e34061a1acfe0422c1a5fd351848cace9bebbe806f28462","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:36"]}, {"digest":"7f959241c24128b4983b559984811861dc59774b85905c8fa57c6cb0148a3dbc","names":["packages/goal/goal/src/domain.ts#GoalMessageSource"],"sources":["packages/goal/goal/src/domain.ts:47"]}, - {"digest":"7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"8064c03c87c357fd1575cb9395ce86e6dcbe2d275bf7717864a02cddf01827d5","names":["packages/llm/llm/src/types.ts#ContentBlock"],"sources":["packages/llm/llm/src/types.ts:157"]}, {"digest":"80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc","names":[],"sources":[]}, {"digest":"8067b0d232c350f189738e60ee3c9939d46ca3b32b45db5525237b077893f649","names":[],"sources":[]}, @@ -395,6 +393,7 @@ {"digest":"83d6916021eede8f2d83a1872716caa1efdec39a3681890996c55147187fdd12","names":[],"sources":[]}, {"digest":"83da72c6857601c75da11212ef847f57d457b9c99f0a82246dcdff3e26700239","names":["packages/context/agent-instructions/src/render.ts#AgentInstructionChange"],"sources":["packages/context/agent-instructions/src/render.ts:62"]}, {"digest":"8465ece5e9d9007c038b357015d849c15262cb0bc25abc59e47692d87ee01a15","names":["packages/workflow/workflow/src/types.ts#WorkflowStopReason"],"sources":["packages/workflow/workflow/src/types.ts:63"]}, + {"digest":"848639f8787f035b480ec53cb5686850897c5e8006d87ca231cd8a9ee8634936","names":["packages/subagent/subagent/src/continuation-messages.ts#SubagentSettledMessageSource"],"sources":["packages/subagent/subagent/src/continuation-messages.ts:29"]}, {"digest":"84ac8c1a66ffc697262e181f42e851259eae14038c113ca329fb4700ccdb1f7c","names":["packages/goal/goal/src/types.ts#GoalBlockReason"],"sources":["packages/goal/goal/src/types.ts:52"]}, {"digest":"84bbfdce7d2eab5b0c53e72ff7406db856c8bfd621b965b72fd86598ba493bf7","names":[],"sources":[]}, {"digest":"854db3efdfb0cd39d30953b28703e519c121f1115cebfffc40369fe86c406dd1","names":[],"sources":[]}, @@ -402,6 +401,7 @@ {"digest":"85f9b505b7bdff1f61845c4cea8f36fd0fde1b62facbe87d8924d1d27e616f3a","names":[],"sources":[]}, {"digest":"85fe96bf15d5c7559eec3bae4d6cf1a76fda9f5be05a29c2830cff560cab0c0d","names":[],"sources":[]}, {"digest":"8620189c8e33582708ece48fd2d20dc4d57912486a17bdbb9aea4c44f7018062","names":[],"sources":[]}, + {"digest":"866f7b2dbdc5b421eab3e629312d1c839b75c259633b4b43b50d23bac44d92a0","names":[],"sources":[]}, {"digest":"86d1d0e9cfebb240421187e3dc37fb71cc38a1501885cf32f8f9adef7b0a2bde","names":["packages/subagent/subagent/src/descriptor.ts#SubagentDescriptorData"],"sources":["packages/subagent/subagent/src/descriptor.ts:89"]}, {"digest":"86e1e384495ee09ac2d60c9db3610f1f1fddac2d248f6f1d6000e78054680219","names":["packages/llm/llm/src/message.ts#ContextSnapshotSection"],"sources":["packages/llm/llm/src/message.ts:70"]}, {"digest":"871bfd6f7bb91061246768d3377f3fd58d6b8ea7c31f44c714ae7ab215650d62","names":[],"sources":[]}, @@ -420,11 +420,12 @@ {"digest":"8e31bb958e9b015e6f8407eaade32217068159e816f3cc99c3ad76eb889732e0","names":[],"sources":["packages/llm/llm/src/types.ts:167"]}, {"digest":"8e611bf46821e5003a1605a73560a6f56388295149d449dfe2142d5ec335f29c","names":["packages/llm/llm/src/types.ts#ToolAdditionBlock"],"sources":["packages/llm/llm/src/types.ts:122"]}, {"digest":"8e8155594e07812356b67d732196dda894b0f9c91a5969d51612cf490b0a016d","names":[],"sources":[]}, - {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:237"]}, + {"digest":"8e8e91646a5cae3fc78f7532a0013ff2088ae47077642c2edd507a508209b8af","names":["packages/schedule/schedule/src/types.ts#OneShotScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:213"]}, {"digest":"8f324cea3916c0517261e88167def8efb3a9994c1135e23d40ed9fd48f8c7bd4","names":[],"sources":[]}, {"digest":"8f6d609794bf5afc01d7ccf3e03811d32f4b8047f58a2c9a98db0154c2ad7cb9","names":[],"sources":[]}, {"digest":"8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543","names":[],"sources":["packages/core/tools/src/index.ts:28"]}, {"digest":"904bf499d98be4a3a5f836fcac533b6c4899569b018071e6604e1d32657d00fd","names":[],"sources":[]}, + {"digest":"920d87e22b7409bcc7224f8b1dc7f5101c33574c75627c65baab12b85cc96e75","names":[],"sources":[]}, {"digest":"930c1cd289def119d443e19dd90008916bf035f0a4d23e07241e7f050f2b89b7","names":["packages/interaction/user-approval/src/types.ts#ApprovalOutcome"],"sources":["packages/interaction/user-approval/src/types.ts:32"]}, {"digest":"935c8d486292b13c87b57ca280eb8c58b5b2f5239be86fcd4334c33fdeb87682","names":[],"sources":[]}, {"digest":"938f7c7357bc403ea3b281a9dd016939df7a0880fc8db12612585be574d0d615","names":[],"sources":[]}, @@ -434,6 +435,7 @@ {"digest":"94c56aeb1564ad735eb773d88636b40761d063efa1610f1308004d32923f5378","names":[],"sources":[]}, {"digest":"95080295115fbd83544520ba247b68a03790131f6a2eac323d388758cb542f65","names":[],"sources":["packages/llm/llm/src/types.ts:498"]}, {"digest":"95a3ffccbf3c8afcf9a2f3b355f724da8e07e98dc47ee741166dde7f9ea058bd","names":[],"sources":[]}, + {"digest":"95b5cf90ea1f57da3319184d6f5f3811d0f651aa9113591c10e81c3d1e9b9f70","names":[],"sources":[]}, {"digest":"95c0e88fcf0bafb2087f912ad9e2369de6ae6530cc0c4c2772c96205b57f7f60","names":[],"sources":[]}, {"digest":"9645cf93769a6dfb227bd400bd6cb9fa7bab9140f4a851e4ae92514ade6e3114","names":[],"sources":[]}, {"digest":"96bfb916a727cd4445a594df264c523fc039749a31bfed924b8cc7bb308a5bb0","names":[],"sources":[]}, @@ -471,7 +473,7 @@ {"digest":"a3a259a1aa5401af786ce08c4a8419681d3000d73467991b5fc563389bc4ebd2","names":[],"sources":[]}, {"digest":"a3c6f1ea38e9a61d7a9706057ba65aabe02dfe6d9dd90d4736aa62325d874531","names":[],"sources":[]}, {"digest":"a3edd1efd1fef21b72c55e213c8a8b24196b091abde2b89db52be0b2aaae3cfa","names":[],"sources":[]}, - {"digest":"a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c","names":[],"sources":["packages/experimental/agent-team/src/types.ts:232"]}, + {"digest":"a40d12070f6f4a124f32fb3cc86e7857554702e32f0eda3080a25c4b9ac9b18c","names":[],"sources":["packages/team/agent-team/src/types.ts:175"]}, {"digest":"a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302","names":[],"sources":["packages/api/session-controller/src/types.ts:397"]}, {"digest":"a6567ccb2e530606b775371eb4fa31468d72084339968e8b0440a516a23b39dc","names":[],"sources":[]}, {"digest":"a6b41f5bede8094d7bf635be5d69b1bd7a25e006ca9cf9415bceb9322f1a7feb","names":["packages/experimental/hook-protocol/src/types.ts#HookDialect"],"sources":["packages/experimental/hook-protocol/src/types.ts:48"]}, @@ -508,14 +510,15 @@ {"digest":"b0127044ab31a702bddfd785d345f5abd7a70876746e895ce443afa3e60ddf2d","names":[],"sources":[]}, {"digest":"b062078e899958f99ae464514578b8c093924dfe34bd9a835932b420ff2150b1","names":[],"sources":[]}, {"digest":"b0b0eb1b16490f6bee135b2377e8f8c39227974c799ad7d49ff418af23ecbc35","names":["packages/attachment/attachment/src/types.ts#ImageAttachmentRef"],"sources":["packages/attachment/attachment/src/types.ts:11"]}, + {"digest":"b120362fd216a16a40fe787f6d3286086aa131266322bab79c026a130ccd0f72","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:136"]}, {"digest":"b158f3ff6923714807c0d73882f0b05dc87f8fa85c9e90814852d48bbc866081","names":["packages/core/session/src/types.ts#RequestContext"],"sources":["packages/core/session/src/types.ts:260"]}, {"digest":"b1664fa89f8eab49a14e7e3168d8bc4da4aa9fd76332f6c4a053d839e5276ae7","names":[],"sources":[]}, - {"digest":"b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1","names":[],"sources":["packages/experimental/agent-team/src/types.ts:230"]}, + {"digest":"b1ebd5cda47d90d980bb05bffc3f970c51537b9aff15b3bc3d639811727741b1","names":[],"sources":["packages/team/agent-team/src/types.ts:173"]}, {"digest":"b1f62380f6746fedd629e71065e3583cef83334875b499ac9665c2eb87acfbf5","names":[],"sources":[]}, {"digest":"b222069eea2d768065161c1147b1f2c78c1b54328c84b3586ae5c8f91b8ed35e","names":[],"sources":[]}, {"digest":"b2245a906e13aa94f2d3cc6cf7b04cfa0267f7b7f4d468de1b00b1a314e54626","names":[],"sources":[]}, {"digest":"b2a5c8c008a31e3dc6c3013502f2356aca13894b31c8e70601fa92f2d40d1dba","names":[],"sources":[]}, - {"digest":"b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943","names":["packages/experimental/agent-team/src/types.ts#TeamTaskStatus"],"sources":["packages/experimental/agent-team/src/types.ts:72"]}, + {"digest":"b2d2a01e51341a3bfec809198952c8c830a7899f4cb6ecd3c1dc0b5d9a2af943","names":["packages/team/agent-team/src/types.ts#TeamTaskStatus"],"sources":["packages/team/agent-team/src/types.ts:61"]}, {"digest":"b3681c026a0b98e98b103f057dfd217fbe904129c090efd668253ec9aea7fece","names":[],"sources":[]}, {"digest":"b38f206d59bad891fa58c89f97a0036987b3defe7685acbd318fa55eb85f9751","names":[],"sources":[]}, {"digest":"b4ec0af39fd52ed971990e42f04e5be3204882e555c409eb330f8238eec21569","names":[],"sources":[]}, @@ -558,6 +561,7 @@ {"digest":"c1f0f17b6493b85db6453bb30e01b208d703731b25bc1e68e5d4fc72eea9cdea","names":["packages/llm/llm/src/types.ts#ToolCallBlock"],"sources":["packages/llm/llm/src/types.ts:112"]}, {"digest":"c1f9e0405de6d18cabb9ee70782a027f9bbdc57e5abec9dcccdd56119e2e9058","names":[],"sources":[]}, {"digest":"c219efbdfd53b836786202ab4532913d555798f0a8615a4e9629736e3799fb70","names":[],"sources":[]}, + {"digest":"c2a13242efc3bea4b36a843ddf1524ff4d33c765a71b582fa1fdbfa4fa148434","names":[],"sources":["packages/team/agent-team/src/types.ts:171"]}, {"digest":"c2deb7c9183735d4e0fffddf5c623f4e34daa1c8e96b111982e957dfcbbcf896","names":["packages/workflow/workflow/src/types.ts#WorkflowAgentOutcome"],"sources":["packages/workflow/workflow/src/types.ts:110"]}, {"digest":"c2f49004d9ae38a964e80850c87bc6849d6a872091a1d43e99eedf00c641e2a3","names":[],"sources":[]}, {"digest":"c43b119ce579b3e9983a0d3adc4ba402ebb9ba773d89738a2dab01ecf5813943","names":[],"sources":[]}, @@ -567,7 +571,6 @@ {"digest":"c589e938cc0e4989df8b82abef6339de621f0dc4fe62c230d145b94996af7f92","names":[],"sources":[]}, {"digest":"c592ce75aab73fcab19c1d7845684c72cf402b78d2e1f2833a58ecf9f3598ed6","names":["packages/util/values/src/index.ts#JsonValue"],"sources":["packages/util/values/src/index.ts:4"]}, {"digest":"c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262","names":[],"sources":[]}, - {"digest":"c78b9097bfae83cd08f0a98a92730236ba80ac61d712046959e4fc7f28aa1f36","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:196"]}, {"digest":"c8e6f48878cc2a2f0dc59682280d81f407943fb503f32c64bf9ff3d9393c3eff","names":[],"sources":[]}, {"digest":"c99e20441bf15341e9db54385e558e5c03d21dff2eb1ac08ccbf47c2d8747954","names":[],"sources":[]}, {"digest":"ca085dba2c877feceebf3c62f9d39c6c2a4d2314d97b94b3927a780fe8fe2bb2","names":[],"sources":[]}, @@ -579,21 +582,21 @@ {"digest":"cda2345a9be9d139df49ccbd16dcba716f3440178bf20ff8b801fda1f5eb77dc","names":[],"sources":[]}, {"digest":"cdca80b8dad24d4e7b1d5a288a8475ba8d8d46be385bd2da85f122ee836f1670","names":[],"sources":[]}, {"digest":"cdee10e87dbed8440d8b6935888624884878efc7af95402e94171b29f173dced","names":[],"sources":["packages/llm/llm-retry/src/types.ts:17"]}, - {"digest":"cdf988172b589b230f2bce868489def1bb575eb0501076ac757a8f369ac5c64e","names":[],"sources":[]}, {"digest":"cef171adf021a1867d244618a3dbbaafc22beb17c7f3df3ee203393271c8c6f6","names":["packages/core/tool-executor-ptc/src/types.ts#PtcDispatchEventData"],"sources":["packages/core/tool-executor-ptc/src/types.ts:21"]}, {"digest":"cffcdc19881ab61ec0a9ce18743996f7ac44ac8889f34dfac36ae745574aa22f","names":["packages/goal/goal/src/domain.ts#GoalClearChangeMeta"],"sources":["packages/goal/goal/src/domain.ts:35"]}, {"digest":"d0fbb0ca1bbba059830826f33f801da1aced35a2504376d61e020bdfec8d50c0","names":[],"sources":[]}, {"digest":"d28765f87d6b6ab408e0b2f3e7e297791b004b806d8e302c49903ebae815feb2","names":[],"sources":[]}, {"digest":"d4b739491689cc6bb13d07ffac1a32239875abda364c0d5edd8f74faf5e9c00d","names":[],"sources":["packages/llm/llm/src/types.ts:501"]}, {"digest":"d4c799e3d51cae1040362ba4968efc484739e14416c9c1df20c2f108b4ef2eb5","names":[],"sources":[]}, - {"digest":"d4d960185026266ed7bd127be1e252234689e8b4890c7c2677a644ba58f35401","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"d4e4d575abeb4b72d616dc65c17ac0eaa943cc135609395044c38d5afcb10e31","names":[],"sources":[]}, {"digest":"d595ec73b32b016a6055333c67a5d646032b22e672da1d4a09c5b1ae398a093a","names":[],"sources":[]}, {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, {"digest":"d66e11dddf5dfa3c71547e2cbd7b0608824cd8d6243fc16f532017ff28e8fba5","names":[],"sources":[]}, {"digest":"d6e654b88b584fcdf290a56802b1730bc7b9847ae86baa4265ab7769eb48990c","names":[],"sources":[]}, {"digest":"d85590a5675c6e2fd8164e5792a6cceac714605b8ac228adae5ee668facb1490","names":[],"sources":[]}, + {"digest":"d8a476d2c6fd30df6ec0e799f91716d1518c780d23b4121dce545abfcfb7c5a5","names":[],"sources":[]}, {"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]}, + {"digest":"d95c624eddecdacf1ee74356196c09d2f3fcd625714be5e852a6b643fa12a7ca","names":[],"sources":[]}, {"digest":"d9c462b9f62fdd3efc76a44b9524dc8781f6b91cd9c7e584b17d971defafebab","names":["packages/llm/llm/src/message.ts#ToolMessageSource"],"sources":["packages/llm/llm/src/message.ts:29"]}, {"digest":"d9edf1862e4471d6ad8a106a3f4160e0643874368707d50ecd8e27e5ee7a2567","names":[],"sources":[]}, {"digest":"da60ed58a8fa23d7aa4920ab5c1f4e3d28109cb0797ef9e5c8b125721b847582","names":[],"sources":["packages/session/working-directory/src/index.ts:36"]}, @@ -603,10 +606,12 @@ {"digest":"db874d463b0fdec77e9da1c4568f37cb70bd6596781eb93800db44fb8a116965","names":[],"sources":[]}, {"digest":"dba54c09c6e7aafc9acbed7792ecc920d99f92d0784aeeed10af55f7fe0bc8cd","names":[],"sources":["packages/core/tool-executor-ptc/src/types.ts:68"]}, {"digest":"dbdafceb9a900183cccc80596498d386f3bf7bddead2b8cfde68453aa4739edc","names":[],"sources":[]}, + {"digest":"dcb07e04496586d2664d72dab0e94312917da56927b2a0dc3ee53d6a33e32450","names":[],"sources":[]}, {"digest":"dd00cdccd0ba487b92362ef67db58cd264f48c1bfd368291424a1da9a899489a","names":[],"sources":[]}, {"digest":"dd2780e7e07684332f7a9ab047237798d260e7eaffb1321cb38eca695d184c3d","names":[],"sources":[]}, {"digest":"dd5ee8762bd8a14b6c6bffedd1753e4e78505bb0f9ea1621018d03a54eef59d5","names":[],"sources":[]}, {"digest":"dd6cc2bb2a8f28248347021ad93565360b196a042360b4cd16b569d3a2a91f2d","names":[],"sources":[]}, + {"digest":"ddce54a3873dc57113b0cd38ad9b23b3c259186139e8847e5e5f415d86f52482","names":[],"sources":[]}, {"digest":"dde0cdf9d426768b649b5a9783d2144e7f900c35ef65229cd89036dbf411d1b0","names":[],"sources":[]}, {"digest":"de25352d2dc4196309bd84b5bac6319f6d5c898ea0e82bb5ae66c5738d0d426f","names":[],"sources":[]}, {"digest":"de30b1fa12c75f81df6aa4096e1595296d2d04e2be14a7c29849cf8028b79048","names":[],"sources":[]}, @@ -614,8 +619,10 @@ {"digest":"deebfc7c62177ea840f23c6362b8615bc78ffa93377dd5d243c04e541c413af5","names":[],"sources":["packages/typert/protocol/src/types.ts:457"]}, {"digest":"df5d9709b7db2a72510dc52052a23f0c38f39730af1504bab8bccabc14fae528","names":[],"sources":[]}, {"digest":"df843efd87c78cf8de98f8e0d0216956cd568d0d0e56a22c853663e274aa1a18","names":[],"sources":[]}, - {"digest":"dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd","names":["packages/experimental/agent-team/src/types.ts#TeamMemberPhase"],"sources":["packages/experimental/agent-team/src/types.ts:45"]}, + {"digest":"dfce5db4aa42b7ebe0bb79eca92553587287e18c06b9eba85cbfb9d332e26acd","names":["packages/team/agent-team/src/types.ts#TeamMemberPhase"],"sources":["packages/team/agent-team/src/types.ts:47"]}, {"digest":"e0a787e6ec76c7c94fecbc501b489164ab0293db05bc947914077ad01e674f05","names":[],"sources":[]}, + {"digest":"e1880c67e735e228f3555df8a55a492db2c0b0c71bc8859e938e184a46c7db51","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, + {"digest":"e272493e3ea0b33b2e1d64b6a80e9d8bd3d1d466cc115f2facbdd598f8644a39","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:196"]}, {"digest":"e2ad8f5bcd813f268ffef1b10a12d7ddd2b8ced8b9b6d0275b3f6b7ed094a187","names":[],"sources":[]}, {"digest":"e2d0367e5716bc188435e51718ebff8ce873190625fa93b1c5331102d98758fa","names":[],"sources":[]}, {"digest":"e2f9a41e0989f54ed8cee80f8db2bcf9d60a5c810dc9d45b83fa050b9dce7602","names":[],"sources":[]}, @@ -630,7 +637,7 @@ {"digest":"e4c18e294232c3ba6c9f1999f168263cc55956147cfe4121720899be8e52edd1","names":[],"sources":["packages/core/session/src/types.ts:369"]}, {"digest":"e4cac694f8b6e1d52e48c699464f1c4c26111ef87e558f7931040d00fdc8d486","names":[],"sources":[]}, {"digest":"e5d3828df1ec3e2a66879de0659e0f4866d9cfffc00825ee731a66f8a0c03d98","names":[],"sources":[]}, - {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:244"]}, + {"digest":"e6063d0451dc02026fd9b54ad3f77c7b1b6392ad3e872a7737ac84e13ca72344","names":["packages/schedule/schedule/src/types.ts#EveryScheduleDispatchChange"],"sources":["packages/schedule/schedule/src/types.ts:220"]}, {"digest":"e6411b09c1d982f789bf741ca74e2bea69df56029847f86a6148e722039ee732","names":[],"sources":[]}, {"digest":"e72269f931559e901e5e8fe1cfcbd0669fb795f43cc038ff39fba62f60403c33","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:21"]}, {"digest":"e75916628f3f10c2d50658bd143052a46285fbf1a9a700ba54947614603d26b4","names":[],"sources":[]}, @@ -640,7 +647,7 @@ {"digest":"e7f4cbb3a57f4cbdb61ea41e95bcba626ad1fff6bb9b1e063b1d50a32da6e864","names":[],"sources":[]}, {"digest":"e8de0f457fed5b9ff94dc4950b59ef75fd8ba8af665cc7899485924a62653367","names":[],"sources":[]}, {"digest":"e95f957154b2b1b58692af53d4131180b6dd19e2264869f876dbaa959991494e","names":[],"sources":[]}, - {"digest":"ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403","names":[],"sources":["packages/experimental/agent-team/src/types.ts:234"]}, + {"digest":"ea08ec1df0c33108fd03345b9af199cf04dea450aa045d3c683f216311403403","names":[],"sources":["packages/team/agent-team/src/types.ts:177"]}, {"digest":"eaa71be0fbf0f702df8ea6c11d0aa2f9782263d45a10d0fb14eda662f4bfe04c","names":[],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"ebb768d85ec87fb68e42fc14fd7d8535b5ac11791b14d04c6770180f0a719bf8","names":[],"sources":[]}, {"digest":"ec38b5949af8eacaf00df002f4acbe344f934f8a061e9cdc65a52a48e5f6dd93","names":[],"sources":[]}, @@ -648,7 +655,7 @@ {"digest":"edbbfff1128099fda7b792c56330d2cb04debc9790988e66d1c3f4026e813e0e","names":[],"sources":[]}, {"digest":"edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf","names":[],"sources":[]}, {"digest":"ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad","names":[],"sources":[]}, - {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:223"]}, + {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:199"]}, {"digest":"eefbea819caeeea91ccb02dfafc16c68dd7f961cf9c1b2be25a2084509cf5c5a","names":[],"sources":[]}, {"digest":"ef11a3b7fa2033ae4279545ff8a8a2ee4e301b9b73e5b91654c48e6d08283545","names":[],"sources":["packages/core/session/src/types.ts:305","packages/core/session/src/types.ts:307"]}, {"digest":"ef226a90ddac6cd8e631a3a337a3a3e27f9494be92befb7c718b404681d75e21","names":[],"sources":[]}, @@ -692,11 +699,11 @@ {"digest":"fe1a7acdeed4d0f5ab483396eaa5b3dc97263b7c10eb4da2f0028cb01728bfc9","names":[],"sources":[]}, {"digest":"fe792a6cd430494503837e21e79f91677704ccdd9e870c679aabd7d43ed47ddd","names":[],"sources":[]}, {"digest":"fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394","names":["packages/llm/llm/src/types.ts#TokenUsage"],"sources":["packages/llm/llm/src/types.ts:182"]}, - {"digest":"fee1caf8ab6a65c1bc981f5a1730164490f22a2a89ffa3d0b76f1f432c44c8b5","names":[],"sources":[]}, - {"digest":"ff2cbb53582d1827b02622482246979942f59e07e0393b76a161251423549e72","names":[],"sources":[]} + {"digest":"fee1caf8ab6a65c1bc981f5a1730164490f22a2a89ffa3d0b76f1f432c44c8b5","names":[],"sources":[]} ], "nodes": { "0116b1f89c05221d": {"kind":"literal","value":"web_search_20250305"}, + "01c161379a3c3394": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"b120362fd216a16a","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, "022623b9ef98ec47": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "023a355b2be0d688": {"kind":"object","properties":[{"name":"kind","type":"254dce209e735f9c","optional":false}],"indices":[]}, @@ -811,7 +818,6 @@ "2da725e554cd8930": {"kind":"literal","value":"fork"}, "2e3523541e942ef6": {"kind":"union","types":["18dc21f12bbac8ad","8e8e91646a5cae3f","e6063d0451dc0202","eea687d437880bd5"]}, "2e4debca12f2c449": {"kind":"literal","value":"team-message"}, - "2e505098f9209e52": {"kind":"object","properties":[{"name":"data","type":"7ff62f6599c083ce","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "2eafefdc6f79a492": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderId","type":"4cd48f3e5108bd6e","optional":false},{"name":"senderName","type":"4cd48f3e5108bd6e","optional":false},{"name":"targetId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, @@ -854,7 +860,6 @@ "3ee93b06f3a12585": {"kind":"object","properties":[{"name":"data","type":"7c6129b6961cf4b2","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"44818000e56acb97","optional":false}],"indices":[]}, "3f74ba74acd10644": {"kind":"literal","value":"image/jpeg"}, "3fdf9582c3b5597d": {"kind":"object","properties":[{"name":"afterSeconds","type":"0657d3ca5ac4e7bf","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"5b232a9b9bfcc0fc","optional":false},{"name":"prompt","type":"4cd48f3e5108bd6e","optional":false},{"name":"scheduledAt","type":"4cd48f3e5108bd6e","optional":false},{"name":"title","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, - "4035903993dfee62": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"7e9f1072c17f7aa8","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "408927267422a7b2": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "4208123b50df5006": {"kind":"object","properties":[{"name":"data","type":"ad0c38a0adb82a94","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"3e0eff5946255ff0","optional":false}],"indices":[]}, "42e0916e0dda5f6d": {"kind":"object","properties":[{"name":"data","type":"7f9365bae9fcb73e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"fe792a6cd4304945","optional":false}],"indices":[]}, @@ -873,6 +878,7 @@ "48f9c19417a1abbe": {"kind":"object","properties":[{"name":"data","type":"0bcfaf5566d27102","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"a8a2b9011fc06786","optional":false}],"indices":[]}, "4991dfc415c9efeb": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "49dab019d00e8c26": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, + "4a561c111a78d452": {"kind":"literal","value":"refusal"}, "4a9bef9f27a94252": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"82470020b5bfcb1a","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4ae007ed190a72c9": {"kind":"literal","value":"llm/retry-started"}, "4aed17ec726b5397": {"kind":"tuple","elements":[{"type":"2d11ca7b0d4493e2","optional":false,"rest":false}]}, @@ -885,7 +891,6 @@ "4e011753f8263f43": {"kind":"literal","value":"team/message/queued"}, "4e44c9118152f682": {"kind":"literal","value":"text"}, "4e88776858652856": {"kind":"object","properties":[{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"4e44c9118152f682","optional":false}],"indices":[]}, - "4e97c3d85c0fc817": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "4edec1b770e8ec4c": {"kind":"literal","value":"ptc-mode"}, "4f507598cf476214": {"kind":"literal","value":"series"}, "4f91f187baeabef5": {"kind":"object","properties":[{"name":"capturedFormatVersion","type":"0657d3ca5ac4e7bf","optional":true},{"name":"capturedThroughSeq","type":"3bd652ebfa8726b3","optional":false},{"name":"compacted","type":"aa93010d0e521ad7","optional":false},{"name":"inputIndex","type":"0657d3ca5ac4e7bf","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"omittedBytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"omittedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"originalMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retainedMessages","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"truncated","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, @@ -901,7 +906,6 @@ "530da6c0267813bb": {"kind":"union","types":["34d1ab5c5df37818","4f507598cf476214","e7ce49f12953583f","f789af5ab844827e"]}, "53750b9abf61efb7": {"kind":"object","properties":[{"name":"data","type":"f731ffe80810b028","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"44c8c77aa9aa100b","optional":false}],"indices":[]}, "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, - "53d4f8256bc58109": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"64ef542b1bfc9883","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "54f9276a1617d7c1": {"kind":"object","properties":[{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"stream","type":"84bbfdce7d2eab5b","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "557e148d30b79ee4": {"kind":"literal","value":"agent-preset/selected"}, "5654685d7557ec74": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, @@ -918,7 +922,6 @@ "5abab3a27fd27366": {"kind":"literal","value":"text-delta"}, "5b232a9b9bfcc0fc": {"kind":"literal","value":"after"}, "5b6fb1f226ff5640": {"kind":"object","properties":[{"name":"commandId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"1ab2ef1296f157ba","optional":false},{"name":"sourceEventSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"text","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, - "5bb231bc5afdb532": {"kind":"object","properties":[{"name":"data","type":"4035903993dfee62","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "5bb69b88517f6214": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "5bc66269cfaf614c": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"d9edf1862e4471d6","optional":false}],"indices":[]}, "5bd310104cfe448e": {"kind":"literal","value":"resource-cost"}, @@ -935,15 +938,17 @@ "5f2117d1856a5ab4": {"kind":"object","properties":[{"name":"code","type":"4cd48f3e5108bd6e","optional":false},{"name":"message","type":"4cd48f3e5108bd6e","optional":false},{"name":"offloadImages","type":"0657d3ca5ac4e7bf","optional":true},{"name":"providerRetryAfterMs","type":"0657d3ca5ac4e7bf","optional":true},{"name":"requestId","type":"4cd48f3e5108bd6e","optional":true},{"name":"status","type":"0657d3ca5ac4e7bf","optional":true}],"indices":[]}, "5f26a6c20b37632f": {"kind":"object","properties":[{"name":"data","type":"9a410ddf56792b2b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"ad92f473a03ae725","optional":false}],"indices":[]}, "5f758f3de5f00c18": {"kind":"object","properties":[{"name":"label","type":"4cd48f3e5108bd6e","optional":true},{"name":"mode","type":"d28765f87d6b6ab4","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "601327bedca5f98a": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"95b5cf90ea1f57da","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, "611cae9a3539733a": {"kind":"literal","value":"llm/retry"}, "611d82d2dc50df70": {"kind":"object","properties":[{"name":"cause","type":"750a2b129d67704d","optional":false},{"name":"detail","type":"4cd48f3e5108bd6e","optional":true},{"name":"finishedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"jobId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"owner","type":"4cd48f3e5108bd6e","optional":false},{"name":"producerReported","type":"aa93010d0e521ad7","optional":false},{"name":"startedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"status","type":"c2f49004d9ae38a9","optional":false},{"name":"toolCall","type":"39cf2d3ff8bac81c","optional":true}],"indices":[]}, + "613660455704fb82": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"b120362fd216a16a","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.user-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, "616f93a5047de668": {"kind":"literal","value":"tool-call-chunks"}, "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, "62e6a429ff3f390a": {"kind":"union","types":["1d8798b1a5e8c545","1e346446e183ee76","34d1ab5c5df37818","7624ca28c61ca0ea","ad22a5ca5bbaab2e","d9196086e41e4dd5"]}, "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, "6487b10ba7542f3c": {"kind":"object","properties":[{"name":"agentModel","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentProvider","type":"4cd48f3e5108bd6e","optional":true},{"name":"agentReasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"mode","type":"e5d3828df1ec3e2a","optional":false},{"name":"persona","type":"4cd48f3e5108bd6e","optional":true},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"toolFilter","type":"3cfc3a56502da1f8","optional":true},{"name":"version","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "64ef542b1bfc9883": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"7e9f1072c17f7aa8","optional":false,"compatibility":{"version":1,"policy":"session-source-attribution","binding":"session.developer-message.source","discriminator":"kind","unknownKinds":"preserve","attributionKinds":["action-cards","tmux-context","user-question-reply","working-directory"]}}],"indices":[]}, + "65377a76c6a58f78": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"01c161379a3c3394","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "6598cd6da253948d": {"kind":"object","properties":[{"name":"context","type":"50cf02d875f8a1f1","optional":false},{"name":"description","type":"4cd48f3e5108bd6e","optional":false},{"name":"error","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"phase","type":"dfce5db4aa42b7eb","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "65a8400e451e667e": {"kind":"object","properties":[{"name":"kind","type":"09655b34d7f3cf1e","optional":false}],"indices":[]}, "65d583e66518c523": {"kind":"object","properties":[{"name":"entries","type":"aba175fb20ffc711","optional":false},{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"incomplete","type":"dacf3d5f3e4ff619","optional":true},{"name":"kind","type":"6ebcc2dbec9f2dab","optional":false},{"name":"update","type":"dacf3d5f3e4ff619","optional":true}],"indices":[]}, @@ -953,6 +958,7 @@ "68141cbe3994a5ff": {"kind":"literal","value":"max-tokens"}, "688e853dc149f0d3": {"kind":"literal","value":"reasoning-chunks"}, "68f44f59e91c4139": {"kind":"literal","value":"user"}, + "690583582246babf": {"kind":"array","element":"613660455704fb82"}, "69081694be231d56": {"kind":"object","properties":[{"name":"data","type":"6bc8e51124d0874b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1c5a58f4599bd4a9","optional":false}],"indices":[]}, "693f4952fb5565da": {"kind":"object","properties":[{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"a2be0f0cb59f0d4a","optional":false}],"indices":[]}, "69d238a6e9b08d67": {"kind":"literal","value":"interrupted"}, @@ -977,7 +983,7 @@ "6f72ece8f317cd08": {"kind":"object","properties":[{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "6f9e00383836275e": {"kind":"literal","value":"snapshot"}, "70b082fe78991edf": {"kind":"literal","value":"request/context"}, - "70d2acdec1ebcfea": {"kind":"object","properties":[{"name":"data","type":"53d4f8256bc58109","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, + "70ea8e7943c5e2d7": {"kind":"object","properties":[{"name":"data","type":"65377a76c6a58f78","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1379f0b72275994d","optional":false}],"indices":[]}, "7180844e1066230c": {"kind":"literal","value":"service-stability"}, "719c51f67074f970": {"kind":"object","properties":[{"name":"kind","type":"2765e9119edf5816","optional":false},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"replayState","type":"bbc5696e3f13c758","optional":true}],"indices":[]}, "71bb3254ec8f1e49": {"kind":"object","properties":[{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"texts","type":"93c33d9687613293","optional":false},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"688e853dc149f0d3","optional":false}],"indices":[]}, @@ -995,20 +1001,17 @@ "7a651f3b672c52fb": {"kind":"literal","value":"session/title"}, "7af85bf70d4eafce": {"kind":"object","properties":[{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, - "7c203f3d4dfa6638": {"kind":"array","element":"4035903993dfee62"}, "7c6129b6961cf4b2": {"kind":"object","properties":[{"name":"messageId","type":"4cd48f3e5108bd6e","optional":false},{"name":"sessionId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "7c9f44e90a0058f4": {"kind":"object","properties":[{"name":"data","type":"5302e76315127761","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"570e850224346133","optional":false}],"indices":[]}, "7d226b9fd95b4ba2": {"kind":"union","types":["1df34a6c086866ff","cffcdc19881ab61e"]}, "7d54a5a5e629e2e7": {"kind":"object","properties":[{"name":"category","type":"3305a4bb6b6c29b4","optional":true},{"name":"text","type":"4cd48f3e5108bd6e","optional":true}],"indices":[]}, "7d65acf0a3a43a8f": {"kind":"union","types":["1f0133217eeeffd8","277b61f9c6f81704","3c2535ca0a2062f1","4e44c9118152f682","83d6916021eede8f","85f9b505b7bdff1f","fb8b6a2e53cb9cf4"]}, "7df62978a2b7de85": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"78a9be340090b735","optional":false}],"indices":[]}, - "7e9f1072c17f7aa8": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","4e97c3d85c0fc817","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "7f13860ee89a2d35": {"kind":"literal","value":"session-reference"}, "7f7fd5a6b0064f59": {"kind":"object","properties":[{"name":"data","type":"5dd766ccd1702a11","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"10e386801903f9d4","optional":false}],"indices":[]}, "7f9365bae9fcb73e": {"kind":"object","properties":[{"name":"runId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"8465ece5e9d9007c","optional":false}],"indices":[]}, "7f959241c24128b4": {"kind":"object","properties":[{"name":"goalId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"b815d7b91cdd9fc6","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false},{"name":"round","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "7ff62f6599c083ce": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"ff2cbb53582d1827","optional":false},{"name":"reasoningEffort","type":"4cd48f3e5108bd6e","optional":true},{"name":"route","type":"07e1a58c58b593f5","optional":false},{"name":"system","type":"4cd48f3e5108bd6e","optional":false},{"name":"titleProvider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8064c03c87c357fd": {"kind":"union","types":["12d5808fac1996b9","43e311235aa537df","4e88776858652856","814d9434e1ddf907","8e611bf46821e500","c1f0f17b6493b85d","f2da0f27c1e6add5"]}, "80677c8c8b804189": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, "8067b0d232c350f1": {"kind":"literal","value":"time-context"}, @@ -1023,6 +1026,7 @@ "83d6916021eede8f": {"kind":"literal","value":"tool-removal"}, "83da72c6857601c7": {"kind":"object","properties":[{"name":"action","type":"904bf499d98be4a3","optional":false},{"name":"digest","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false},{"name":"scope","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "8465ece5e9d9007c": {"kind":"union","types":["1ebc6f9ff3aa9e3a","2142e391b9ccb60d","a2be0f0cb59f0d4a"]}, + "848639f8787f035b": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bf16d2e98a7f1389","optional":false},{"name":"senderSessionId","type":"4cd48f3e5108bd6e","optional":false},{"name":"stopReason","type":"866f7b2dbdc5b421","optional":true},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "84ac8c1a66ffc697": {"kind":"object","properties":[{"name":"code","type":"4cd48f3e5108bd6e","optional":false},{"name":"message","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "84bbfdce7d2eab5b": {"kind":"array","element":"33341aac09312300"}, "854db3efdfb0cd39": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -1030,6 +1034,7 @@ "85f9b505b7bdff1f": {"kind":"literal","value":"tool-addition"}, "85fe96bf15d5c755": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, "8620189c8e335827": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "866f7b2dbdc5b421": {"kind":"union","types":["1e0b0b66b6f0c53f","1ebc6f9ff3aa9e3a","4a561c111a78d452","68141cbe3994a5ff","a2be0f0cb59f0d4a"]}, "86d1d0e9cfebb240": {"kind":"union","types":["5f758f3de5f00c18","6487b10ba7542f3c"]}, "86e1e384495ee09a": {"kind":"object","properties":[{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "871bfd6f7bb91061": {"kind":"literal","value":"provisioning"}, @@ -1053,6 +1058,7 @@ "8f6d609794bf5afc": {"kind":"tuple","elements":[{"type":"4e88776858652856","optional":false,"rest":false}]}, "8fcb0b44a575e998": {"kind":"object","properties":[{"name":"kind","type":"a720757f704a2512","optional":false}],"indices":[]}, "904bf499d98be4a3": {"kind":"union","types":["7382c4fc95fe8c5d","b765ee31033cea46","f6cb462f808309e3"]}, + "920d87e22b7409bc": {"kind":"object","properties":[{"name":"data","type":"c2a13242efc3bea4","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d8a476d2c6fd30df","optional":false}],"indices":[]}, "930c1cd289def119": {"kind":"union","types":["2142e391b9ccb60d","2c4c21f19f426a58","811229eedcec5797","fab35c4520883c0d"]}, "935c8d486292b13c": {"kind":"literal","value":"web_search"}, "938f7c7357bc403e": {"kind":"primitive","type":"null"}, @@ -1062,6 +1068,7 @@ "94c56aeb1564ad73": {"kind":"literal","value":"in_progress"}, "95080295115fbd83": {"kind":"object","properties":[{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"text","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"5abab3a27fd27366","optional":false}],"indices":[]}, "95a3ffccbf3c8afc": {"kind":"literal","value":"owner"}, + "95b5cf90ea1f57da": {"kind":"array","element":"e272493e3ea0b33b"}, "95c0e88fcf0bafb2": {"kind":"literal","value":"assistant"}, "9645cf93769a6dfb": {"kind":"literal","value":"user-question-reply"}, "96bfb916a727cd44": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, @@ -1136,6 +1143,7 @@ "b0127044ab31a702": {"kind":"object","properties":[{"name":"data","type":"ca59530d1a4f3e19","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1986c2664009c991","optional":false}],"indices":[]}, "b062078e899958f9": {"kind":"object","properties":[{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, "b0b0eb1b16490f6b": {"kind":"object","properties":[{"name":"attachmentId","type":"4cd48f3e5108bd6e","optional":false},{"name":"bytes","type":"0657d3ca5ac4e7bf","optional":false},{"name":"height","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mediaType","type":"2f1e6a7ebace43d7","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"originalDimensions","type":"0f46153645c29784","optional":true},{"name":"width","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "b120362fd216a16a": {"kind":"union","types":["0203243b72fc867a","022623b9ef98ec47","02b2c23f2d94b028","0ed8d1108fe7a5e1","0eeb17e1df89b1eb","11638dc58a31496f","1938c8c20f1cba7c","1e709346005826eb","1fdad624334d3548","2152caf1a71e588e","2235d957bf4b7c6c","224aa11d4d5f88c4","24ce31aa528272e5","260523b412c19ad8","28936c614bd4e7e2","290f32bfd81ff85a","297fbd8067d7815a","2aad1179f9576314","312aee2f0c42aabb","31907de956375182","3247e566f4340029","3b04790e08b35241","3b4f2c9ef2c1217e","3bdb8dc6989655b0","408927267422a7b2","45f005e6bbb76452","4991dfc415c9efeb","49dab019d00e8c26","4a9bef9f27a94252","52c6113cb0e53f34","53cf1704ae0709c7","5654685d7557ec74","58015da1c1950a66","5bb69b88517f6214","5bc66269cfaf614c","5cdbf342b7748d15","5d7a64ed6aac5551","6085488d223aeffd","6292bcbedaa97fea","65a8400e451e667e","65d583e66518c523","672c4aa2a9b736e3","6ccb6bc423fb3952","6ea608bdc8a7a63d","6f22a9d02b9a1f11","6f44f32be9bcd9a8","719c51f67074f970","7554565be416b034","756b5e23a5cb2c7f","7df62978a2b7de85","7eaef7a763ba5b94","7f959241c24128b4","80677c8c8b804189","825ca23416b1ea9d","8338ee303e2bd448","848639f8787f035b","854db3efdfb0cd39","85fe96bf15d5c755","8620189c8e335827","87b1a33564b9a4d6","88841202942c7683","8a046b52331959aa","8c1c4f72755a78ea","8c627d7a45fa406c","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "b158f3ff69237148": {"kind":"object","properties":[{"name":"contextWindow","type":"0657d3ca5ac4e7bf","optional":true},{"name":"model","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"systemPromptUpdate","type":"f311671e07bc7fa6","optional":true}],"indices":[]}, "b1664fa89f8eab49": {"kind":"array","element":"bbc5696e3f13c758"}, "b1ebd5cda47d90d9": {"kind":"object","properties":[{"name":"member","type":"6598cd6da253948d","optional":false},{"name":"teamId","type":"4cd48f3e5108bd6e","optional":false},{"name":"version","type":"a0f906856fc06f1c","optional":false}],"indices":[]}, @@ -1186,6 +1194,7 @@ "c1f0f17b6493b85d": {"kind":"object","properties":[{"name":"arguments","type":"4cd48f3e5108bd6e","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"1f0133217eeeffd8","optional":false}],"indices":[]}, "c1f9e0405de6d18c": {"kind":"object","properties":[{"name":"data","type":"a6da9ad5d42ae83a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"cdca80b8dad24d4e","optional":false}],"indices":[]}, "c219efbdfd53b836": {"kind":"literal","value":"step/end"}, + "c2a13242efc3bea4": {"kind":"object","properties":[{"name":"enabled","type":"aa93010d0e521ad7","optional":false}],"indices":[]}, "c2deb7c9183735d4": {"kind":"union","types":["1ebc6f9ff3aa9e3a","2142e391b9ccb60d","b57a2889408de36e"]}, "c2f49004d9ae38a9": {"kind":"union","types":["1ebc6f9ff3aa9e3a","b57a2889408de36e","ef226a90ddac6cd8"]}, "c43b119ce579b3e9": {"kind":"literal","value":"paused"}, @@ -1195,7 +1204,6 @@ "c589e938cc0e4989": {"kind":"literal","value":"tool/call"}, "c592ce75aab73fca": {"kind":"union","types":["0657d3ca5ac4e7bf","4cd48f3e5108bd6e","529e0ccd0e34079a","72ec79127a9c0d02","938f7c7357bc403e","aa93010d0e521ad7"]}, "c748fb42c80a1200": {"kind":"array","element":"86e1e384495ee09a"}, - "c78b9097bfae83cd": {"kind":"union","types":["09f3f8dc417f2782","4035903993dfee62","4b259f7f8f0a44ad","64ef542b1bfc9883","fa87537f4a9c1e25"]}, "c8e6f48878cc2a2f": {"kind":"literal","value":"active"}, "c99e20441bf15341": {"kind":"literal","value":"feedback/record"}, "ca085dba2c877fec": {"kind":"literal","value":"sandbox/mode"}, @@ -1207,21 +1215,21 @@ "cda2345a9be9d139": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"24b10f7cdae64928","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cdca80b8dad24d4e": {"kind":"literal","value":"tool-workflow/run-start"}, "cdee10e87dbed844": {"kind":"object","properties":[{"name":"delayMs","type":"0657d3ca5ac4e7bf","optional":false},{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"maxRetries","type":"0657d3ca5ac4e7bf","optional":false},{"name":"mode","type":"3bc287e765d58dc3","optional":false},{"name":"policyKey","type":"4cd48f3e5108bd6e","optional":false},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false},{"name":"retry","type":"0657d3ca5ac4e7bf","optional":false},{"name":"retryId","type":"4cd48f3e5108bd6e","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, - "cdf988172b589b23": {"kind":"object","properties":[{"name":"data","type":"d4d960185026266e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "cef171adf021a186": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"isError","type":"aa93010d0e521ad7","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"name","type":"4cd48f3e5108bd6e","optional":false},{"name":"parentCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false},{"name":"subCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "cffcdc19881ab61e": {"kind":"object","properties":[{"name":"cleared","type":"0b6d718c693fdf7f","optional":false},{"name":"clearedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"kind","type":"237c004c73b6b288","optional":false},{"name":"operation","type":"e7e154d47d5fbc53","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "d0fbb0ca1bbba059": {"kind":"literal","value":"delete"}, "d28765f87d6b6ab4": {"kind":"literal","value":"one-shot"}, "d4b739491689cc6b": {"kind":"object","properties":[{"name":"block","type":"8064c03c87c357fd","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"eefbea819caeeea9","optional":false}],"indices":[]}, "d4c799e3d51cae10": {"kind":"literal","value":"working-directory/change"}, - "d4d960185026266e": {"kind":"object","properties":[{"name":"inserted","type":"7c203f3d4dfa6638","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, "d595ec73b32b016a": {"kind":"object","properties":[{"name":"data","type":"a40d12070f6f4a12","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"b57ae1b37e52bee0","optional":false}],"indices":[]}, "d63b8b8ffad9c02f": {"kind":"object","properties":[{"name":"data","type":"8bb8c3751a6ce64b","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"47e5d84f1a93450a","optional":false}],"indices":[]}, "d66e11dddf5dfa3c": {"kind":"object","properties":[{"name":"data","type":"cef171adf021a186","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"fb5e0517050d2c6d","optional":false}],"indices":[]}, "d6e654b88b584fcd": {"kind":"literal","value":"fallback"}, "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false}],"indices":[]}, + "d8a476d2c6fd30df": {"kind":"literal","value":"team/mode"}, "d9196086e41e4dd5": {"kind":"literal","value":"complete"}, + "d95c624eddecdacf": {"kind":"object","properties":[{"name":"data","type":"601327bedca5f98a","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"587bb11da730e06a","optional":false}],"indices":[]}, "d9c462b9f62fdd3e": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"kind","type":"a13d8f379222ece8","optional":false}],"indices":[]}, "d9edf1862e4471d6": {"kind":"literal","value":"schedule"}, "da60ed58a8fa23d7": {"kind":"object","properties":[{"name":"cwd","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -1231,10 +1239,12 @@ "db874d463b0fdec7": {"kind":"object","properties":[{"name":"data","type":"3e4e7683b0192c9f","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"e2d0367e5716bc18","optional":false}],"indices":[]}, "dba54c09c6e7aafc": {"kind":"object","properties":[{"name":"kind","type":"4edec1b770e8ec4c","optional":false}],"indices":[]}, "dbdafceb9a900183": {"kind":"literal","value":"hook"}, + "dcb07e04496586d2": {"kind":"object","properties":[{"name":"data","type":"613660455704fb82","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"sourceEventSeqs","type":"5d03ba38734809bc","optional":true},{"name":"surfaceOp","type":"335e242de1fcc17b","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"de25352d2dc41963","optional":false}],"indices":[]}, "dd00cdccd0ba487b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "dd2780e7e0768433": {"kind":"literal","value":"fresh"}, "dd5ee8762bd8a14b": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "dd6cc2bb2a8f2824": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "ddce54a3873dc571": {"kind":"object","properties":[{"name":"data","type":"e1880c67e735e228","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"829a2fb3be6efd4b","optional":false}],"indices":[]}, "dde0cdf9d426768b": {"kind":"object","properties":[{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "de25352d2dc41963": {"kind":"literal","value":"user/message"}, "de30b1fa12c75f81": {"kind":"literal","value":"image/gif"}, @@ -1244,6 +1254,8 @@ "df843efd87c78cf8": {"kind":"array","element":"4f91f187baeabef5"}, "dfce5db4aa42b7eb": {"kind":"union","types":["871bfd6f7bb91061","b57a2889408de36e","c8e6f48878cc2a2f"]}, "e0a787e6ec76c7c9": {"kind":"object","properties":[{"name":"data","type":"ef11a3b7fa2033ae","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"c219efbdfd53b836","optional":false}],"indices":[]}, + "e1880c67e735e228": {"kind":"object","properties":[{"name":"inserted","type":"690583582246babf","optional":false},{"name":"outcome","type":"d4e4d575abeb4b72","optional":true},{"name":"removedCount","type":"0657d3ca5ac4e7bf","optional":true},{"name":"start","type":"0657d3ca5ac4e7bf","optional":false},{"name":"target","type":"96f4a9c81fc0f940","optional":false}],"indices":[]}, + "e272493e3ea0b33b": {"kind":"union","types":["01c161379a3c3394","09f3f8dc417f2782","4b259f7f8f0a44ad","613660455704fb82","fa87537f4a9c1e25"]}, "e2ad8f5bcd813f26": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":false},{"name":"mode","type":"e5d3828df1ec3e2a","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "e2d0367e5716bc18": {"kind":"literal","value":"compaction/start"}, "e2f9a41e0989f54e": {"kind":"object","properties":[{"name":"data","type":"9947aa5938fe19a8","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"ef4f00923b9edbae","optional":false}],"indices":[]}, @@ -1320,7 +1332,6 @@ "fe1a7acdeed4d0f5": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "fe792a6cd4304945": {"kind":"literal","value":"tool-workflow/run-end"}, "fec5442b9ee4122e": {"kind":"object","properties":[{"name":"cacheReadTokens","type":"0657d3ca5ac4e7bf","optional":true},{"name":"cacheWriteTokens","type":"0657d3ca5ac4e7bf","optional":true},{"name":"inputTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"outputTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"reasoningTokens","type":"0657d3ca5ac4e7bf","optional":true},{"name":"totalTokens","type":"0657d3ca5ac4e7bf","optional":true}],"indices":[]}, - "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"}, - "ff2cbb53582d1827": {"kind":"array","element":"c78b9097bfae83cd"} + "fee1caf8ab6a65c1": {"kind":"literal","value":"instructions"} } } diff --git a/docs/subsystems/README.i18n.yaml b/docs/subsystems/README.i18n.yaml index 069f78cc33..9bd04642b1 100644 --- a/docs/subsystems/README.i18n.yaml +++ b/docs/subsystems/README.i18n.yaml @@ -3,5 +3,5 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/README.md /subsystems: - en: 81b2c48d922de5a9 - zh: cf0db50b34d2feb3 + en: e95b837b8f47eac8 + zh: bd69de97c80fe2ae diff --git a/docs/subsystems/README.md b/docs/subsystems/README.md index 86e30a5519..7d66caa4dd 100644 --- a/docs/subsystems/README.md +++ b/docs/subsystems/README.md @@ -51,7 +51,7 @@ One page per subsystem of the DeepSeek Harness: what it is, the data structures | [subagent.md](subagent.md) | the subagent seam: the named-provider registry, `SubagentStartRequest`/`Result`/`Run`, the start-time-vs-runtime capability split | | [voice-input.md](voice-input.md) | experimental named recognizers, transient audio and revision-guarded draft insertion | | [translation.md](translation.md) | experimental anonymous text translation and explicit provider requests | -| [agent-team.md](agent-team.md) | Agent Teams: implicit Lead identity, named continuable teammates, direct peer inbox delivery, and shared task DAG | +| [agent-team.md](agent-team.md) | Agent Teams: shared task DAG and task ownership for a subagent tree | | [liveshare.md](liveshare.md) | the opt-in LiveShare bundle: nested share modes, a fork's ceiling and durability, enforcement installation, and the constraint a shared Session's externally driven turns run under | | [claude-code-mods.md](claude-code-mods.md) | Claude Code mods through the experimental bridge: every event, `$` member, chain rule, drawing feature, and example mod that differs from Claude Code | | [web.md](web.md) | the web access seam: `WebSearchRequest`/`Result`, `WebFetchRequest`/`Result`, `WebFetchBody`, provider availability, `WebError` | diff --git a/docs/subsystems/README.zh.md b/docs/subsystems/README.zh.md index 289a6a71f3..7358fe0203 100644 --- a/docs/subsystems/README.zh.md +++ b/docs/subsystems/README.zh.md @@ -51,7 +51,7 @@ | [subagent.md](subagent.zh.md) | subagent seam:命名提供方注册表、`SubagentStartRequest`/`Result`/`Run`、启动时与运行时能力拆分 | | [voice-input.md](voice-input.zh.md) | 实验性具名语音识别、临时音频和受版本保护的草稿插入 | | [translation.md](translation.zh.md) | 实验性免登录文本翻译与显式 Provider 请求 | -| [agent-team.md](agent-team.zh.md) | Agent Teams:隐式 Lead 身份、具名 continuable teammate、直接 peer inbox 投递 与共享任务 DAG | +| [agent-team.md](agent-team.zh.md) | Agent Teams:子代理树共享的任务 DAG 与任务归属 | | [liveshare.md](liveshare.zh.md) | 可选的 LiveShare bundle:嵌套分享模式、fork 的上限与持久性、上限安装,以及共享会话外部驱动轮次所受的约束 | | [claude-code-mods.md](claude-code-mods.zh.md) | 经实验性桥接运行的 Claude Code 模组:与 Claude Code 不同的每个事件、`$` 成员、链规则、绘制特性与示例模组 | | [web.md](web.zh.md) | Web 访问 seam:`WebSearchRequest`/`Result`、`WebFetchRequest`/`Result`、`WebFetchBody`、提供方可用性、`WebError` | diff --git a/docs/subsystems/agent-team.i18n.yaml b/docs/subsystems/agent-team.i18n.yaml index a4c599562f..435e1b6bbb 100644 --- a/docs/subsystems/agent-team.i18n.yaml +++ b/docs/subsystems/agent-team.i18n.yaml @@ -3,20 +3,20 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/agent-team.md /agent-teams: - en: f571e223220bb616 - zh: dd7e37fdf359eeae -/agent-teams/identity-and-roster: - en: df72d9409b89714d - zh: 982934dd18864ca2 + en: 152195aeb3b5dea1 + zh: 1cf6b3b36bd6f02c +/agent-teams/identity-and-historical-roster: + en: 3a574287e378ecf9 + zh: 818667289271c1af /agent-teams/messages-and-historical-mailbox: - en: 2aed7dd369f47747 - zh: 4f080e50c584ad37 + en: e50b723dfffd6758 + zh: 6e4d5891b5d913fc /agent-teams/shared-task-dag: - en: 4515005d07e4d2a3 - zh: 26811b31f69009d6 + en: c70f0fd199fc7db5 + zh: c6b77cb5a5cfd1c2 /agent-teams/web-projection: - en: 6af99eff8036597a - zh: f172f994e01f12c1 + en: 059d4e5d6a9ddc71 + zh: cb3fd92096144e19 /agent-teams/replay: - en: fe32f71c6d799ebc - zh: aa2b6ccddba8cfd5 + en: 448d32856f87b067 + zh: 7fafd96314c7e2c5 diff --git a/docs/subsystems/agent-team.md b/docs/subsystems/agent-team.md index c5c6a0f775..49b27ea176 100644 --- a/docs/subsystems/agent-team.md +++ b/docs/subsystems/agent-team.md @@ -2,14 +2,14 @@ English | [中文](agent-team.zh.md) -Types shared by the experimental implicit-root Team domain, model tools, and host adapters. The [Agent Teams Agent Note](../../.agents/notes/implemented/feature/2026-08-05-agent-teams.md) owns identity, mailbox, task, and shared-checkout decisions; this page records the durable and client-visible forms from [`packages/experimental/agent-team/src/types.ts`](../../packages/experimental/agent-team/src/types.ts). +Types shared by the shared task board, model tools, and host adapters. The [task-board wait decision](../../.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.md) owns coordination semantics; this page records durable and client-visible forms from [`packages/team/agent-team/src/types.ts`](../../packages/team/agent-team/src/types.ts). -## Identity and roster +## Identity and historical roster -`TeamId` is the root `SessionId` under a distinct [brand](core.md#branded-ids). `TeamTaskId` is allocated as `task-`. New sends return the target inbox `MessageId`; `TeamMessageId` is retained only for historical mailbox records. Teammate names are immutable labels. +`TeamId` brands the root `SessionId`; `TeamTaskId` uses `task-`. `TeamMessageId` and roster records remain for historical decoding. The subagent runtime resolves the tree and discovers eligible task owners at arbitrary depth; historical roster entries grant no authority. ```ts type-equiv -/** Whole durable value written on every teammate lifecycle change. */ +/** Historical roster value written by earlier Team builds on every teammate lifecycle change. */ interface TeamMemberSnapshot { readonly id: SessionId readonly name: string @@ -21,11 +21,11 @@ interface TeamMemberSnapshot { } ``` -Every member starts in `provisioning` and reaches exactly one terminal roster phase, `active` or `failed`. Roster `running`/`inactive` status is derived separately and never rewrites this record. +Historical records retain their recorded `provisioning`, `active`, or `failed` phase. Current turn activity belongs to ordinary subagent discovery and Session status, independently of task completion. ## Messages and historical mailbox -New sends return inbox acceptance or reject. The target stores the existing `agent-message` source with the real sender Session id and a sender-name content prefix. Team has no new-message outbox or resend deduplication. The [package contract](../../packages/experimental/agent-team/README.md#understand-the-implementation) defines persistence. The following mailbox types remain readable so historical Lead logs still replay; Team does not deliver their pending records. +Members exchange ordinary [subagent messages](subagent.md), retaining the real sender Session id. Task changes do not end inbox waits, add inbox messages, or start idle agents. Send an explicit message when an agent needs to act on a task update. The following historical mailbox types remain readable; Team never delivers their pending records. ```ts type-equiv /** One peer message recorded by the historical Team mailbox. */ @@ -38,8 +38,6 @@ interface TeamMessageSnapshot { } ``` -Every message attempts Steer delivery. A running target receives it at the nearest step boundary; an inactive target starts a turn if loaded or cold-resumes otherwise. Scheduling is not stored in the durable record because callers cannot select another mode. - Historical `team-message` sources retain the old message id and sender attribution; the client uses them for the message title and icon. ```ts type-equiv @@ -71,25 +69,15 @@ interface TeamTaskSnapshot { } ``` -`pending` is unstarted or released, `in_progress` carries an owner, `completed` satisfies blockers, and `deleted` is a retained tombstone. Views add owner name, readiness, and write-scope overlap warnings without changing the durable snapshot. +`pending` is unstarted or released, `in_progress` carries an owner, `completed` satisfies blockers, and `deleted` is a retained tombstone. Views expose `ownerId`, readiness, and advisory write-scope overlap without changing the durable snapshot. ## Web projection -The Lead Session publishes `SessionProjectionMap.agentTeam` with durable roster rows and non-deleted task views. `failure` reports a rejected persisted record beside the last valid state. Member activity comes from Session status; model labels come from each member's `modelSelection` projection. +`agentTeam.enabled` exposes the root Session’s saved selection. New Sessions default to false; `team/mode` records explicit selections. Historical tasks imply enabled until an explicit selection. Only the root can call `setEnabled`; descendants share that mode. The Web menu calls the same method through `remote.agentTeams.setEnabled`, with the root Session id resolved to its live Agent by the Gateway. Mode writes take effect before awaiting persistence. Tools resolve availability at step preparation; prompt providers read the selection when evaluated. Task mutations check the current mode when their queued operation starts; admitted mutations may finish. Mode changes do not end inbox waits. A failed flush leaves the appended selection active; retrying the same selection flushes it without a duplicate event. -```ts type-equiv -/** One durable roster row published through the `agentTeam` Session projection. */ -interface TeamMemberProjection { - readonly id: SessionId - readonly name: string - readonly role: 'lead' | 'teammate' - /** Durable lifecycle; the Lead row is always `active`. Turn activity comes from Session status. */ - readonly phase: TeamMemberPhase - readonly error?: string -} -``` +The root Session publishes non-deleted task views through `SessionProjectionMap.agentTeam`. `failure` reports a rejected persisted task or mode record beside the last valid state. Historical roster and mailbox records are not projected. The task panel identifies every owner by its Session id. ```ts type-equiv /** Runtime-enriched task view returned to tools and hosts. */ @@ -101,7 +89,7 @@ interface TeamTaskView { readonly status: TeamTaskStatus readonly blockedBy: TeamTaskId[] readonly writeScopes: string[] - readonly ownerName?: string + readonly ownerId?: SessionId readonly ready: boolean readonly writeScopeWarnings: string[] } @@ -111,10 +99,10 @@ interface TeamTaskView { /** * Durable Team state published to browser clients through the Lead Session's * `agentTeam` projection. `failure` names the first rejected persisted Team - * record; members and tasks then stay at the last valid state. + * record; tasks then stay at the last valid state. */ interface TeamProjection { - readonly members: TeamMemberProjection[] + readonly enabled: boolean readonly tasks: TeamTaskView[] readonly failure?: string } @@ -122,7 +110,7 @@ interface TeamProjection { ## Replay -The `agentTeam` Session projection replays one root Session into the roster, task board, and historical queued-minus-delivered mailbox. It selects records by `TeamId`, so events inherited by an ordinary fork retain the ancestor id and never enter the new root's state. Session event `seq` and `time` remain the ordering and timing record; Team snapshots do not duplicate them. Roster and task reads reach callers as views; pending mail is not exposed to callers. The package [README](../../packages/experimental/agent-team/README.md) owns operation, authorization, recovery, and limit behavior. +The `agentTeam` projection replays task records selected by `TeamId` and the Session’s own mode selections. Subagent discovery owns current tree membership and ignores inherited catalog authority. Session event `seq` and `time` own ordering and timing. Committed durable generations are preserved. The [package README](../../packages/team/agent-team/README.md) defines task operations and limits. @@ -140,42 +128,35 @@ Agent Teams service backed by the exact live Lead Session log. ```ts cordis-catalog /** - * Resolve one exact live Agent's Team role. - * @param agent - exact live Agent used as the authority credential. - * @returns its root, Team identity, role, and model-facing name. + * Read the Team selection shared by the caller's subagent tree. + * @param caller - exact live root or descendant. + * @returns whether Team tools and guidance are enabled. */ -membership(agent: Agent): TeamMembership +isEnabled(caller: Agent): boolean /** - * List the runtime-enriched roster visible to one Team member. - * @param agent - exact live Team member. - * @returns Lead and teammate rows in creation order. + * Save a root Session's Team selection without stopping children or deleting tasks. + * The selection takes effect before awaiting persistence. Tools resolve availability at + * step preparation; prompt providers read the selection when evaluated. Task mutations + * check the current mode when their queued operation starts; admitted operations finish. + * @param agent - exact live root whose tree receives the selection. + * @param enabled - selected Team mode. + * @param signal - cancellation checked before changing the selection. + * @returns fulfillment after the selection flushes. + * @throws when called by a descendant or persistence fails. An appended selection remains active; + * retrying the same selection flushes without a duplicate event. */ -listMembers(agent: Agent): TeamMemberView[] - -/** - * Create one named, continuable direct child of the Team Lead. - * @param caller - exact live Lead Agent. - * @param request - immutable name, description, prompt, context mode, provider, and cancellation. - * @returns the active roster row. - */ -async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise - -/** - * Steer one peer message into the target inbox or reject the attempt. - * @param caller - exact live sending Team member. - * @param request - target name, content, and cancellation before acceptance. - * @returns accepted inbox identity; acceptance follows normal Agent persistence and does not await model processing. - */ -async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise +@Remote async setEnabled(agent: Agent, enabled: boolean, signal?: AbortSignal): Promise /** * Create one unowned pending task in the Team Lead log. * @param caller - exact live Team member creating the task. * @param request - task text, blockers, and advisory write scopes. + * @param signal - cancellation before the task event is appended; omitted means no cancellation. * @returns the revision-one task view. + * @throws TEAM_TASK_PERSISTENCE_UNCONFIRMED when the task is visible but durability is unknown; read it before retrying. */ -async createTask(caller: Agent, request: CreateTeamTaskRequest): Promise +async createTask(caller: Agent, request: CreateTeamTaskRequest, signal?: AbortSignal): Promise /** * Return one task, including a deleted tombstone. @@ -196,36 +177,14 @@ listTasks(caller: Agent): TeamTaskView[] * Compare-and-set one authorized task transition. * @param caller - exact live Team member authorizing the mutation. * @param request - task identity, expected revision, action, and action fields. + * @param signal - cancellation before the task event is appended; omitted means no cancellation. * @returns the committed next task revision. + * @throws TEAM_TASK_PERSISTENCE_UNCONFIRMED when the task is visible but durability is unknown; read it before retrying. */ -async updateTask(caller: Agent, request: UpdateTeamTaskRequest): Promise - -/** - * Wait for the next Team-domain or member-status change. - * @param caller - exact live Team member waiting for activity. - * @param timeoutMs - bounded wait duration from ten seconds through one hour. - * @param signal - caller cancellation for the wait only. - * @returns one observed change or a timeout result. - */ -async waitForChange(caller: Agent, timeoutMs: number, signal: AbortSignal): Promise - -/** - * Interrupt one live teammate turn without clearing its pending inbox. - * @param caller - exact live Lead Agent. - * @param targetName - durable teammate name. - * @returns the target status sampled before cancellation. - */ -interrupt(caller: Agent, targetName: string): { previousStatus: 'running' | 'inactive' } - -/** - * Resolve a caller without throwing, used by scoped-tool installation and observers. - * @param agent - candidate exact live Agent. - * @returns Team membership, or undefined for non-Team subagents and stale identities. - */ -tryMembership(agent: Agent): TeamMembership | undefined +async updateTask(caller: Agent, request: UpdateTeamTaskRequest, signal?: AbortSignal): Promise ``` Types: [Agent](core.md) -Source: [`packages/experimental/agent-team/src/index.ts`](../../packages/experimental/agent-team/src/index.ts) +Source: [`packages/team/agent-team/src/index.ts`](../../packages/team/agent-team/src/index.ts) diff --git a/docs/subsystems/agent-team.zh.md b/docs/subsystems/agent-team.zh.md index 2e3c0b040e..fb52d49be4 100644 --- a/docs/subsystems/agent-team.zh.md +++ b/docs/subsystems/agent-team.zh.md @@ -2,14 +2,14 @@ [English](agent-team.md) | 中文 -实验性隐式 Root Team 领域、模型工具与宿主适配器共享的类型。[Agent Teams Agent Note](../../.agents/notes/implemented/feature/2026-08-05-agent-teams.zh.md)负责身份、mailbox、task 与共享 checkout 决策;本页记录 [`packages/experimental/agent-team/src/types.ts`](../../packages/experimental/agent-team/src/types.ts) 中的持久与客户端可见形式。 +共享任务板、模型工具和 host 适配器共享的类型。[任务板等待决策](../../.agents/notes/implemented/architecture/2026-10-19-team-task-board-inbox.zh.md)负责协调语义;本页记录 [`packages/team/agent-team/src/types.ts`](../../packages/team/agent-team/src/types.ts) 中的持久化和客户端可见形式。 -## 身份与 roster +## 身份与历史名册 -`TeamId` 是使用独立[品牌类型](core.zh.md#branded-ids)的 root `SessionId`。`TeamTaskId` 按 `task-` 分配。新发送返回目标 inbox 的 `MessageId`;`TeamMessageId` 仅供历史 mailbox 记录保留。teammate 名称是不可变标签。 +`TeamId` 品牌化根 `SessionId`;`TeamTaskId` 使用 `task-`。`TeamMessageId` 和名册记录为历史解码保留。subagent 运行时解析树,并发现任意深度的有效任务所有者;历史名册条目不授予权限。 ```ts type-equiv -/** Whole durable value written on every teammate lifecycle change. */ +/** Historical roster value written by earlier Team builds on every teammate lifecycle change. */ interface TeamMemberSnapshot { readonly id: SessionId readonly name: string @@ -21,11 +21,11 @@ interface TeamMemberSnapshot { } ``` -每个 member 都从 `provisioning` 开始,并且只到达一个终态 roster phase:`active` 或 `failed`。roster 的 `running`/`inactive` 状态单独派生,绝不会重写该记录。 +历史记录保留其记录的 `provisioning`、`active` 或 `failed` 阶段。当前轮次活动属于普通 subagent 发现和 Session 状态,与任务完成相互独立。 ## 消息与历史 mailbox -新发送返回 inbox 接收结果或拒绝。目标保存现有 `agent-message` source,包含真实发送者 Session id 和发送者名称正文前缀。Team 不为新消息提供 outbox 或重发去重。[包约定](../../packages/experimental/agent-team/README.zh.md#understand-the-implementation)定义持久化。以下 mailbox 类型继续可读,以便历史 Lead 日志仍能回放;Team 不投递其中的 pending 记录。 +成员交换普通 [subagent 消息](subagent.zh.md),保留真实发送方 Session id。任务变更不会结束收件箱等待、添加收件箱消息或启动空闲 agent。需要 agent 处理任务更新时,发送明确消息。下列历史邮箱类型保持可读;Team 绝不投递其待处理记录。 ```ts type-equiv /** One peer message recorded by the historical Team mailbox. */ @@ -38,8 +38,6 @@ interface TeamMessageSnapshot { } ``` -每条消息都会尝试 Steer 投递。running target 在最近的步骤边界收到消息,inactive target 在已加载时启动一个轮次,否则冷恢复。调用方不能选择其他模式,因此持久记录不存储调度方式。 - 历史 `team-message` source 保留旧消息 id 与发送者归属;客户端用它们展示消息标题和图标。 ```ts type-equiv @@ -71,25 +69,15 @@ interface TeamTaskSnapshot { } ``` -`pending` 表示尚未开始或已经释放,`in_progress` 携带 owner,`completed` 满足 blocker,`deleted` 是保留的 tombstone。view 会添加 owner name、readiness 和 write-scope 重叠警告,但不会改变持久快照。 +`pending` 表示未开始或已释放,`in_progress` 携带负责人,`completed` 满足依赖,`deleted` 是保留的墓碑记录。视图提供 `ownerId`、就绪性和写入范围重叠提示,不改变持久快照。 ## Web 投影 -Lead Session 通过 `SessionProjectionMap.agentTeam` 发布持久 roster 行与未删除任务视图。`failure` 在最后有效状态旁报告被拒绝的持久记录。成员活动来自 Session 状态;模型标签来自各成员的 `modelSelection` 投影。 +`agentTeam.enabled` 提供根 Session 保存的选择。新 Session 默认为 false;`team/mode` 记录显式选择。历史任务在显式选择前视为开启。仅根可调用 `setEnabled`;后代共享该模式。Web 菜单通过 `remote.agentTeams.setEnabled` 调用同一方法,Gateway 将根 Session id 解析为其存活 Agent。模式写入先立即生效,再等待刷盘。工具在步骤准备时确定可用性;提示词提供方在求值时读取选择。任务修改在排队操作开始时检查当前模式;已获准的修改可继续完成。模式变更不会结束收件箱等待。刷盘失败时已追加的选择仍然生效;重试相同选择会再次刷盘,不重复追加事件。 -```ts type-equiv -/** One durable roster row published through the `agentTeam` Session projection. */ -interface TeamMemberProjection { - readonly id: SessionId - readonly name: string - readonly role: 'lead' | 'teammate' - /** Durable lifecycle; the Lead row is always `active`. Turn activity comes from Session status. */ - readonly phase: TeamMemberPhase - readonly error?: string -} -``` +根 Session 通过 `SessionProjectionMap.agentTeam` 发布未删除任务视图。`failure` 在最后有效状态旁报告被拒绝的持久化任务或模式记录。历史名册与邮箱记录不参与投影。任务面板以 Session id 标识每个负责人。 ```ts type-equiv /** Runtime-enriched task view returned to tools and hosts. */ @@ -101,7 +89,7 @@ interface TeamTaskView { readonly status: TeamTaskStatus readonly blockedBy: TeamTaskId[] readonly writeScopes: string[] - readonly ownerName?: string + readonly ownerId?: SessionId readonly ready: boolean readonly writeScopeWarnings: string[] } @@ -111,10 +99,10 @@ interface TeamTaskView { /** * Durable Team state published to browser clients through the Lead Session's * `agentTeam` projection. `failure` names the first rejected persisted Team - * record; members and tasks then stay at the last valid state. + * record; tasks then stay at the last valid state. */ interface TeamProjection { - readonly members: TeamMemberProjection[] + readonly enabled: boolean readonly tasks: TeamTaskView[] readonly failure?: string } @@ -122,7 +110,7 @@ interface TeamProjection { ## 回放 -`agentTeam` Session 投影把一个 Root Session 回放成roster、任务板与历史 queued-minus-delivered mailbox。它按 `TeamId` 选取记录,因此普通 fork 继承的 event 保留 ancestor id,绝不会进入新 Root 的状态。Session event 的 `seq` 与 `time` 继续负责顺序和时间记录,Team snapshot 不再重复保存它们。roster 与 task 读取以 view 形式到达调用方,而 pending 邮件不对调用方公开。包 [README](../../packages/experimental/agent-team/README.zh.md)负责 operation、authorization、recovery 和限制行为。 +`agentTeam` 投影按 `TeamId` 重放任务记录,并重放 Session 自身的模式选择。subagent 发现负责当前树成员关系,不将继承目录作为权限来源。Session 事件的 `seq` 和 `time` 负责排序和时间。已提交的持久化代次保持不变。[包 README](../../packages/team/agent-team/README.zh.md)定义任务操作和限制。 @@ -140,42 +128,35 @@ Agent Teams service backed by the exact live Lead Session log. ```ts cordis-catalog /** - * Resolve one exact live Agent's Team role. - * @param agent - exact live Agent used as the authority credential. - * @returns its root, Team identity, role, and model-facing name. + * Read the Team selection shared by the caller's subagent tree. + * @param caller - exact live root or descendant. + * @returns whether Team tools and guidance are enabled. */ -membership(agent: Agent): TeamMembership +isEnabled(caller: Agent): boolean /** - * List the runtime-enriched roster visible to one Team member. - * @param agent - exact live Team member. - * @returns Lead and teammate rows in creation order. + * Save a root Session's Team selection without stopping children or deleting tasks. + * The selection takes effect before awaiting persistence. Tools resolve availability at + * step preparation; prompt providers read the selection when evaluated. Task mutations + * check the current mode when their queued operation starts; admitted operations finish. + * @param agent - exact live root whose tree receives the selection. + * @param enabled - selected Team mode. + * @param signal - cancellation checked before changing the selection. + * @returns fulfillment after the selection flushes. + * @throws when called by a descendant or persistence fails. An appended selection remains active; + * retrying the same selection flushes without a duplicate event. */ -listMembers(agent: Agent): TeamMemberView[] - -/** - * Create one named, continuable direct child of the Team Lead. - * @param caller - exact live Lead Agent. - * @param request - immutable name, description, prompt, context mode, provider, and cancellation. - * @returns the active roster row. - */ -async spawnTeammate(caller: Agent, request: SpawnTeammateRequest): Promise - -/** - * Steer one peer message into the target inbox or reject the attempt. - * @param caller - exact live sending Team member. - * @param request - target name, content, and cancellation before acceptance. - * @returns accepted inbox identity; acceptance follows normal Agent persistence and does not await model processing. - */ -async sendMessage(caller: Agent, request: SendTeamMessageRequest): Promise +@Remote async setEnabled(agent: Agent, enabled: boolean, signal?: AbortSignal): Promise /** * Create one unowned pending task in the Team Lead log. * @param caller - exact live Team member creating the task. * @param request - task text, blockers, and advisory write scopes. + * @param signal - cancellation before the task event is appended; omitted means no cancellation. * @returns the revision-one task view. + * @throws TEAM_TASK_PERSISTENCE_UNCONFIRMED when the task is visible but durability is unknown; read it before retrying. */ -async createTask(caller: Agent, request: CreateTeamTaskRequest): Promise +async createTask(caller: Agent, request: CreateTeamTaskRequest, signal?: AbortSignal): Promise /** * Return one task, including a deleted tombstone. @@ -196,36 +177,14 @@ listTasks(caller: Agent): TeamTaskView[] * Compare-and-set one authorized task transition. * @param caller - exact live Team member authorizing the mutation. * @param request - task identity, expected revision, action, and action fields. + * @param signal - cancellation before the task event is appended; omitted means no cancellation. * @returns the committed next task revision. + * @throws TEAM_TASK_PERSISTENCE_UNCONFIRMED when the task is visible but durability is unknown; read it before retrying. */ -async updateTask(caller: Agent, request: UpdateTeamTaskRequest): Promise - -/** - * Wait for the next Team-domain or member-status change. - * @param caller - exact live Team member waiting for activity. - * @param timeoutMs - bounded wait duration from ten seconds through one hour. - * @param signal - caller cancellation for the wait only. - * @returns one observed change or a timeout result. - */ -async waitForChange(caller: Agent, timeoutMs: number, signal: AbortSignal): Promise - -/** - * Interrupt one live teammate turn without clearing its pending inbox. - * @param caller - exact live Lead Agent. - * @param targetName - durable teammate name. - * @returns the target status sampled before cancellation. - */ -interrupt(caller: Agent, targetName: string): { previousStatus: 'running' | 'inactive' } - -/** - * Resolve a caller without throwing, used by scoped-tool installation and observers. - * @param agent - candidate exact live Agent. - * @returns Team membership, or undefined for non-Team subagents and stale identities. - */ -tryMembership(agent: Agent): TeamMembership | undefined +async updateTask(caller: Agent, request: UpdateTeamTaskRequest, signal?: AbortSignal): Promise ``` Types: [Agent](core.zh.md) -Source: [`packages/experimental/agent-team/src/index.ts`](../../packages/experimental/agent-team/src/index.ts) +Source: [`packages/team/agent-team/src/index.ts`](../../packages/team/agent-team/src/index.ts) diff --git a/docs/subsystems/boot.md b/docs/subsystems/boot.md index 48b9b179e0..7e72c394f3 100644 --- a/docs/subsystems/boot.md +++ b/docs/subsystems/boot.md @@ -116,6 +116,49 @@ Types: [Agent](core.md) · [Session](session.md) · [ToolCallId](core.md) Source: [`packages/experimental/action-cards/src/index.ts`](../../packages/experimental/action-cards/src/index.ts) + + +### `ctx.cliAccounts` — `CliAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the bundle package, the account source, the page operations, and the presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the package. + */ +register(registration: CliAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param packageName - the account's bundle package. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown package or operation, while another operation runs, or after the account's disposal. + */ +@Remote start(packageName: string, operation: string): CliOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param packageName - the account's bundle package. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown package. + */ +@Remote cancel(packageName: string, id: CliOperationId): Promise +``` + +Source: [`packages/client/ui-cli-account/src/index.ts`](../../packages/client/ui-cli-account/src/index.ts) + ### `ctx.configEditor` — `ConfigEditor` diff --git a/docs/subsystems/boot.zh.md b/docs/subsystems/boot.zh.md index d80c05fb53..2151e59f5e 100644 --- a/docs/subsystems/boot.zh.md +++ b/docs/subsystems/boot.zh.md @@ -116,6 +116,49 @@ Types: [Agent](core.zh.md) · [Session](session.zh.md) · [ToolCallId](core.zh.m Source: [`packages/experimental/action-cards/src/index.ts`](../../packages/experimental/action-cards/src/index.ts) + + +### `ctx.cliAccounts` — `CliAccounts` + +Holds the registered accounts and serves them to the Plugins page. + +```ts cordis-catalog +/** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the bundle package, the account source, the page operations, and the presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the package. + */ +register(registration: CliAccountRegistration): () => void + +/** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ +@Remote({ mode: 'stream' }) async *watch(signal: AbortSignal): AsyncIterable + +/** + * Start one of the operations the account registered as page actions. + * @param packageName - the account's bundle package. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown package or operation, while another operation runs, or after the account's disposal. + */ +@Remote start(packageName: string, operation: string): CliOperationId + +/** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param packageName - the account's bundle package. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown package. + */ +@Remote cancel(packageName: string, id: CliOperationId): Promise +``` + +Source: [`packages/client/ui-cli-account/src/index.ts`](../../packages/client/ui-cli-account/src/index.ts) + ### `ctx.configEditor` — `ConfigEditor` diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index 54d4801a17..dbf1b7ddc3 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/computer-use.md /computer-use: - en: e78e111e0debc21b - zh: 0d218fa34c63cc32 + en: 38cfa2a698be898f + zh: 60961256fee5ef21 /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index 957990b09c..08888a044c 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -14,7 +14,7 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys |---|---| | `CuaApplicationId`, `CuaApplicationGrant` | A platform-provided application identity and its displayed saved decision. | | `CuaSystemPermission` | Accessibility or Screen Recording, selected by the human. | -| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native privilege checks, observed helper/parent processes, and the application identified by macOS process responsibility at helper startup. Application metadata is absent if the optional system query or application lookup is unavailable. | +| `CuaPermissionProcess`, `CuaSystemPermissionState` | Native privilege checks, observed helper/parent processes, and the application identified by macOS process responsibility at helper startup. The independent helper uses its own bundle when system attribution is unavailable; application metadata is absent if neither bundle can be identified. | | `CuaApplicationState` | Saved grants, refused applications, and whether persistence is available. Session-only grants remain internal to the provider. System observations and application icons are queried separately so the page can display each result as it arrives. | ## Choose a provider @@ -103,18 +103,20 @@ Browser controls for provider-owned native permission and application decisions. @Remote async applicationIcons(): Promise> /** - * Request a system privilege explicitly selected by the user. + * Request the selected system privilege through the native provider. * @param permission macOS privilege to request. - * @returns Preflight state after requesting; a false value never implies consent. + * @param locale Current Client language for provider-owned permission UI. + * @returns Current permission observations; requesting does not establish consent. */ -@Remote async requestPermission(permission: CuaSystemPermission): Promise +@Remote async requestPermission(permission: CuaSystemPermission, locale: string): Promise /** * Open the macOS privacy pane selected by the user. * @param permission Corresponding system privilege. + * @param locale Current Client language for provider-owned recovery instructions. * @returns Completion after macOS accepted the open request. */ -@Remote async openSettings(permission: CuaSystemPermission): Promise +@Remote async openSettings(permission: CuaSystemPermission, locale: string): Promise /** * Remove saved and session access and join affected operations. diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 30d6f91ae1..28fdc9b794 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -14,7 +14,7 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 |---|---| | `CuaApplicationId`、`CuaApplicationGrant` | 平台提供的应用身份,以及显示给用户的已保存决定。 | | `CuaSystemPermission` | 用户选择申请的辅助功能或屏幕录制权限。 | -| `CuaPermissionProcess`、`CuaSystemPermissionState` | 观测到的 helper、父进程和原生权限状态,以及 helper 启动时由 macOS 责任进程记录识别出的应用。可选系统查询或应用查找不可用时,省略应用信息。 | +| `CuaPermissionProcess`、`CuaSystemPermissionState` | 观测到的 helper、父进程和原生权限状态,以及 helper 启动时由 macOS 责任进程记录识别出的应用。系统归属信息不可用时,独立 helper 使用自身 bundle;两者都无法识别时才省略应用信息。 | | `CuaApplicationState` | 持久授权、拒绝记录,以及能否持久保存。会话授权只保留在 provider 内部。系统权限和应用图标分别查询,页面在各项结果返回后分别显示。 | ## 选择提供方 @@ -103,18 +103,20 @@ Browser controls for provider-owned native permission and application decisions. @Remote async applicationIcons(): Promise> /** - * Request a system privilege explicitly selected by the user. + * Request the selected system privilege through the native provider. * @param permission macOS privilege to request. - * @returns Preflight state after requesting; a false value never implies consent. + * @param locale Current Client language for provider-owned permission UI. + * @returns Current permission observations; requesting does not establish consent. */ -@Remote async requestPermission(permission: CuaSystemPermission): Promise +@Remote async requestPermission(permission: CuaSystemPermission, locale: string): Promise /** * Open the macOS privacy pane selected by the user. * @param permission Corresponding system privilege. + * @param locale Current Client language for provider-owned recovery instructions. * @returns Completion after macOS accepted the open request. */ -@Remote async openSettings(permission: CuaSystemPermission): Promise +@Remote async openSettings(permission: CuaSystemPermission, locale: string): Promise /** * Remove saved and session access and join affected operations. diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index a2b168f3fd..363584a5fd 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -9,8 +9,8 @@ en: c90cb23528ddb6c8 zh: 62724b7255b586b6 /core/creation-and-ownership: - en: e516e14228c6bd35 - zh: dba25d7da1d5a44e + en: d71c669c1a36bf52 + zh: 9b335f90c84a894e /core/the-agent-handle: en: 6ee15fec81bc0686 zh: b6f3fcd48823ea75 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 48ff2ce633..40264ec898 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -46,9 +46,9 @@ interface AgentHandle { } ``` -`CreateAgentOptions` carries the shared identity and everything a fresh agent needs before publication: an optional live `parentAgent`, session metadata (`meta` — validated `cwd`, fork lineage, the `isSeeded` marker, origin classification, delegation depth, and `agentPreset`), the exact fork cut in sibling field `inheritedEventCount`, an optional `seed` replay prefix, per-agent `AgentOptions`, a creation-only cancellation `signal`, and `setup`. `ResumeAgentOptions` is the persisted-identity counterpart: `resumeSessionId`, `parentAgent`, `agentOptions`, `signal`, and `setup`. The `setup` callback (`AgentSetup`) receives `(agentCtx, agent)` after Session store entry and completed `session/created`, before Agent registration: the context owns scoped registrations, while the explicit Agent supplies the exact child Session without a reverse property on the Context. Everything registered through `agentCtx` exists before `agent/created` and the first prompt assembly. Setup may return a synchronous commit invoked immediately before publication; a setup rejection, commit throw, or owner disposal unwinds the transaction, removes the Session, and preserves restored pending input and already stored events. +`CreateAgentOptions` carries the shared identity and everything a fresh agent needs before publication: session metadata (`meta` — validated `cwd`, fork lineage, the `isSeeded` marker, origin classification, delegation depth, and `agentPreset`), the exact fork cut in sibling field `inheritedEventCount`, an optional `seed` replay prefix, per-agent `AgentOptions`, a creation-only cancellation `signal`, and `setup`. `ResumeAgentOptions` is the persisted-identity counterpart: `resumeSessionId`, `agentOptions`, `signal`, and `setup`. The `setup` callback (`AgentSetup`) receives `(agentCtx, agent)` after Session store entry and completed `session/created`, before Agent registration: the context owns scoped registrations, while the explicit Agent supplies the exact child Session without a reverse property on the Context. Everything registered through `agentCtx` exists before `agent/created` and the first prompt assembly. Setup may return a synchronous commit invoked immediately before publication; a setup rejection, commit throw, or owner disposal unwinds the transaction, removes the Session, and preserves restored pending input and already stored events. -`AgentFactory` is the creation interface behind the registry: the loop registers its factory via `ctx.agents.setFactory()`, so consumers use `ctx.agents` without depending on the concrete loop package. A runtime child creator sets `options.parentAgent`; the registry passes the options and caller Context to the factory without deriving one from the other. The exact `create`/`resume` signatures and rollback contracts are in the [generated section](#ctxagents--agentregistry) below. +`AgentFactory` is the creation interface behind the registry: the loop registers its factory via `ctx.agents.setFactory()`, so consumers use `ctx.agents` without depending on the concrete loop package. The registry passes creation options and the caller Context to the factory; the caller Context owns the returned handle's lifetime. The exact `create`/`resume` signatures and rollback contracts are in the [generated section](#ctxagents--agentregistry) below. ## The agent handle @@ -764,7 +764,7 @@ setFactory(factory: AgentFactory): () => void * agent): this constructs the agent and its session. Rejects if no factory is * registered or creation/setup fails. The resolved {@link AgentHandle} lets * the owner tear down exactly this agent. - * @param options - shared identity, optional live parent, session seed/metadata, and agent options. + * @param options - shared identity, session seed/metadata, and agent options. * @returns the handle after setup, rollback-covered publication, and loop start complete. */ async create(options: CreateAgentOptions): Promise @@ -773,7 +773,7 @@ async create(options: CreateAgentOptions): Promise * Load a persisted session and resume an agent on it through the registered * factory. Rejects if no factory is registered; the factory rejects if * session persistence is not configured or persistence/setup fails. - * @param options - persisted identity, optional live parent, configuration, and setup. + * @param options - persisted identity, configuration, and setup. * @returns the handle after setup, rollback-covered publication, and loop start complete. */ async resume(options: ResumeAgentOptions): Promise @@ -785,8 +785,7 @@ async resume(options: ResumeAgentOptions): Promise * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the * emits are scope-filtered regardless of which context invoked `register` * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always - * requires passing the carrier). The entry is a runtime root; factory-backed - * creation uses `options.parentAgent` for child ownership. Await the registration before using the agent. + * requires passing the carrier). Await registration before using the agent. * @param agent - the already-constructed agent to record in the store. * @returns the awaitable Cordis effect disposer (single-shot; a repeat call * returns undefined without awaiting an in-flight teardown). Exact @@ -806,15 +805,12 @@ register(agent: Agent): ReturnType * returned detach closure into its pre-installed composite teardown before * calling {@link announce}. Ordinary callers use {@link register}. * @param agent - the prepared, unpublished agent. - * @param owner - explicitly supplied live runtime owner, or - * undefined for a top-level runtime root. This is runtime ownership, not - * the resumed session's durable parent lineage. * @returns an idempotent closure that removes this exact entry and emits * `agent/disposed` with listener failures contained. When called from a * `agent/created` listener, removal and disposal wait until the serial * creation dispatch settles. */ -enter(agent: Agent, owner: Agent | undefined): () => void +enter(agent: Agent): () => void /** * Announce an agent previously inserted with {@link enter}. @@ -835,29 +831,11 @@ async announce(agent: Agent, source: SessionStartSource, signal?: AbortSignal): */ get(id: SessionId): Agent | undefined -/** - * Test whether a live agent was created through one exact parent agent's - * scoped context. Runtime ownership is independent of durable session - * lineage and remains unambiguous when unrelated providers reuse an id. - * @param id - the candidate child agent's shared agent/session id. - * @param owner - the expected runtime creator agent. - * @returns true only while the exact child entry is live under that owner. - */ -isOwnedBy(id: SessionId, owner: Agent): boolean - /** * All live agents, in registration order. * @returns a fresh array; mutating it does not affect the registry. */ list(): Agent[] - -/** - * All live top-level agents in registration order. A top-level agent was - * created without an owning agent context; durable session lineage does not - * affect this runtime relation, so a resumed fork may still be a root. - * @returns a fresh array; mutating it does not affect the registry. - */ -roots(): Agent[] ``` Types: [Session](session.md) diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 19acf51b51..ff1d3b579e 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -48,9 +48,9 @@ interface AgentHandle { } ``` -`CreateAgentOptions` 携带共享标识以及新 agent 发布前所需的一切:可选的存活 `parentAgent`、会话元数据(`meta`——已校验的 `cwd`、fork 谱系、`isSeeded` 标记、来源分类、委派深度与 `agentPreset`)、同级字段 `inheritedEventCount` 所表示的精确 fork cut、可选的 `seed` 回放前缀、按 agent 的 `AgentOptions`、仅创建期有效的取消 `signal`,以及 `setup`。`ResumeAgentOptions` 是持久标识的对应项:`resumeSessionId`、`parentAgent`、`agentOptions`、`signal` 与 `setup`。`setup` 回调(`AgentSetup`)在 Session 入库且 `session/created` 完成后、Agent 注册前接收 `(agentCtx, agent)`:上下文拥有作用域注册,显式 Agent 提供确切的子 Session,Context 无需反向属性。凡经 `agentCtx` 注册的内容都先于 `agent/created` 与第一次提示词组装存在。Setup 可以返回在发布前一刻调用的同步 commit;setup 拒绝、commit 抛出或所有者 dispose(资源释放)都会撤销事务并移除 Session,同时保留恢复出的待处理输入及已存储事件。 +`CreateAgentOptions` 携带共享标识以及新 agent 发布前所需的一切:会话元数据(`meta`——已校验的 `cwd`、fork 谱系、`isSeeded` 标记、来源分类、委派深度与 `agentPreset`)、同级字段 `inheritedEventCount` 所表示的精确 fork cut、可选的 `seed` 回放前缀、按 agent 的 `AgentOptions`、仅创建期有效的取消 `signal`,以及 `setup`。`ResumeAgentOptions` 是持久标识的对应项:`resumeSessionId`、`agentOptions`、`signal` 与 `setup`。`setup` 回调(`AgentSetup`)在 Session 入库且 `session/created` 完成后、Agent 注册前接收 `(agentCtx, agent)`:上下文拥有作用域注册,显式 Agent 提供确切的子 Session,Context 无需反向属性。凡经 `agentCtx` 注册的内容都先于 `agent/created` 与第一次提示词组装存在。Setup 可以返回在发布前一刻调用的同步 commit;setup 拒绝、commit 抛出或所有者 dispose(资源释放)都会撤销事务并移除 Session,同时保留恢复出的待处理输入及已存储事件。 -`AgentFactory` 是注册表背后的创建接口:循环经 `ctx.agents.setFactory()` 注册其工厂,因此消费方使用 `ctx.agents` 时无需依赖具体循环包。运行时子 Agent 的创建方设置 `options.parentAgent`;注册表把 options 与调用方 Context 传给工厂,不从其中一项推导另一项。确切的 `create`/`resume` 签名及回滚约定见下方[生成区块](#ctxagents--agentregistry)。 +`AgentFactory` 是注册表背后的创建接口:循环经 `ctx.agents.setFactory()` 注册其工厂,因此消费方使用 `ctx.agents` 时无需依赖具体循环包。注册表把创建选项和调用方 Context 传给工厂;调用方 Context 拥有返回句柄的生命周期。确切的 `create`/`resume` 签名及回滚约定见下方[生成区块](#ctxagents--agentregistry)。 @@ -776,7 +776,7 @@ setFactory(factory: AgentFactory): () => void * agent): this constructs the agent and its session. Rejects if no factory is * registered or creation/setup fails. The resolved {@link AgentHandle} lets * the owner tear down exactly this agent. - * @param options - shared identity, optional live parent, session seed/metadata, and agent options. + * @param options - shared identity, session seed/metadata, and agent options. * @returns the handle after setup, rollback-covered publication, and loop start complete. */ async create(options: CreateAgentOptions): Promise @@ -785,7 +785,7 @@ async create(options: CreateAgentOptions): Promise * Load a persisted session and resume an agent on it through the registered * factory. Rejects if no factory is registered; the factory rejects if * session persistence is not configured or persistence/setup fails. - * @param options - persisted identity, optional live parent, configuration, and setup. + * @param options - persisted identity, configuration, and setup. * @returns the handle after setup, rollback-covered publication, and loop start complete. */ async resume(options: ResumeAgentOptions): Promise @@ -797,8 +797,7 @@ async resume(options: ResumeAgentOptions): Promise * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the * emits are scope-filtered regardless of which context invoked `register` * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always - * requires passing the carrier). The entry is a runtime root; factory-backed - * creation uses `options.parentAgent` for child ownership. Await the registration before using the agent. + * requires passing the carrier). Await registration before using the agent. * @param agent - the already-constructed agent to record in the store. * @returns the awaitable Cordis effect disposer (single-shot; a repeat call * returns undefined without awaiting an in-flight teardown). Exact @@ -818,15 +817,12 @@ register(agent: Agent): ReturnType * returned detach closure into its pre-installed composite teardown before * calling {@link announce}. Ordinary callers use {@link register}. * @param agent - the prepared, unpublished agent. - * @param owner - explicitly supplied live runtime owner, or - * undefined for a top-level runtime root. This is runtime ownership, not - * the resumed session's durable parent lineage. * @returns an idempotent closure that removes this exact entry and emits * `agent/disposed` with listener failures contained. When called from a * `agent/created` listener, removal and disposal wait until the serial * creation dispatch settles. */ -enter(agent: Agent, owner: Agent | undefined): () => void +enter(agent: Agent): () => void /** * Announce an agent previously inserted with {@link enter}. @@ -847,29 +843,11 @@ async announce(agent: Agent, source: SessionStartSource, signal?: AbortSignal): */ get(id: SessionId): Agent | undefined -/** - * Test whether a live agent was created through one exact parent agent's - * scoped context. Runtime ownership is independent of durable session - * lineage and remains unambiguous when unrelated providers reuse an id. - * @param id - the candidate child agent's shared agent/session id. - * @param owner - the expected runtime creator agent. - * @returns true only while the exact child entry is live under that owner. - */ -isOwnedBy(id: SessionId, owner: Agent): boolean - /** * All live agents, in registration order. * @returns a fresh array; mutating it does not affect the registry. */ list(): Agent[] - -/** - * All live top-level agents in registration order. A top-level agent was - * created without an owning agent context; durable session lineage does not - * affect this runtime relation, so a resumed fork may still be a root. - * @returns a fresh array; mutating it does not affect the registry. - */ -roots(): Agent[] ``` Types: [Session](session.zh.md) diff --git a/docs/subsystems/deliverables.i18n.yaml b/docs/subsystems/deliverables.i18n.yaml index 80fd21bc38..c9ed78061e 100644 --- a/docs/subsystems/deliverables.i18n.yaml +++ b/docs/subsystems/deliverables.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/deliverables.md /deliverables: - en: a5ce6d07597594ec - zh: 72639c6033d66f41 + en: b7a2665f103d3e99 + zh: ee642ed0d3385f67 /deliverables/presentedfile-one-declared-delivery: en: bf10a8aa233c61d9 zh: fdab894f8448c843 diff --git a/docs/subsystems/deliverables.md b/docs/subsystems/deliverables.md index 3347481f3e..b1e97daa44 100644 --- a/docs/subsystems/deliverables.md +++ b/docs/subsystems/deliverables.md @@ -6,6 +6,8 @@ What a turn hands to the user, owned by the [deliverables package group](../../p Sources: [`packages/deliverables/tool-present/src/types.ts`](../../packages/deliverables/tool-present/src/types.ts), [`packages/deliverables/workspace-changes/src/types.ts`](../../packages/deliverables/workspace-changes/src/types.ts) +Patch calls use the same summary and comparison APIs. For paths outside Git coverage, a move contributes a deleted source and an added destination; a stopped commit contributes only actual net file changes. The [capture rules](../../packages/deliverables/workspace-changes/README.md#use-this-package) define path selection and observation behavior. + ## `PresentedFile` — one declared delivery ```ts type-equiv diff --git a/docs/subsystems/deliverables.zh.md b/docs/subsystems/deliverables.zh.md index d3d10565d5..396b7d8137 100644 --- a/docs/subsystems/deliverables.zh.md +++ b/docs/subsystems/deliverables.zh.md @@ -6,6 +6,8 @@ 源码:[`packages/deliverables/tool-present/src/types.ts`](../../packages/deliverables/tool-present/src/types.ts)、[`packages/deliverables/workspace-changes/src/types.ts`](../../packages/deliverables/workspace-changes/src/types.ts) +补丁调用使用相同的摘要与对比 API。对于 Git 覆盖之外的路径,移动形成源删除与目标新增;停止的提交只贡献实际文件净变化。[采集规则](../../packages/deliverables/workspace-changes/README.zh.md#use-this-package)定义路径选择与观察行为。 + ## `PresentedFile`:一条声明的交付 ```ts type-equiv diff --git a/docs/subsystems/filesystem.i18n.yaml b/docs/subsystems/filesystem.i18n.yaml index 7dd6e4531e..03d12b8456 100644 --- a/docs/subsystems/filesystem.i18n.yaml +++ b/docs/subsystems/filesystem.i18n.yaml @@ -3,17 +3,20 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/filesystem.md /filesystem: - en: 9085200a1975c5cd - zh: 48af21e513f7dc25 + en: 7f7941ec6f70a8b8 + zh: 450937984b6a8748 /filesystem/target-identity-and-metadata-provider-contract: - en: 345def8a8e6c58e0 - zh: 01d6e2f0f22daf9d + en: 1e55f1c74f0ade3f + zh: faecf389a2fb0a93 +/filesystem/patch-syntax-records: + en: 3ab3a02918d41178 + zh: 78ff80be8599ba43 /filesystem/write-and-edit-guards-provider-contract: - en: 067137c8b8181c98 - zh: 0a9c8282789d147f + en: a7c449176367a0d6 + zh: ecb49a885304db62 /filesystem/the-fs-policy-events-provider-contract-vocabulary: - en: 5dd0bdff9508350d - zh: 74d846f58fe561c9 + en: b25951ca185a890e + zh: 42a1344a2cc860a9 /filesystem/execution-context-policy-plugin: en: a23c12fc81bb4786 zh: 9dc12d18f9c97e6a @@ -21,14 +24,17 @@ en: 9315d84e53db33e9 zh: 86426ffbfa487504 /filesystem/observed-file-state-policy-plugin: - en: 93e8d93a5049b67f - zh: b50db8c745baa5fe + en: cfa56ed5d1eb2ff9 + zh: 04be764f3dc8a48c +/filesystem/patch-execution-consumer: + en: 7b462db42ab89b10 + zh: 968219ded2b55d69 /filesystem/error-taxonomy-provider-contract: - en: 0785de8395fef24f - zh: 0fc173dff1fe4658 + en: ca206569d4e2528d + zh: e36d70ad39a73570 /filesystem/no-timeouts-on-file-io: en: ae18af906f3f7e50 zh: 24a1aa6f903fe08d /filesystem/the-service-and-the-plugin: - en: 6dcd1f39906d785e - zh: e2b4b104bad31144 + en: a5e2474038c20e73 + zh: 0b8c7a9f504226b8 diff --git a/docs/subsystems/filesystem.md b/docs/subsystems/filesystem.md index d099e619b2..fcbbec29cd 100644 --- a/docs/subsystems/filesystem.md +++ b/docs/subsystems/filesystem.md @@ -2,9 +2,9 @@ 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 guards, [dsh-fs-local](../../packages/fs/fs-local) implements local disk, [dsh-fs-observation-policy](../../packages/fs/fs-observation-policy) records observed presence or absence and adds 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 optional filesystem capability composes these roles: [dsh-fs](../../packages/fs/fs) owns `ctx.fs` and guarded file mutations, [dsh-fs-local](../../packages/fs/fs-local) implements local disk, [dsh-fs-observation-policy](../../packages/fs/fs-observation-policy) records observed presence or absence and adds 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 pure [dsh-fs-patch](../../packages/fs/fs-patch/README.md) library supplies patch parsing and text application. -`dsh-fs-observation-policy` is optional. Without it, the `FileSystem` Service Definition, a provider, and the `dsh-tool-fs` Consumer form the complete, unconstrained filesystem seam: `write` unconditionally creates or overwrites, and `edit` unconditionally replaces literal text. The policy plugin changes these operations by deciding the `fs/*` waterfalls. Removing it does not break the tool because the tool calls `ctx.fs` and dispatches events; it does not call policy methods. A deployment that loads `dsh-tool-fs` is expected to also load `dsh-fs-observation-policy` so the default behavior is read-before-write/edit. +`dsh-fs-observation-policy` is optional. Without it, the `FileSystem` Service Definition, a provider, and the `dsh-tool-fs` Consumer form the complete, unconstrained filesystem seam: `write` unconditionally creates or overwrites, and `edit` unconditionally replaces literal text. The policy plugin changes these operations by deciding the `fs/*` waterfalls. Removing it does not break the tool because the tool calls `ctx.fs` and dispatches events; it does not call policy methods. The shipped compositions run without it: `dsh-base` lists the `fs-observation-policy` row `disabled: true`, and a deployment that wants read-before-write/edit sets that row to `disabled: false`. Provider source: [`packages/fs/fs/src/types.ts`](../../packages/fs/fs/src/types.ts) and [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts). Policy source: [`packages/fs/fs-observation-policy/src/types.ts`](../../packages/fs/fs-observation-policy/src/types.ts). Read-rendering source: [`packages/fs/tool-fs/src/read-render.ts`](../../packages/fs/tool-fs/src/read-render.ts). @@ -30,7 +30,7 @@ interface FsTarget { } ``` -The backend owns file-version tokens — the freshness token a write/edit guards against. The policy plugin stores them for stale checks; consumers do not interpret them. Both ids are branded opaque strings. +The backend owns file-version tokens — the freshness token a mutation guards against. The policy plugin stores them for stale checks; consumers do not interpret them. Both ids are branded opaque strings. ```ts type-equiv /** @@ -111,8 +111,114 @@ interface FsDirEntry { } ``` + +## Patch syntax records + +[dsh-fs-patch](../../packages/fs/fs-patch/README.md) parses complete patch text into serializable operations whose paths are unresolved strings, and `applyHunks` applies hunks to caller-supplied LF-normalized text, returning complete new text or a structured match failure. The package README owns the pinned parsing and matching rules. + +```ts type-equiv +/** One contiguous update. */ +interface PatchHunk { + /** One-based input line containing the marker or first implicit hunk line. */ + lineNumber: number + /** Text following `@@ `, used as a search anchor by the text matcher. */ + context?: string + /** Context and removed lines, without patch prefixes or line endings. */ + oldLines: string[] + /** Context and added lines, without patch prefixes or line endings. */ + newLines: string[] + /** Whether `*** End of File` follows this hunk. */ + isEndOfFile: boolean +} + +``` + +```ts type-equiv +/** Ordered file operation; a move is an update with a destination path. */ +type PatchOperation = + | { + kind: 'add' + path: string + lineNumber: number + /** Added lines joined with LF, including a final LF for every added line. */ + content: string + } + | { + kind: 'delete' + path: string + lineNumber: number + } + | { + kind: 'update' + path: string + lineNumber: number + moveTo?: string + hunks: PatchHunk[] + } +``` + +```ts type-equiv +/** The first hunk whose anchor or old lines could not be located in the original text. */ +interface HunkApplyFailure { + /** One-based line of the failing hunk in the patch input. */ + hunkLineNumber: number + /** The failed anchor or old-content search. */ + stage: 'context' | 'oldLines' + /** Zero-based sequential search cursor; EOF searches override it with the tail candidate. */ + searchStart: number + /** Original anchor or old lines, including any trailing empty line retried without its sentinel. */ + pattern: string[] +} + +``` + +```ts type-equiv +/** Complete new text or a match failure; failures contain no partially updated text. */ +type ApplyHunksResult = + | { ok: true; after: string } + | { ok: false; failure: HunkApplyFailure } +``` + ## Write and edit guards (provider contract) +The same optional guard rules cover patches, deletion, and moves. Providers perform no observation recording; callers dispatch intents and record completed outcomes. + +| Operation | Intent | Success observation | +|---|---|---| +| `patchText` | `fs/edit-intent` | Target present at the returned version. | +| `deleteFile` | `fs/delete-intent` | Source absent. | +| `moveFile` source | `fs/edit-intent` | Source absent only when `sourceDeleted` is true. | +| `moveFile` destination | `fs/write-intent` | Destination present at `destination.version`. | + +Patch, delete, and move sources must be regular files; missing or stale sources report `FS_STALE_VERSION`. Patch matching runs on LF-normalized text inside the mutation lock, and a mismatch reports `FS_PATCH_MISMATCH` with the patch hunk line and stage. Moves reject identical target keys with `FS_SAME_TARGET`, use write guards for their destination, and preserve source line endings and mode. Deletion, move-source, and overwritten-destination bases are bounded nullable LF text. A move is two effects: the destination may be published while source removal fails. Cancellation is checked before local destination staging; after that, the provider completes both effects and reports their outcome. + +Targets already follow symlinks, so a caller that rejects symlink sources inspects the path with `lstat` before `resolve`. + +```ts type-equiv +/** Outcome of a guarded delete; the bounded basis follows FsWriteOutcome.before. */ +interface FsDeleteOutcome { + /** LF-normalized removed content, or null for an unavailable, binary, or over-limit basis. */ + before: string | null +} +``` + +```ts type-equiv +/** Serializable failure after a move has published its destination but retained its source. */ +interface FsMoveSourceFailure { + /** Filesystem failure code for source removal. */ + code: FsErrorCode + /** Diagnostic identifying the source and the failed removal. */ + message: string +} +``` + +```ts type-equiv +/** Published destination and removal status; sourceBefore is the bounded LF source basis captured under the move lock. */ +type FsMoveOutcome = + | { sourceBefore: string | null; destination: FsWriteOutcome; sourceDeleted: true } + | { sourceBefore: string | null; destination: FsWriteOutcome; sourceDeleted: false; sourceFailure: FsMoveSourceFailure } +``` + Both `writeText` and `editText` take their version guard OPTIONALLY: omit it for an unconditional (bare-provider) mutation, supply it to guard. `writeText`'s guard is an `FsWriteIntent` — `createIfAbsent` creates a missing target and rejects an existing one with `FS_NOT_OBSERVED`, including a target that appears after the provider's initial probe because publication itself must be no-replace; `replaceIfVersion` replaces only when the target exists at the observed version, else `FS_STALE_VERSION`. Omitting `expected` unconditionally creates-or-overwrites. The union itself carries only the two guarded intents; "no guard" is expressed by omission, so write and edit both use the same optional `expected` field. ```ts type-equiv @@ -180,9 +286,9 @@ interface FsEditOutcome { ## The fs policy events (provider contract vocabulary) -`dsh-fs` owns three events the tool dispatches and the policy plugin listens for, so the emitter (`dsh-tool-fs`) and the listener (`dsh-fs-observation-policy`) share a vocabulary without the emitter depending on the policy plugin. They carry only `dsh-fs` vocabulary plus an opaque `object` actor — no model-facing concepts and no agent/session owner structure. +`dsh-fs` owns four events for mutation consumers and observation policy. Consumers dispatch intents before operations and record completed effects; they do not depend on the policy plugin. They carry only `dsh-fs` vocabulary plus an opaque `object` actor — no model-facing concepts and no agent/session owner structure. -`fs/write-intent` and `fs/edit-intent` are **single-slot decision waterfalls**: the tool dispatches each with a default thunk returning `undefined` (the bare provider), and a listener fully decides without calling `next()`. The slot is first-wins by registration order — the policy plugin owning it is a deployment convention, not an enforced invariant. `fs/observed` is a fire-and-forget recording event carrying an `FsObservation`: present at a version or confirmed absent. It is dispatched with a plain `ctx.emit`; its listener MUST be synchronous and side-effect-only, because the tool does NOT guard the emit — a throwing listener can replace a read error or surface as the tool's `isError` result after a mutation already succeeded. The generated [cordis surface](#cordis-surface) below shows the exact signatures. +`fs/write-intent`, `fs/edit-intent`, and `fs/delete-intent` are **single-slot decision waterfalls**: the tool dispatches each with a default thunk returning `undefined` (the bare provider), and a listener fully decides without calling `next()`. The slot is first-wins by registration order — the policy plugin owning it is a deployment convention, not an enforced invariant. `fs/observed` is a fire-and-forget recording event carrying an `FsObservation`: present at a version or confirmed absent. It is dispatched with a plain `ctx.emit`; its listener MUST be synchronous and side-effect-only, because the tool does NOT guard the emit — a throwing listener can replace a read error or surface as the tool's `isError` result after a mutation already succeeded. The generated [cordis surface](#cordis-surface) below shows the exact signatures. ```ts type-equiv /** @@ -239,35 +345,37 @@ interface FileReadOutcome { ## Observed-file state (policy plugin) -Observed state is a `WeakMap>` held inside the `dsh-fs-observation-policy` plugin. Missing map entry means unseen; `{ kind: 'absent' }` means a `read` or `str_replace_editor` `view`, `str_replace`, or `insert` metadata miss confirmed absence; `{ kind: 'present', version }` means a read, write, or edit observed that version. The write decision maps unseen and absent to `createIfAbsent`, while present maps to `replaceIfVersion`; the edit decision maps unseen to `FS_NOT_OBSERVED`, absent to `FS_NOT_FOUND`, and present to its version guard. The owner is derived from the event actor (normally `exec.agent.session`), treated as opaque and never read. Disposal drops everything (HMR safety), and the policy performs no filesystem I/O. +Observed state is a `WeakMap>` held inside the `dsh-fs-observation-policy` plugin. Missing map entry means unseen; `{ kind: 'absent' }` means a `read` or `str_replace_editor` `view`, `str_replace`, or `insert` metadata miss confirmed absence; `{ kind: 'present', version }` means a read, write, or edit observed that version. The write decision maps unseen and absent to `createIfAbsent`, while present maps to `replaceIfVersion`; the edit/delete decision maps unseen to `FS_NOT_OBSERVED`, absent to `FS_NOT_FOUND`, and present to its version guard. The owner is derived from the event actor (normally `exec.agent.session`), treated as opaque and never read. Disposal drops everything (HMR safety), and the policy performs no filesystem I/O. + +## Patch execution (consumer) + +The internal [tool-fs patch executor](../../packages/fs/tool-fs/README.md#understand-the-implementation) dispatches intent decisions in preflight without emitting observations, simulates preceding operations, and reacquires guards for each commit. Sandbox containment stays with the provider at commit, as for `write` and `edit`. Provider results determine which effects are recorded; executor details and failure guarantees belong to the package README. + +| Operation | Preflight intent on first target use | Commit intent | Successful observation | +|---|---|---|---| +| add | `fs/write-intent` | `fs/write-intent` | target present(version) | +| update | `fs/edit-intent` | `fs/edit-intent` | target present(version) | +| delete | `fs/delete-intent` | `fs/delete-intent` | target absent | +| move | source `fs/edit-intent`; destination `fs/write-intent` | same two intents, freshly dispatched | destination present(version); source absent only when removed | + +The `apply_patch` tool returns strict commit values with per-operation diagnostics and full-text change inputs for rendering; persisted metadata holds diff hunks from the provider's bounded bases and a stopped flag. Syntax and preflight refusals set `isError: true`; commit reports retain `isError: false` even when stopped so known partial diffs reach Session presentation, except that a cancelled call receives the tool registry's abort result like every other tool. The [tool README](../../packages/fs/tool-fs/README.md#use-this-package) owns formatting and recovery. ## Error taxonomy (provider contract) Filesystem failures use stable `FsErrorCode` strings carried by `FsError` (`HarnessError`). The tool registry preserves `{ name, code }` on error results, so retry, permission, and UI layers can branch without parsing text. -```ts type-equiv -/** - * Stable, machine-routable codes for filesystem failures. Carried on - * {@link FsError}; the tool registry exposes `{ 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_TOO_LARGE' - | '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_PATCH_MISMATCH` means a hunk failed inside the provider commit; its message names the patch line and failed search stage. `FS_SAME_TARGET` means a move source and destination share the resolved identity. Delete intent follows edit intent: unseen is `FS_NOT_OBSERVED`, observed absence is `FS_NOT_FOUND`, and present state supplies a version. Provider-side missing patch/delete/move sources use `FS_STALE_VERSION` even without a guard. + +```ts +import { FS_ERROR_CODES } from '@deepseek-ai/dsh-fs' ``` -`FS_NOT_DIRECTORY`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR` are used by directory listing to distinguish an existing non-directory target, a denied listing, and an unexpected backend I/O failure. `FS_SANDBOX_DENIED` is a POLICY refusal from a sandbox-enforcing backend (`dsh-fs-sandbox`) — the mode fence denied a write/edit — distinct from `FS_PERMISSION_DENIED` (the host kernel refusing). `FS_NOT_OBSERVED` means the policy plugin has no prior-observation record for this owner (or a `createIfAbsent` hit an existing file). `FS_NOT_FOUND` also represents an edit rejected from confirmed absence. `FS_STALE_VERSION` means the backend version no longer matches the observed one (or the provider itself receives an edit for a missing target). Freshness authorization has no partial/full distinction, so there is no `FS_PARTIAL_OBSERVATION`. +```ts type-equiv +/** One machine-routable filesystem failure code from FS_ERROR_CODES. */ +type FsErrorCode = typeof FS_ERROR_CODES[number] +``` + +`FS_NOT_DIRECTORY`, `FS_PERMISSION_DENIED`, and `FS_IO_ERROR` are used by directory listing to distinguish an existing non-directory target, a denied listing, and an unexpected backend I/O failure. `FS_SANDBOX_DENIED` is a POLICY refusal from a sandbox-enforcing backend (`dsh-fs-sandbox`) — the mode fence denied a mutation — distinct from `FS_PERMISSION_DENIED` (the host kernel refusing). `FS_NOT_OBSERVED` means the policy plugin has no prior-observation record for this owner (or a `createIfAbsent` hit an existing file). `FS_NOT_FOUND` also represents an edit rejected from confirmed absence. `FS_STALE_VERSION` means the backend version no longer matches the observed one (or the provider itself receives an edit for a missing target). Freshness authorization has no partial/full distinction, so there is no `FS_PARTIAL_OBSERVATION`. ## No timeouts on file IO @@ -275,7 +383,7 @@ type FsErrorCode = ## The service and the plugin -`FileSystem` (`ctx.fs`, abstract) owns the provider primitives: `resolve`, `processPath`, `processPathFromHostPath`, `fileUrl`, `contains`, `stat`, `lstat`, `readText`, `streamText`, `readBytes`, `listDir`, `writeText`, and `editText`. `dsh-fs-observation-policy` registers **no service** — it is a plugin that adds policy through the `fs/*` event gate: it decides the write/edit intent waterfalls from unseen/absent/present state and records `FsObservation` values. The executor is `dsh-tool-fs`: it reads/writes/edits through `ctx.fs`, dispatches the waterfalls, and emits the recording event. The generated [`ctx.fs` section](#ctxfs--filesystem-abstract-seam) below shows the exact signatures. +`FileSystem` (`ctx.fs`, abstract) owns the provider primitives: `resolve`, `processPath`, `processPathFromHostPath`, `fileUrl`, `contains`, `stat`, `lstat`, `readText`, `streamText`, `readBytes`, `listDir`, `writeText`, `editText`, `patchText`, `deleteFile`, and `moveFile`. `dsh-fs-observation-policy` registers **no service** — it is a plugin that adds policy through the `fs/*` event gate: it decides the write/edit/delete intent waterfalls from unseen/absent/present state and records `FsObservation` values. The executor is `dsh-tool-fs`: it reads/writes/edits through `ctx.fs`, dispatches the waterfalls, and emits the recording event. The generated [`ctx.fs` section](#ctxfs--filesystem-abstract-seam) below shows the exact signatures. @@ -289,7 +397,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.fs` — `FileSystem` (abstract seam) -Abstract filesystem provider. Targets must preserve identity across aliases; reads expose regular UTF-8 text or typed errors, listings are stable and content-free, and mutations are atomic. Optional guards add stale protection without changing the unguarded provider contract. +Abstract filesystem provider. Targets must preserve identity across aliases; reads expose regular UTF-8 text or typed errors, listings are stable and content-free, and single-file publication is atomic. Moves can retain their source after publishing the destination. Optional guards add stale protection without changing the unguarded provider contract. ```ts cordis-catalog /** @@ -458,6 +566,53 @@ abstract writeText( target: FsTarget, content: string, expected?: FsWriteIntent, * @returns the outcome, including the version the edit produced. */ abstract editText( target: FsTarget, edit: FsEditRequest, expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Atomically apply parsed hunks to the LF-normalized text and restore the + * stored line-ending style. A missing or stale target reports + * `FS_STALE_VERSION`; an unmatched hunk reports `FS_PATCH_MISMATCH`. + * @param target - the resolved regular file to patch. + * @param hunks - ordered hunks from `parsePatch`. + * @param expected - the version guard; omit for an unconditional patch. + * @param signal - aborts before atomic publication takes effect. + * @param sandboxPolicy - the per-call mode and workspace root this patch runs + * under; a sandboxing backend fences the patch by it, the bare backend + * ignores it. Omit to leave the backend its own default. + * @returns the outcome, including the version the patch produced. + */ +abstract patchText( target: FsTarget, hunks: readonly PatchHunk[], expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Remove a regular file. A missing or stale target reports `FS_STALE_VERSION`; + * a directory or other non-file reports `FS_NOT_REGULAR_FILE`. Resolution has + * already followed symlinks, so the target is the real file. + * @param target - the resolved file to remove. + * @param expected - the version guard; omit for an unconditional removal. + * @param signal - aborts before removal. + * @param sandboxPolicy - the per-call mode and workspace root this removal + * runs under; a sandboxing backend fences it, the bare backend ignores it. + * Omit to leave the backend its own default. + * @returns the bounded LF-normalized removed text, or null when no basis is available. + */ +abstract deleteFile( target: FsTarget, expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Publish the source text, optionally patched, at the destination, then remove + * the source. Both targets stay locked in canonical order. Identical targets + * report `FS_SAME_TARGET`; the source guard follows `patchText` and the + * destination guard follows `writeText`. The two effects are separate: a + * published destination with a retained source is a final outcome reported + * through `sourceDeleted: false`. + * @param source - the resolved regular source; its line-ending style and mode carry over. + * @param destination - the resolved destination within the same provider. + * @param options - optional hunks and the source/destination guards; an omitted guard is unconditional. + * @param signal - checked before destination staging; the commit then completes both effects. + * @param sandboxPolicy - the per-call mode and workspace root both paths run + * under; a sandboxing backend fences them, the bare backend ignores it. + * Omit to leave the backend its own default. + * @returns the bounded LF source basis, the destination outcome, and the source-removal status. + */ +abstract moveFile( source: FsTarget, destination: FsTarget, options: { hunks?: readonly PatchHunk[] expectedSource?: { version: FsVersion } expectedDestination?: FsWriteIntent }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise ``` Types: [SandboxExecutionPolicy](sandbox.md) @@ -468,6 +623,25 @@ Source: [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts) ### `fs/*` events + + +#### `fs/delete-intent` — waterfall + +Single-slot decision for FileSystem.deleteFile; the first returned guard wins. Calling next() delegates to an unconditional deletion. + +```ts cordis-catalog +/** + * Single-slot decision for FileSystem.deleteFile; the first returned guard wins. + * Calling next() delegates to an unconditional deletion. + * @param target - the resolved source about to be removed. + * @param actor - the opaque tool-execution context used to select observed state. + * @mode waterfall + */ +'fs/delete-intent'(target: FsTarget, actor: object | undefined, next: () => { version: FsVersion } | undefined | Promise<{ version: FsVersion } | undefined>): Promise<{ version: FsVersion } | undefined> +``` + +Source: [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts) + #### `fs/edit-intent` — waterfall diff --git a/docs/subsystems/filesystem.zh.md b/docs/subsystems/filesystem.zh.md index 6e907d07b8..22f59a7884 100644 --- a/docs/subsystems/filesystem.zh.md +++ b/docs/subsystems/filesystem.zh.md @@ -2,9 +2,9 @@ [English](filesystem.md) | 中文 -可选的文件系统能力由四个部分组成:[dsh-fs](../../packages/fs/fs) 拥有 `ctx.fs` 以及带可选守卫的原子文本操作;[dsh-fs-local](../../packages/fs/fs-local) 实现本地磁盘后端;[dsh-fs-observation-policy](../../packages/fs/fs-observation-policy) 记录观测到的存在或缺失状态,并通过事件(而非服务)添加新鲜度规则;[dsh-tool-fs](../../packages/fs/tool-fs) 直接执行面向模型的 read/write/edit 调用并渲染窗口。它位于 agent loop(智能体循环)主干之外;替换后端不会改变策略或工具 schema。 +可选的文件系统能力由以下角色组成:[dsh-fs](../../packages/fs/fs) 拥有 `ctx.fs` 和受防护的文件变更操作;[dsh-fs-local](../../packages/fs/fs-local) 实现本地磁盘后端;[dsh-fs-observation-policy](../../packages/fs/fs-observation-policy) 记录观测到的存在或缺失状态,并通过事件(而非服务)添加新鲜度规则;[dsh-tool-fs](../../packages/fs/tool-fs) 直接执行面向模型的 read/write/edit 调用并渲染窗口。它位于 agent loop(智能体循环)主干之外;替换后端不会改变策略或工具 schema。纯库 [dsh-fs-patch](../../packages/fs/fs-patch/README.zh.md) 提供补丁解析与文本应用。 -`dsh-fs-observation-policy` 是可选插件。没有该插件时,`FileSystem` 服务定义、一个提供方和 `dsh-tool-fs` 消费方组成完整且不受约束的文件系统 seam:`write` 无条件创建或覆盖,`edit` 无条件替换字面文本。策略插件通过裁决 `fs/*` waterfall(瀑布式事件)来改变这些操作。移除该插件不会破坏工具,因为工具调用 `ctx.fs` 并分发事件,而不调用策略方法。加载了 `dsh-tool-fs` 的部署也应加载 `dsh-fs-observation-policy`,使默认行为为「先读后写/编辑」。 +`dsh-fs-observation-policy` 是可选插件。没有该插件时,`FileSystem` 服务定义、一个提供方和 `dsh-tool-fs` 消费方组成完整且不受约束的文件系统 seam:`write` 无条件创建或覆盖,`edit` 无条件替换字面文本。策略插件通过裁决 `fs/*` waterfall(瀑布式事件)来改变这些操作。移除该插件不会破坏工具,因为工具调用 `ctx.fs` 并分发事件,而不调用策略方法。随发行版交付的组合不启用它:`dsh-base` 中的 `fs-observation-policy` 行写着 `disabled: true`,需要「先读后写/编辑」的部署把该行改为 `disabled: false`。 提供方源码:[`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-observation-policy/src/types.ts`](../../packages/fs/fs-observation-policy/src/types.ts)。读取渲染源码:[`packages/fs/tool-fs/src/read-render.ts`](../../packages/fs/tool-fs/src/read-render.ts)。 @@ -30,7 +30,7 @@ interface FsTarget { } ``` -后端拥有文件版本 token,即 write/edit 所守卫的新鲜度 token。策略插件存储它们以进行陈旧检查;消费方不解释其内容。两个 id 都是品牌化的不透明字符串。 +后端拥有文件版本 token,即变更所守卫的新鲜度 token。策略插件存储它们以进行陈旧检查;消费方不解释其内容。两个 id 都是品牌化的不透明字符串。 ```ts type-equiv /** @@ -111,8 +111,114 @@ interface FsDirEntry { } ``` + +## 补丁语法记录 + +[dsh-fs-patch](../../packages/fs/fs-patch/README.zh.md) 将完整补丁文本解析为可序列化的操作,路径保持为未解析的字符串;`applyHunks` 将 hunk 应用于调用方提供的 LF 规范化文本,返回完整新文本或结构化匹配失败。固定的解析与匹配规则由包 README 维护。 + +```ts type-equiv +/** One contiguous update. */ +interface PatchHunk { + /** One-based input line containing the marker or first implicit hunk line. */ + lineNumber: number + /** Text following `@@ `, used as a search anchor by the text matcher. */ + context?: string + /** Context and removed lines, without patch prefixes or line endings. */ + oldLines: string[] + /** Context and added lines, without patch prefixes or line endings. */ + newLines: string[] + /** Whether `*** End of File` follows this hunk. */ + isEndOfFile: boolean +} + +``` + +```ts type-equiv +/** Ordered file operation; a move is an update with a destination path. */ +type PatchOperation = + | { + kind: 'add' + path: string + lineNumber: number + /** Added lines joined with LF, including a final LF for every added line. */ + content: string + } + | { + kind: 'delete' + path: string + lineNumber: number + } + | { + kind: 'update' + path: string + lineNumber: number + moveTo?: string + hunks: PatchHunk[] + } +``` + +```ts type-equiv +/** The first hunk whose anchor or old lines could not be located in the original text. */ +interface HunkApplyFailure { + /** One-based line of the failing hunk in the patch input. */ + hunkLineNumber: number + /** The failed anchor or old-content search. */ + stage: 'context' | 'oldLines' + /** Zero-based sequential search cursor; EOF searches override it with the tail candidate. */ + searchStart: number + /** Original anchor or old lines, including any trailing empty line retried without its sentinel. */ + pattern: string[] +} + +``` + +```ts type-equiv +/** Complete new text or a match failure; failures contain no partially updated text. */ +type ApplyHunksResult = + | { ok: true; after: string } + | { ok: false; failure: HunkApplyFailure } +``` + ## 写入与编辑守卫(提供方约定) +相同的可选防护规则也覆盖补丁、删除和移动。提供方不记录观察;调用方分派意图并记录已完成的结果。 + +| 操作 | 意图 | 成功观察 | +|---|---|---| +| `patchText` | `fs/edit-intent` | 目标存在于返回的版本。 | +| `deleteFile` | `fs/delete-intent` | 源缺失。 | +| `moveFile` 源 | `fs/edit-intent` | 仅在 `sourceDeleted` 为 true 时记录源缺失。 | +| `moveFile` 目标 | `fs/write-intent` | 目标存在于 `destination.version`。 | + +补丁、删除和移动的源必须是普通文件;源缺失或版本陈旧报告 `FS_STALE_VERSION`。补丁在变更锁内对 LF 规范化文本匹配,不匹配报告 `FS_PATCH_MISMATCH`,包含补丁 hunk 行号与阶段。移动以 `FS_SAME_TARGET` 拒绝相同目标 key,对目标使用写入防护,并保留源的行尾风格与模式。删除、移动源和被覆盖目标的基线是有界、可空的 LF 文本。移动是两个效果:目标可能已发布而源删除失败。本地移动在暂存目标前检查取消;随后提供方完成两端效果并报告结果。 + +目标已跟随符号链接,因此拒绝符号链接源的调用方在 `resolve` 前用 `lstat` 检查路径。 + +```ts type-equiv +/** Outcome of a guarded delete; the bounded basis follows FsWriteOutcome.before. */ +interface FsDeleteOutcome { + /** LF-normalized removed content, or null for an unavailable, binary, or over-limit basis. */ + before: string | null +} +``` + +```ts type-equiv +/** Serializable failure after a move has published its destination but retained its source. */ +interface FsMoveSourceFailure { + /** Filesystem failure code for source removal. */ + code: FsErrorCode + /** Diagnostic identifying the source and the failed removal. */ + message: string +} +``` + +```ts type-equiv +/** Published destination and removal status; sourceBefore is the bounded LF source basis captured under the move lock. */ +type FsMoveOutcome = + | { sourceBefore: string | null; destination: FsWriteOutcome; sourceDeleted: true } + | { sourceBefore: string | null; destination: FsWriteOutcome; sourceDeleted: false; sourceFailure: FsMoveSourceFailure } +``` + `writeText` 和 `editText` 的版本守卫都是可选的:省略守卫时执行无条件的裸提供方变更,提供守卫时则执行相应的条件检查。`writeText` 的守卫是 `FsWriteIntent`:`createIfAbsent` 在目标缺失时创建,目标已存在时以 `FS_NOT_OBSERVED` 拒绝;即使目标在提供方初始探测后才出现,也必须拒绝,因为发布操作本身不得替换。`replaceIfVersion` 仅在目标存在且版本匹配时替换,否则报 `FS_STALE_VERSION`。省略 `expected` 则无条件创建或覆盖。联合类型本身只包含两种有守卫的意图;「无守卫」通过省略表达,因此 write 和 edit 都使用同一个可选的 `expected` 字段。 ```ts type-equiv @@ -180,9 +286,9 @@ interface FsEditOutcome { ## fs 策略事件(提供方约定词汇) -`dsh-fs` 拥有三个事件,由工具分发、策略插件监听,使事件发出方(`dsh-tool-fs`)与监听方(`dsh-fs-observation-policy`)共享词汇,而事件发出方无需依赖策略插件。它们只携带 `dsh-fs` 词汇加一个不透明的 `object` actor,不含面向模型的概念,也不含 agent/会话所有者结构。 +`dsh-fs` 为变更消费方与观察策略定义四个事件。消费方在操作前分发意图,并记录已完成的效果,无需依赖策略插件。它们只携带 `dsh-fs` 词汇加一个不透明的 `object` actor,不含面向模型的概念,也不含 agent/会话所有者结构。 -`fs/write-intent` 与 `fs/edit-intent` 是**单槽决策 waterfall**:工具分发时附带一个默认 thunk(返回 `undefined`,即裸提供方),监听方完全决策而不调用 `next()`。该 slot 按注册顺序先到先得——由策略插件占据是部署约定,而非强制不变式。`fs/observed` 是一个即发即弃的记录事件,携带 `FsObservation`:存在于某个版本,或确认缺失。该事件通过普通 `ctx.emit` 分发;其监听方必须是同步的、仅产生副作用,因为工具不会捕获该 emit 抛出的异常——抛出异常的监听方可能取代读取操作原本待返回的错误,或使工具在变更已经成功后返回 `isError` 结果。下方生成的 [cordis surface](#cordis-surface) 展示确切签名。 +`fs/write-intent`、`fs/edit-intent` 与 `fs/delete-intent` 是**单槽决策 waterfall**:工具分发时附带一个默认 thunk(返回 `undefined`,即裸提供方),监听方完全决策而不调用 `next()`。该 slot 按注册顺序先到先得——由策略插件占据是部署约定,而非强制不变式。`fs/observed` 是一个即发即弃的记录事件,携带 `FsObservation`:存在于某个版本,或确认缺失。该事件通过普通 `ctx.emit` 分发;其监听方必须是同步的、仅产生副作用,因为工具不会捕获该 emit 抛出的异常——抛出异常的监听方可能取代读取操作原本待返回的错误,或使工具在变更已经成功后返回 `isError` 结果。下方生成的 [cordis surface](#cordis-surface) 展示确切签名。 ```ts type-equiv /** @@ -239,35 +345,37 @@ interface FileReadOutcome { ## 已观测文件状态(策略插件) -已观测状态是 `dsh-fs-observation-policy` 插件内部持有的 `WeakMap>`。映射中没有条目表示未见;`{ kind: 'absent' }` 表示 `read` 的元数据未命中,或 `str_replace_editor` 的 `view`、`str_replace`、`insert` 命令发生元数据未命中,从而确认缺失;`{ kind: 'present', version }` 表示 read、write 或 edit 观测到该版本。写入决策把未见和缺失映射到 `createIfAbsent`,把存在映射到 `replaceIfVersion`;编辑决策把未见映射到 `FS_NOT_OBSERVED`,把缺失映射到 `FS_NOT_FOUND`,把存在映射到其版本守卫。所有者从事件 actor 推导(通常是 `exec.agent.session`),被视为不透明且从不读取。dispose(资源释放)时丢弃全部数据(HMR(热模块替换)安全),策略不执行任何文件系统 I/O。 +已观测状态是 `dsh-fs-observation-policy` 插件内部持有的 `WeakMap>`。映射中没有条目表示未见;`{ kind: 'absent' }` 表示 `read` 的元数据未命中,或 `str_replace_editor` 的 `view`、`str_replace`、`insert` 命令发生元数据未命中,从而确认缺失;`{ kind: 'present', version }` 表示 read、write 或 edit 观测到该版本。写入决策把未见和缺失映射到 `createIfAbsent`,把存在映射到 `replaceIfVersion`;编辑/删除决策把未见映射到 `FS_NOT_OBSERVED`,把缺失映射到 `FS_NOT_FOUND`,把存在映射到其版本守卫。所有者从事件 actor 推导(通常是 `exec.agent.session`),被视为不透明且从不读取。dispose(资源释放)时丢弃全部数据(HMR(热模块替换)安全),策略不执行任何文件系统 I/O。 + +## 补丁执行(消费方) + +内部 [tool-fs 补丁执行器](../../packages/fs/tool-fs/README.zh.md#understand-the-implementation) 在预检时分发意图决策而不发出观察、模拟前序操作,并在每次提交时重新取得防护。沙箱围栏与 `write`、`edit` 一样由提供方在提交时判断。提供方结果决定记录哪些效果;执行器细节与失败保证由包 README 维护。 + +| 操作 | 首次使用目标的预检意图 | 提交意图 | 成功观察 | +|---|---|---|---| +| add | `fs/write-intent` | `fs/write-intent` | 目标 present(version) | +| update | `fs/edit-intent` | `fs/edit-intent` | 目标 present(version) | +| delete | `fs/delete-intent` | `fs/delete-intent` | 目标 absent | +| move | 源 `fs/edit-intent`;目标 `fs/write-intent` | 重新分发同一组意图 | 目标 present(version);仅在源删除成功时记录 absent | + +`apply_patch` 工具返回严格的提交值,包含各操作诊断及用于渲染的完整文本变更输入;持久化元数据只保留基于提供方有界基线的 diff hunk 与停止标志。语法和预检拒绝为 `isError: true`;停止的提交报告仍为 `isError: false`,确保已知部分 diff 进入 Session 展示,但被取消的调用与其他工具一样收到工具注册表的中止结果。[工具 README](../../packages/fs/tool-fs/README.zh.md#use-this-package) 维护格式与恢复规则。 ## 错误分类体系(提供方约定) 文件系统故障使用稳定的 `FsErrorCode` 字符串,由 `FsError`(`HarnessError`)携带。工具注册表在错误结果上保留 `{ name, code }`,使重试、权限和 UI 层可以按 code 分支而无需解析文本。 -```ts type-equiv -/** - * Stable, machine-routable codes for filesystem failures. Carried on - * {@link FsError}; the tool registry exposes `{ 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_TOO_LARGE' - | '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_PATCH_MISMATCH` 表示 hunk 在提供方提交阶段未匹配;消息标明补丁行号与失败的搜索阶段。`FS_SAME_TARGET` 表示移动源与目标共享已解析身份。删除意图遵循编辑意图:未见为 `FS_NOT_OBSERVED`,观察到缺失为 `FS_NOT_FOUND`,存在状态提供版本。提供方收到缺失的补丁/删除/移动源时,即使没有防护也使用 `FS_STALE_VERSION`。 + +```ts +import { FS_ERROR_CODES } from '@deepseek-ai/dsh-fs' ``` -目录列表使用 `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_NOT_FOUND` 也表示策略因确认缺失而拒绝 edit。`FS_STALE_VERSION` 表示后端版本不再与观测到的版本匹配(或提供方本身收到针对缺失目标的 edit)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。 +```ts type-equiv +/** One machine-routable filesystem failure code from FS_ERROR_CODES. */ +type FsErrorCode = typeof FS_ERROR_CODES[number] +``` + +目录列表使用 `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_NOT_FOUND` 也表示策略因确认缺失而拒绝 edit。`FS_STALE_VERSION` 表示后端版本不再与观测到的版本匹配(或提供方本身收到针对缺失目标的 edit)。新鲜度授权没有部分/完整之分,因此不存在 `FS_PARTIAL_OBSERVATION`。 ## 文件 IO 不设超时 @@ -275,7 +383,7 @@ type FsErrorCode = ## 服务与插件 -`FileSystem`(`ctx.fs`,abstract)拥有提供方原语:`resolve`、`processPath`、`processPathFromHostPath`、`fileUrl`、`contains`、`stat`、`lstat`、`readText`、`streamText`、`readBytes`、`listDir`、`writeText` 与 `editText`。`dsh-fs-observation-policy` **不注册服务**。它通过 `fs/*` 事件门禁添加策略,根据未见、缺失或存在状态对写入与编辑意图 waterfall 作出决策,并记录 `FsObservation` 值。执行器是 `dsh-tool-fs`:它通过 `ctx.fs` 读取、写入或编辑,分发 waterfall,并 emit 记录事件。下方生成的 [`ctx.fs` 小节](#ctxfs--filesystem-abstract-seam) 展示确切的 `ctx.fs` 签名。 +`FileSystem`(`ctx.fs`,abstract)拥有提供方原语:`resolve`、`processPath`、`processPathFromHostPath`、`fileUrl`、`contains`、`stat`、`lstat`、`readText`、`streamText`、`readBytes`、`listDir`、`writeText`、`editText`、`patchText`、`deleteFile` 与 `moveFile`。`dsh-fs-observation-policy` **不注册服务**。它通过 `fs/*` 事件门禁添加策略,根据未见、缺失或存在状态对写入、编辑与删除意图 waterfall 作出决策,并记录 `FsObservation` 值。执行器是 `dsh-tool-fs`:它通过 `ctx.fs` 读取、写入或编辑,分发 waterfall,并 emit 记录事件。下方生成的 [`ctx.fs` 小节](#ctxfs--filesystem-abstract-seam) 展示确切的 `ctx.fs` 签名。 @@ -289,7 +397,7 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.fs` — `FileSystem` (abstract seam) -Abstract filesystem provider. Targets must preserve identity across aliases; reads expose regular UTF-8 text or typed errors, listings are stable and content-free, and mutations are atomic. Optional guards add stale protection without changing the unguarded provider contract. +Abstract filesystem provider. Targets must preserve identity across aliases; reads expose regular UTF-8 text or typed errors, listings are stable and content-free, and single-file publication is atomic. Moves can retain their source after publishing the destination. Optional guards add stale protection without changing the unguarded provider contract. ```ts cordis-catalog /** @@ -458,6 +566,53 @@ abstract writeText( target: FsTarget, content: string, expected?: FsWriteIntent, * @returns the outcome, including the version the edit produced. */ abstract editText( target: FsTarget, edit: FsEditRequest, expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Atomically apply parsed hunks to the LF-normalized text and restore the + * stored line-ending style. A missing or stale target reports + * `FS_STALE_VERSION`; an unmatched hunk reports `FS_PATCH_MISMATCH`. + * @param target - the resolved regular file to patch. + * @param hunks - ordered hunks from `parsePatch`. + * @param expected - the version guard; omit for an unconditional patch. + * @param signal - aborts before atomic publication takes effect. + * @param sandboxPolicy - the per-call mode and workspace root this patch runs + * under; a sandboxing backend fences the patch by it, the bare backend + * ignores it. Omit to leave the backend its own default. + * @returns the outcome, including the version the patch produced. + */ +abstract patchText( target: FsTarget, hunks: readonly PatchHunk[], expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Remove a regular file. A missing or stale target reports `FS_STALE_VERSION`; + * a directory or other non-file reports `FS_NOT_REGULAR_FILE`. Resolution has + * already followed symlinks, so the target is the real file. + * @param target - the resolved file to remove. + * @param expected - the version guard; omit for an unconditional removal. + * @param signal - aborts before removal. + * @param sandboxPolicy - the per-call mode and workspace root this removal + * runs under; a sandboxing backend fences it, the bare backend ignores it. + * Omit to leave the backend its own default. + * @returns the bounded LF-normalized removed text, or null when no basis is available. + */ +abstract deleteFile( target: FsTarget, expected?: { version: FsVersion }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise + +/** + * Publish the source text, optionally patched, at the destination, then remove + * the source. Both targets stay locked in canonical order. Identical targets + * report `FS_SAME_TARGET`; the source guard follows `patchText` and the + * destination guard follows `writeText`. The two effects are separate: a + * published destination with a retained source is a final outcome reported + * through `sourceDeleted: false`. + * @param source - the resolved regular source; its line-ending style and mode carry over. + * @param destination - the resolved destination within the same provider. + * @param options - optional hunks and the source/destination guards; an omitted guard is unconditional. + * @param signal - checked before destination staging; the commit then completes both effects. + * @param sandboxPolicy - the per-call mode and workspace root both paths run + * under; a sandboxing backend fences them, the bare backend ignores it. + * Omit to leave the backend its own default. + * @returns the bounded LF source basis, the destination outcome, and the source-removal status. + */ +abstract moveFile( source: FsTarget, destination: FsTarget, options: { hunks?: readonly PatchHunk[] expectedSource?: { version: FsVersion } expectedDestination?: FsWriteIntent }, signal?: AbortSignal, sandboxPolicy?: SandboxExecutionPolicy, ): Promise ``` Types: [SandboxExecutionPolicy](sandbox.zh.md) @@ -468,6 +623,25 @@ Source: [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts) ### `fs/*` events + + +#### `fs/delete-intent` — waterfall + +Single-slot decision for FileSystem.deleteFile; the first returned guard wins. Calling next() delegates to an unconditional deletion. + +```ts cordis-catalog +/** + * Single-slot decision for FileSystem.deleteFile; the first returned guard wins. + * Calling next() delegates to an unconditional deletion. + * @param target - the resolved source about to be removed. + * @param actor - the opaque tool-execution context used to select observed state. + * @mode waterfall + */ +'fs/delete-intent'(target: FsTarget, actor: object | undefined, next: () => { version: FsVersion } | undefined | Promise<{ version: FsVersion } | undefined>): Promise<{ version: FsVersion } | undefined> +``` + +Source: [`packages/fs/fs/src/index.ts`](../../packages/fs/fs/src/index.ts) + #### `fs/edit-intent` — waterfall diff --git a/docs/subsystems/schedule.i18n.yaml b/docs/subsystems/schedule.i18n.yaml index 63354f0fd0..a8ce292ca5 100644 --- a/docs/subsystems/schedule.i18n.yaml +++ b/docs/subsystems/schedule.i18n.yaml @@ -3,38 +3,47 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/schedule.md /host-wide-schedule: - en: 71c4686e65a7c7f9 - zh: dfba124c28db2f63 -/host-wide-schedule/durable-records: - en: 41cd197b5c74bfa3 - zh: 18ed11259036d726 + en: d977861519ae2e36 + zh: 910ba93329cfe56b +/host-wide-schedule/durable-tasks: + en: 5ddc67179a897c74 + zh: 47024e886fa70abf +/host-wide-schedule/storage-versioning: + en: ad9b7b25eebb91b3 + zh: 6158c5cc9ef12a7f +/host-wide-schedule/recurrence-rules: + en: f68c0b3ff09ce20e + zh: 9fc4470739ff640c /host-wide-schedule/absolute-time-input: - en: a07f1a7153b0074f - zh: f3c584db1073e49d -/host-wide-schedule/daily-wall-clock-input: - en: 2d249edc3dfccb8a - zh: 33fecda132b03b84 + en: a7c1c1b63ffb19cf + zh: 9b00f818c4774ad8 +/host-wide-schedule/daily-and-weekly-input: + en: a4c09868c5009bef + zh: 511ec3d7ae6b0d98 /host-wide-schedule/fixed-rate-input-and-catch-up: - en: d2b5997cce3806dc - zh: 2483ba9e38ad3cf3 -/host-wide-schedule/cron-wall-clock-input: - en: 1ba9ae84f05d8919 - zh: 5b4abfdcddbbcae0 -/host-wide-schedule/historical-session-changes: - en: d3bdcf22dd771a7d - zh: 11af3e617a7ef3fd -/host-wide-schedule/active-views-and-management: - en: 93798ad69f74ddd5 - zh: 634126ad8accc356 -/host-wide-schedule/web-catalog: - en: 3377a013bf8cbfb7 - zh: c5666dc3f28b087f + en: 79fb76147de2d82c + zh: 8a75d2bc1229caf3 +/host-wide-schedule/cron-input: + en: 0019e68edcba3717 + zh: 82efc84f09bb8062 +/host-wide-schedule/rrule-input: + en: f93ebb99c73f5d38 + zh: 8b5787f0ea845ad2 +/host-wide-schedule/delivery-targets: + en: d10b60799a055427 + zh: 68d33f2f59f826b8 +/host-wide-schedule/task-management: + en: 7a979f8fef09af59 + zh: 475d982686030c50 /host-wide-schedule/timing-edits: - en: ce5d2095a3ad2e82 - zh: 167b3715f8eaffc1 + en: 93c882d1c1924527 + zh: 750b73ab93c9517a /host-wide-schedule/saved-delivery-records: - en: 077aa6573d9ede1a - zh: 0acea592a6e3630a + en: 968ae643ca6533a9 + zh: ec47298b370b2b05 /host-wide-schedule/host-delivery: - en: d5fc5b853529b139 - zh: 4cc5eba14f9660e6 + en: 362e9b4c26f90b5a + zh: 37a9882fcf5bafc1 +/host-wide-schedule/historical-session-changes: + en: 0df44daf6df88577 + zh: 178d9dc601ac2843 diff --git a/docs/subsystems/schedule.md b/docs/subsystems/schedule.md index 13f1752a31..fb60d5c33f 100644 --- a/docs/subsystems/schedule.md +++ b/docs/subsystems/schedule.md @@ -2,448 +2,140 @@ English | [中文](schedule.zh.md) -Schedule stores reminders independently of Session activation and delivers them to their original Session. This page records the durable and model-facing types from [`types.ts`](../../packages/schedule/schedule/src/types.ts); the [package README](../../packages/schedule/schedule/README.md) owns composition and reminder framing. +Schedule stores Host tasks independently of Session activation. One management API addresses tasks by id, and one evaluator handles seven authoritative timing kinds: `after`, `at`, `every`, `daily`, `weekly`, `cron`, and `rrule`. Targets reuse an existing Session, create one Session and reuse it, or create a Session for each delivery. The [package README](../../packages/schedule/schedule/README.md) owns composition and reminder framing; [`types.ts`](../../packages/schedule/schedule/src/types.ts) owns the complete value and request types. -## Durable records + +## Durable tasks -`ScheduleId` is a globally unique [branded id](core.md#branded-ids). The version-1 `schedule` storage domain owns a `tasks` table whose entries bind a `ScheduleRecord` to its original `sessionId`, with stored `status: 'active' | 'inactive'` and optional `lastDelivery`. Records lacking status normalize to `active` without scanning or recreating historical Sessions. Creation canonicalizes the target into RFC 3339 UTC `scheduledAt`; `after` retains the submitted delay, `every` retains its fixed interval, `daily` and `weekly` retain normalized local `time` and their explicit `timeZone`, and `cron` retains its canonical five-field `expression` and explicit `timeZone`. Daily, weekly, and cron decoding preserve the committed instant and stored zone spelling. The stored task record declares a required `title`, the short name the task surfaces show; creation requires it and never derives it from the instruction. No stored record may omit its title: a record whose `title` is missing, blank after trimming, untrimmed, or longer than 120 characters fails durable decoding with `ScheduleLogError`, and the schedule domain declares no backup-and-skip policy, so one such stored task rejects the whole domain open instead of being dropped. Only explicit deletion removes a task; previously physically deleted tasks are not restored or fabricated. +The plugin README owns the current [v2 task schema, v1 defaults, and persisted JSON example](../../packages/schedule/schedule/README.md#storage-format). The domain retains its name, routing, and whole-unit layout. All seven timing kinds remain authoritative; normalization preserves committed occurrences and does not convert Cron into RRULE. -```ts type-equiv -/** Durable one-shot reminder created from a positive delay. */ -interface AfterScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a delayed one-shot reminder. */ - readonly kind: 'after' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Positive safe-integer delay accepted at creation. */ - readonly afterSeconds: number - /** Four-digit-year RFC 3339 UTC target. */ - readonly scheduledAt: string -} -``` +Malformed storage, invalid rows, mismatched task keys, and unsupported versions reject before tasks activate. Failed opening leaves the medium unchanged. An absent file starts empty. Missing target Sessions remain visible in management; reading a task never activates its Session. -```ts type-equiv -/** Durable one-shot reminder created from an absolute instant. */ -interface AtScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for an absolute one-shot reminder. */ - readonly kind: 'at' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Four-digit-year RFC 3339 UTC target. */ - readonly scheduledAt: string -} -``` + +## Storage versioning -```ts type-equiv -/** Durable fixed-rate reminder aligned to creation or its most recent interval edit. */ -interface EveryScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a fixed-rate recurring reminder. */ - readonly kind: 'every' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Fixed safe-integer interval, never below one minute. */ - readonly everySeconds: number - /** Next anchor-aligned occurrence while active, or final occurrence when inactive. */ - readonly scheduledAt: string -} -``` +The README defines [when tasks upgrade](../../packages/schedule/schedule/README.md#storage-format), SQLite's unchanged physical schema, mutation costs, and a future compatible v3. `compatibleVersions` admits old unit stamps for current decoding; normal edits and delivery persist current rows. Reads leave storage unchanged. The shared [domain version policy](storage.md#domain-versioning) applies to both JSON and SQLite. -```ts type-equiv -/** Durable daily wall-clock reminder; gaps skip a date and overlaps use the earlier instant. */ -interface DailyScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a daily wall-clock reminder. */ - readonly kind: 'daily' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Local time normalized to HH:mm:ss.SSS. */ - readonly time: string - /** Explicit IANA zone; equivalent timing edits retain the stored spelling. */ - readonly timeZone: string - /** Committed next UTC instant while active, or final occurrence when inactive. */ - readonly scheduledAt: string -} -``` + +## Recurrence rules -```ts type-equiv -/** One-shot task variants. */ -type OneShotScheduleRecord = AfterScheduleRecord | AtScheduleRecord -``` +[`dsh-util-time`](../../packages/util/time/README.md) owns reusable `Cron` and `RRule` parsing and bounded occurrence arithmetic. Both parsed values expose their authoritative expression and zone, `next(after)`, and `resolve(scheduledAt, acceptedAt)`. Parsers return an accepted value or a rejection reason; Schedule maps reasons to its own input errors and owns record validation, admission limits, persistence, and dispatch. -```ts type-equiv -/** Recurring Host task variants. */ -type RecurringScheduleRecord = EveryScheduleRecord | DailyScheduleRecord | WeeklyScheduleRecord | CronScheduleRecord -``` +Every stored `scheduledAt` is a canonical RFC 3339 UTC instant with millisecond precision and a year from 0001 through 9999. Decoding never recalculates it from current zone data. Latest-only catch-up preserves that committed floor, delivers the latest due occurrence once, and commits the first future occurrence. Exhaustion leaves the task stored as `ended`. -```ts type-equiv -/** Reminder rule and target, stored with its original Session binding. */ -type ScheduleRecord = OneShotScheduleRecord | RecurringScheduleRecord -``` +| Kind | Authoritative timing | +|---|---| +| `after` | Positive integer `afterSeconds` and the committed one-shot UTC target. | +| `at` | Committed one-shot UTC target. Input accepts an explicit-offset instant or a local date, time, and explicit zone. | +| `every` | Integer `everySeconds` of at least 60; occurrences stay aligned to their committed interval anchor. | +| `daily` | Local `time` as `HH:mm:ss.SSS` and explicit `timeZone`. | +| `weekly` | Daily fields plus a nonempty, unique, ascending ISO `weekdays` set, Monday 1 through Sunday 7. | +| `cron` | Canonical five-field `expression` and explicit `timeZone`. | +| `rrule` | One normalized `DTSTART` line and one `RRULE` line in `rrule`; `DTSTART` supplies the anchor and zone. | +Local calendar rules skip missing wall times and choose the earlier instant of an overlap. Fixed intervals retain their elapsed-time meaning. A one-shot delay may be shorter than a minute; the per-task delivery floor still applies after its first delivery. + + ## Absolute-time input -The `at` selector is either a strict offset-bearing RFC 3339 string or an exact local-calendar object. The local form keeps its interpretation explicit at the tool boundary: - -```ts type-equiv -/** Structured local-calendar input accepted by creation and timing edits. */ -interface LocalAtInput { - /** Four-digit ISO calendar date. */ - readonly date: string - /** Local wall-clock time with optional one-to-three digit milliseconds. */ - readonly time: string - /** Explicit UTC or IANA Area/Location zone. */ - readonly time_zone: string -} -``` - -```ts type-equiv -/** Absolute selector accepted by creation and timing edits. */ -type AtInput = string | LocalAtInput -``` - -The shipped Web composition mounts the `schedule` service and the `ui-schedule` task page. The clock reading and the four reminder tools are preset-owned: `standard`, `cordis`, and `ptc` declare `time-context` and `@deepseek-ai/dsh-tool-schedule` together, and `minimal` declares neither. The `tool-subagent` and `tool-subagent-fork` rows in those three presets deny the four tools, and each tool refuses a delegated caller with `subagent_session`, so a delegated child neither sees the tools nor has a call accepted. Time-context tells the model to interpret otherwise-unqualified natural-language dates and times in that request-local zone when the open turn has one unambiguous browser zone; mixed or missing browser-zone records tell the model to ask. That guidance is not a durable Session default: the model must still pass an offset in the string form or `time_zone` in the local form, and Schedule never reads browser, Session, process, or model context. - -Schedule rejects invalid offsets and zones, offset-free strings, non-future targets, and local times inside daylight-saving gaps. A daylight-saving overlap chooses its first, earlier instant. Successful creation stores only canonical UTC `scheduledAt`, so replay never depends on ambient time-zone state. +An `at` selector accepts an RFC 3339 instant with an explicit `Z` or numeric offset, or `{ date, time, time_zone }`. Local dates use `YYYY-MM-DD`; local times use `HH:mm:ss` with optional one-to-three fractional digits. Ambiguous or nonexistent calendar values are validated through the shared time utilities. A new absolute target must be strictly future and representable. -## Daily wall-clock input +## Daily and weekly input -`daily` is one of the mutually exclusive creation selectors, alongside `after_seconds`, `at`, `every_seconds`, the weekly selector, and the cron selector. For example, `daily: { time: '23:00:00', time_zone: 'Asia/Shanghai' }` selects 23:00 in that zone on each eligible local date. The exact object has no date, offset, or interval field: - -```ts type-equiv -/** Daily local-time selector accepted by creation and timing edits. */ -interface DailyInput { - /** Local HH:mm:ss time with optional one-to-three fractional digits. */ - readonly time: string - /** Explicit UTC or IANA Area/Location zone. */ - readonly time_zone: string -} -``` - -Creation requires `HH:mm:ss` with optional one-to-three fractional digits, rejects leap seconds and `24:00`, canonicalizes the explicit IANA zone, and stores `time` as `HH:mm:ss.SSS`. The first `scheduledAt` is strictly after creation time. A nonexistent local time or entire date is skipped; an overlap selects the earlier instant once per local date. If that earlier instant has passed, the later duplicate is not eligible. Only UTC target years 0001–9999 are constrained; local dates at the UTC range edges may fall in year 0 or 10000. - -A saved next target is a committed UTC instant. The Host decoder and restart preserve that instant without resolving it against time-zone rules again, and valid stored zone aliases remain readable when canonical names change. Subsequent targets use the Host's current IANA data. The next target must be both after the delivery decision and on a local date later than the selected occurrence's date. Creation fails with `time_out_of_range` when no future UTC target is representable. +Daily input supplies `{ time, time_zone }`; Weekly adds explicit `weekdays`. Creation chooses the first strictly future actual occurrence. Catch-up chooses the latest actual due occurrence and advances to a later matching local date. Equivalent edits retain the stored IANA alias and pinned UTC target, including milliseconds. + ## Fixed-rate input and catch-up -`every_seconds` is a safe-integer interval of at least 60 seconds, aligned to creation time. It measures elapsed time, not daily wall-clock time: `every_seconds: 86400` cannot substitute for `daily` across offset changes. The protocol provides no shared cooldown or cross-record admission rule; the cron selector described below is wall-clock timing, not a fixed-rate interval. - -When the Host starts with an overdue Every, Daily, Weekly, or Cron record, it sends only the latest due occurrence. Every advances to the first target aligned to its current interval anchor after the delivery decision; Daily, Weekly, and Cron follow the local-date rules above and below. Missed occurrences do not accumulate. If no next UTC target is representable, delivery retains the record as inactive with its latest receipt. - -One-shots produce individual follow-ups. Recurring records due in the same scan for the same Session share one follow-up rendered by `renderRecurringReminderBatchFraming`, with one latest occurrence per record. The one-minute minimum applies only to fixed-rate intervals; delivery does not wait for the target Agent to become idle. +Every input supplies `every_seconds`. A new interval starts from acceptance time; a changed interval establishes a new anchor at edit acceptance. An unchanged interval or a name/prompt edit keeps the old anchor. Downtime coalesces missed intervals instead of replaying each occurrence. -## Cron wall-clock input +## Cron input -`cron` is one of the mutually exclusive creation selectors. Its exact object carries only the strict five-field Vixie expression `minute hour day-of-month month day-of-week` and an explicit IANA zone, for example `cron: { expression: '*/15 9-17 * * 1-5', time_zone: 'Asia/Shanghai' }`. The field bounds are: +Cron input supplies `{ expression, time_zone }`. Its five numeric fields are minute, hour, day-of-month, month, and day-of-week. Supported atoms are `*`, a value, an inclusive range, a star or range step, and comma-separated lists. Sunday accepts 0 or 7 and canonicalizes to 0. Names, macros, a seconds field, and a value followed by a step are rejected. -| Field | Accepted range | Notes | -|---|---|---| -| minute | 0-59 | | -| hour | 0-23 | | -| day-of-month | 1-31 | | -| month | 1-12 | | -| day-of-week | 0-7 | Both `0` and `7` mean Sunday. | +Cron keeps Vixie day matching: when both day fields are restricted, day-of-month **or** day-of-week may match; when either field starts with `*`, including a stepped star, both matched sets must match. Canonicalization preserves that distinction. Searches are bounded by one 400-year Gregorian cycle and the four-digit UTC range. A rule with no representable future occurrence is refused when armed. -Every field accepts `*`, a single value, an `a-b` range, a `*/n` or `a-b/n` step with `n >= 1`, and a comma-separated list of those forms. Everything else is rejected with `invalid_rule` and a message naming the offending field: `L`, `W`, and `#` operators, `JAN`/`MON` names, `@daily`-style macros, six-field expressions with a seconds field, out-of-range values, inverted ranges, zero steps, and empty fields. Because the dialect has five fields, the smallest interval is one minute; sub-minute scheduling stays unsupported. +Cron records are never converted into RRULE. Their saved expression and zone remain authoritative through reads, descriptive edits, retargeting, and restart. The Custom editor accepts a five-field Cron expression and exposes its explicit zone selector. -Creation canonicalizes the expression before storing it. Canonicalization expands each field into its matched value set and re-encodes that set deterministically: repeated values collapse, adjacent values and ranges merge, a uniform step is written as `a-b/n` or, for a field that started with `*`, as a star-step (`*` for every value, otherwise the widest star-step walk plus any remaining values), a step of `1` is dropped, and Sunday is written as `0`. A field that did not start with `*` never becomes a star-step. Preserving each field's star flag is what keeps the day-of-month/day-of-week rule below Vixie-faithful across the stored expression. The durable decoder rejects a stored expression that is not canonical. + +## RRULE input -The first target is the first strictly future instant whose local date and time in the zone match. It reuses the Daily and Weekly local-time resolution: a non-existent local time is skipped, and an ambiguous one takes the earlier occurrence once for that date. The committed UTC `scheduledAt` is never recomputed on restart. +RRULE accepts a bounded RFC 5545 subset, defined by the shared [`rrule.ts` parser](../../packages/util/time/src/rrule.ts). Input has exactly two nonempty content lines: `DTSTART` followed by `RRULE`. The start is a real `YYYYMMDDTHHMMSS` date-time with UTC `Z` or an explicit IANA `TZID`; floating local time, numeric offsets, date-only values, and extra content lines are rejected. The engine uses `rrule` 2.8.1 and supports `MINUTELY`, `HOURLY`, `DAILY`, `WEEKLY`, `MONTHLY`, and `YEARLY`. A one-shot uses `COUNT=1`. -Day-of-month and day-of-week follow Vixie semantics. A field is a star when its text starts with `*`, independently of the values it matches, so `*/1` and `*/2` are stars while `1-31` and `0-7` are restricted. When either field is a star, a local date matches only when both fields match; when neither is a star, it matches when either field matches. +Only `FREQ`, `INTERVAL`, `COUNT`, `UNTIL`, `WKST`, `BYSECOND`, `BYMINUTE`, `BYHOUR`, `BYDAY`, `BYMONTHDAY`, `BYYEARDAY`, `BYWEEKNO`, `BYMONTH`, and `BYSETPOS` are accepted; names and list values must be unique. `INTERVAL` is a positive safe integer. `WKST` is a weekday from `MO` through `SU` and defaults to `MO`. Numeric lists must fit the parser's ranges. Minute/hour rules accept no `BY` parts. `BYMONTHDAY` and ordinal `BYDAY` require Monthly or Yearly; `BYYEARDAY` and `BYWEEKNO` require Yearly. Ordinal `BYDAY` cannot combine with `BYWEEKNO`, and `BYSETPOS` requires another `BY` part. -Cron decoding preserves the committed instant and the stored zone spelling, and rejects a non-canonical stored expression. Cron belongs only to the current Host `ScheduleRecord`; the frozen historical Session decoder does not admit it. +Validation precedes enumeration. `SECONDLY`, multiple `BYSECOND` values, and more than 10,080 possible candidates per frequency period are rejected. `COUNT` is 1 through 1,000 and cannot coexist with `UNTIL`; `UNTIL` is an absolute UTC date-time ending in `Z`. Starts and limits use years 0100 through 9999. At most 31 set positions are accepted, each from −366 through −1 or 1 through 366 and within its bounded period. The stricter new-rule authoring profile also rejects `BYSETPOS` when a period has at most one candidate; decoding and resuming an unchanged supported rule use its normal evaluator. -## Historical Session changes +A nonexistent local `DTSTART` is rejected. Later missing local occurrences are skipped without consuming `COUNT`; overlaps choose the earlier instant. `COUNT` counts each actual occurrence once, including when positive and negative set positions select the same occurrence. -Version-1 `schedule/change` events remain decodable as historical Session data. Their create and fold types use `LegacyScheduleRecord`, which admits only After, At, and Every; Daily, Weekly, and Cron belong only to the current Host `ScheduleRecord`. The Host record decoder is separate from the frozen historical decoder. A create record written before titles existed carries no `title`, so the historical decoder admits that absent member while the Host decoder still requires it. Historical events do not populate the storage domain or schedule delivery. Existing reminders in these events require explicit recreation through `schedule_create`; no implicit Session migration or conversion of old `at` records occurs. +Custom RRULE text retains its `DTSTART` zone. The model-facing tools continue to teach and accept RRULE; the shared management API accepts each timing kind explicitly. -```ts type-equiv -/** - * Frozen Session event and fold vocabulary; daily rules belong only to Host storage. - * - * A version-1 event written before titles existed persists no `title` member, so - * `after`, `at`, and `every` decode without one and stay readable. The Host task - * record requires the member and never persists a record without it. - */ -type LegacyScheduleRecord = - | LegacyAfterScheduleRecord - | LegacyAtScheduleRecord - | LegacyEveryScheduleRecord -``` + +## Delivery targets -```ts type-equiv -/** Creates one durable reminder record. */ -interface ScheduleCreateChange { - readonly version: 1 - readonly operation: 'create' - readonly schedule: LegacyScheduleRecord -} -``` +| Target | Delivery behavior | +|---|---| +| `session` | Deliver to one existing Session. Arming checks inside the management FIFO that it exists, is not archived, and is not a delegated child. Delivery rechecks archived destinations. | +| `new_once` | Reserve a Session id before first delivery, create that exact Session when needed, then store `session` and reuse it. Retries and restart keep the reservation. | +| `new` | Create a Session per delivery. Persist `pendingDelivery.targetSessionId` before creation so a failed attempt retries the same Session. | -```ts type-equiv -/** Deletes one currently active reminder. */ -interface ScheduleDeleteChange { - readonly version: 1 - readonly operation: 'delete' - readonly id: ScheduleId -} -``` +An omitted creation target defaults to `new_once`. Adding or replacing a `new` or `new_once` target requires the embedding's Session creation provider. SDK compositions without it reject those requests with `invalid_rule` before saving; existing `session` targets remain available. Creation values `cwd` and `agentPreset` are optional and use Host defaults. A created Session joins the Workspace registered at its directory, if any, and takes the task title while untitled; `new` adds its creation minute in the rule's zone. Join or rename failures are logged without blocking delivery. -```ts type-equiv -/** Records that one active one-shot reminder entered the durable dispatch history. */ -interface OneShotScheduleDispatchChange { - readonly version: 1 - readonly operation: 'dispatch' - readonly id: ScheduleId -} -``` + +## Task management -```ts type-equiv -/** Records one fixed-rate decision and advances directly past missed occurrences. */ -interface EveryScheduleDispatchChange { - readonly version: 1 - readonly operation: 'dispatch' - readonly id: ScheduleId - /** Wall-clock decision time used to select the latest due occurrence. */ - readonly acceptedAt: string -} -``` +All callers use the same `ScheduleCreateRequest`, `ScheduleCatalogEntry`, `ScheduleTiming`, and `ScheduleEditRequest`. Browser-safe types come from `@deepseek-ai/dsh-schedule/client`. There is no Session-bound management surface or second family of type aliases. -```ts type-equiv -/** Durable dispatch shapes supported by the current rule set. */ -type ScheduleDispatchChange = OneShotScheduleDispatchChange | EveryScheduleDispatchChange -``` +| Operation | Behavior | +|---|---| +| `create(request, actorSessionId?, signal?)` | Allocate the id and store title, prompt, typed `timing`, and optional target. | +| `list(request?)` | Read a page; default 100, maximum 500, optional `active` filter and nonnegative `offset`. | +| `catalog()` / `view({ id })` | Read all tasks without a page limit, or one task. | +| `history({ id, limit, before? })` | Read saved deliveries without Session activation; limit is 1 through 100. | +| `edit(request, actorSessionId?, signal?)` | Apply an `update` patch or `delete` atomically by id. | +| `deleteInactive()` | Remove only `ended` tasks in one batch, preserve active and paused tasks, and return `{ deleted }`. An empty set performs no write. | +| `run({ id }, signal?)` | Deliver now through normal admission without changing the scheduled occurrence or lifecycle. | +| `deliveryLimits()` | Read the configured minimum spacing for `new` targets. | -```ts type-equiv -/** Strict version-1 durable Schedule mutation union. */ -type ScheduleChange = ScheduleCreateChange | ScheduleDeleteChange | ScheduleDispatchChange -``` +Remote routes expose `create`, `list`, `catalog`, `view`, `history`, `edit`, `deleteInactive`, `run`, and `deliveryLimits`; the transport wrappers delegate to the same management methods. Remote validation failures use `schedule/input-invalid` with the Schedule input code. Native callers receive `ScheduleInputError`. -The historical decoder and fold reject unknown versions, extra fields, reused ids, and invalid transitions. The event remains indexed in the [persistence catalog](../persistence-catalog.md#schedulechange--log-only). Session history is not the authority for active tasks. +A successful nonempty `deleteInactive` batch emits `schedule/changed` for readers to refresh; it queues no Agent notices. A rejected batch also emits that event so readers discard stale state. A normal failure preserves all rows; an `unknown-state` failure can have removed rows and quarantines the domain until reopening. The failed call rejects instead of reporting a deletion count. -## Active views and management +An update may replace title, prompt, typed timing, target, or activity. Omitted fields keep their values. A changed rule or explicit resume computes a future occurrence at FIFO acceptance; equivalent timing and descriptive edits keep the committed target. A delivered one-shot needs new future timing to resume. Retargeting does not require converting its timing kind. -Tool values combine the stored record with timing derived from the current wall clock. The Host restores the original Session when delivery requires it; listing and deleting tasks do not activate that Session. - -```ts type-equiv -/** Current delivery timing derived from the durable record and wall clock. */ -type ScheduleState = 'scheduled' | 'overdue' -``` - -```ts type-equiv -/** Host-driven delivery resumes the original Session when needed. */ -type ScheduleDeliveryMode = 'host' -``` - -```ts type-equiv -/** Complete model-facing view of one active reminder. */ -type ScheduleView = ScheduleRecord & { - /** Whether the target remains in the future. */ - readonly state: ScheduleState - /** Reminder delivery never leaves the owning session. */ - readonly deliveryMode: ScheduleDeliveryMode -} -``` - -The [tool catalog](../tool-catalog.md#deepseek-aidsh-tool-schedule) owns schemas for `schedule_create`, `schedule_list`, `schedule_delete`, and `schedule_update`, which [`@deepseek-ai/dsh-tool-schedule`](../../packages/schedule/tool-schedule/README.md) contributes to each preset that mounts it; the Host service owns storage and delivery. Create, delete, and update acknowledge the storage-domain write. A Host-wide queue serializes these mutations against due delivery; deleting a task does not remove an already queued message. Model tools address the current Session, while the shared Host create, list, update, and delete methods accept an explicit Session binding. `create` and `update` refuse a Session a delegated child owns with `subagent_session` when its delegation depth is above zero, and delivery cannot reach such a Session. The four model tools refuse a delegated caller in the tool layer, while `list`, `catalog`, `history`, and `delete` still serve that Session. Creation requires a `title` that must be non-empty after trimming and at most 120 characters; a missing, blank, or over-long title is rejected with `invalid_prompt`, and creation never derives one from the instruction. Create and list views carry the stored `title` alongside the instruction, and a stored record whose `title` is missing or invalid is rejected at decode. - -```ts type-equiv -/** Reminder creation selector, shared by the model consumer and Host service. */ -interface ScheduleCreateRequest { - /** Non-empty reminder text. */ - prompt: string - /** Required task name of at most 120 characters, non-empty after trimming; names the card, detail heading, and task lists. */ - title: string - /** Relative one-shot delay in seconds. */ - after_seconds?: number - /** Absolute one-shot target. */ - at?: AtInput - /** Fixed recurrence interval in seconds. */ - every_seconds?: number - /** Daily wall-clock time in an explicit IANA zone. */ - daily?: DailyInput - /** Weekly wall-clock time and explicit ISO weekday set in an IANA zone. */ - weekly?: WeeklyInput - /** Five-field cron expression evaluated in an explicit IANA zone. */ - cron?: CronInput -} -``` - -```ts type-equiv -/** Session-scoped task list, without Agent activation. */ -interface ScheduleListRequest { - /** Original Session binding. */ - sessionId: SessionId -} -``` - -```ts type-equiv -/** Delete request identifying a task within its original Session binding. */ -interface ScheduleDeleteRequest extends ScheduleListRequest { - /** Task to remove. */ - id: ScheduleId -} -``` - -```ts type-equiv -/** Successful `schedule_delete` value, including the non-mutating not-found result. */ -type ScheduleDeleteResult = - | { readonly id: ScheduleId; readonly deleted: true } - | { readonly id: ScheduleId; readonly deleted: false; readonly code: 'schedule_not_found' } -``` - -```ts type-equiv -/** Successful Host-wide removal of every ended task, whether or not any remained. */ -interface ScheduleDeleteInactiveResult { - /** Ended task rows this call removed; zero when the Host held none. */ - readonly deleted: number -} -``` - -## Web catalog - -The Remote `schedule.catalog()` method returns active and inactive Host tasks with their original Session bindings, ordered by `scheduledAt` ascending and then lexicographically by `id`. It reads only the Schedule domain, without activating Sessions or reading their history. Browser consumers receive this browser-safe type: - -```ts type-equiv -/** Durable Session inbox delivery acknowledgment, not model execution completion. */ -interface ScheduleDeliveryReceipt { - /** Canonical UTC target of the delivered occurrence. */ - readonly scheduledAt: string - /** Canonical UTC time sampled after Session persistence acknowledged delivery. */ - readonly deliveredAt: string - /** Identity of the delivered message, shared by tasks in one recurring batch. */ - readonly messageId: MessageId -} -``` - -```ts type-equiv -/** Browser-safe retained reminder with its original Session binding. */ -type ScheduleCatalogEntry = ScheduleRecord & { - /** Session receiving this reminder when it becomes due. */ - readonly sessionId: SessionId - /** Inactive reminders remain visible but never schedule another delivery. */ - readonly status: 'active' | 'inactive' - /** Most recent durably acknowledged inbox delivery, when available. */ - readonly lastDelivery?: ScheduleDeliveryReceipt -} -``` - -The Remote `schedule.list({ sessionId })`, model `schedule_list`, and Session-header catalog return only active tasks. A model view's derived timing `state` remains distinct from stored lifecycle `status`. Deletion uses `schedule.delete({ sessionId, id })` with the entry's original binding; a mismatched binding returns not found. Model tools supply the current Agent's Session, whereas the global user interface supplies the selected task's binding. The binding check alone does not establish caller authorization. `schedule.deleteInactive()` removes every ended (inactive) task across Sessions, with the saved delivery records each row carries; on success it answers `{ deleted }` with the count it removed; a normal failed batch rejects with nothing removed; an `unknown-state` failure may have removed rows and quarantines the Host schedule domain, so later schedule operations reject until it is reopened. Any rejection announces `schedule/changed`, and clients then re-read. The Automation tasks page's bulk cleanup uses it. An ended task never arms a timer, so the removal recomputes no target. The payload-free `schedule/changed` event invalidates client lists; reconnecting clients fetch current state again. - -The shipped Web composition mounts `ui-schedule` with the Host capability. The [client package](../../packages/client/ui-schedule/README.md) owns the catalog, empty state, and deletion controls. The page separately filters all, active, and inactive tasks, retains inactive details and an original-Session control in the detail tab strip, and requires explicit confirmed deletion. The Rules and Records tabs separate task settings from lazily paged saved receipts. Neither a receipt nor inactive status confirms model execution. +`expectedUpdatedAt` is an optional optimistic comparison. A string compares with the saved revision; explicit `null` compares with an absent revision. Mismatch returns `schedule_conflict`. An edit of a row without a revision creates one; later revisions advance monotonically even if the clock rolls back. Cancellation is checked before the write begins, and a started durable write is not rolled back. + ## Timing edits -`schedule.update({ sessionId, id, expected, change })` edits an active task without activating its Session. `expected` is the complete observed `ScheduleRecord`, not a catalog entry with extra metadata. The Host compares it to the current record inside the same FIFO used by dispatch and deletion. Normal delivery can advance the target during editing; that stale snapshot returns `schedule_conflict` instead of overwriting the current rule. Missing or mismatched bindings return `schedule_not_found`, and inactive tasks return `schedule_ended`. - -```ts type-equiv -/** Timing-only edit; it may select a different recurrence kind than the stored record, and one-shot targets use an absolute `at`. */ -type ScheduleTimingChange = - | { readonly kind: 'at'; readonly at: AtInput } - | { readonly kind: 'every'; readonly every_seconds: number } - | { readonly kind: 'daily'; readonly daily: DailyInput } - | { readonly kind: 'weekly'; readonly weekly: WeeklyInput } - | { readonly kind: 'cron'; readonly cron: CronInput } -``` - -```ts type-equiv -/** Compare-and-update request within the original Session binding. */ -interface ScheduleUpdateRequest extends ScheduleDeleteRequest, ScheduleUpdateContent { - /** Complete record observed when editing began, including the committed target. */ - readonly expected: ScheduleRecord - /** New timing; its kind may differ from the stored record's kind, and an omitted value keeps the committed target. */ - readonly change?: ScheduleTimingChange -} -``` - -```ts type-equiv -/** Successful current record, non-mutating lookup/conflict failure, or invalid name/instruction/timing. */ -type ScheduleUpdateResult = - | { readonly id: ScheduleId; readonly updated: boolean; readonly record: ScheduleRecord } - | ScheduleUpdateMiss - | ScheduleToolError -``` - -A changed Daily rule computes its first strictly future target using the saved local time and zone semantics. A changed Cron rule canonicalizes its expression and computes its first strictly future target under the same local-date, gap, and earlier-overlap rules. A changed Every interval starts a new anchor at accepted save time plus that interval. An After or At task can receive a different absolute target as an At record with the same id. These operations preserve the stored `title`, the prompt, original Session binding, lifecycle status, and all saved receipts. A change may also select a different recurrence kind, which recomputes the target from the new rule with the same id, title, prompt, Session binding, status, and saved receipts. An equivalent normalized rule returns `updated: false` with its unchanged record; it does not rewrite storage, reset the target, or emit a change event. A differently spelled but equivalent Cron expression is such a no-op, because the comparison uses the canonical expression and the canonical zone. - -Input validation uses existing timing errors. A changed absolute target must still be future when its FIFO slot runs. The successful task put precedes the change notification and timer recomputation. Storage and lifecycle failures reject; cancellation is checked after queue and initialization waits but cannot roll back an in-flight write. One-shot records retain a UTC instant rather than the editing form's IANA zone. Timing edits append no historical Session event: the model reaches the same in-place update through `schedule_update`, which compares the record it read with the stored one instead of deleting and recreating the task. +The `timing` discriminant selects exactly its matching payload, for example `{ kind: "cron", cron: { expression: "0 9 * * 1-5", time_zone: "Asia/Shanghai" } }` or `{ kind: "rrule", rrule: "DTSTART:20990101T090000Z\nRRULE:FREQ=DAILY" }`. Other selectors use `after_seconds`, `at`, `every_seconds`, `daily`, or `weekly`. Invalid combinations are refused before persistence. The UI saves typed Cron/RRULE input through this same API and preserves untouched timing. + ## Saved delivery records -`schedule.history({ sessionId, id, limit })` reads saved receipts without activating a Session. The explicit limit is a safe integer from 1 through 100. Pages follow reverse append order, not wall-clock sorting; the optional message-id cursor excludes the oldest record from the preceding page. New arrivals do not shift that cursor. A missing task or wrong Session binding returns `schedule_not_found`; an unknown cursor returns `delivery_cursor_not_found`, not an empty successful page. +A receipt records `scheduledAt`, `deliveredAt`, `messageId`, and `targetSessionId`; it acknowledges a durable Session inbox write, not model completion. A saved record may also have its immutable sent `prompt`. Old receipts without a target id use their resolved reusable destination before any retargeting edit, so a later target cannot rewrite their history. A receipt without either an explicit destination or a known reusable target rejects decoding; a new default reservation cannot establish a historical destination. -```ts type-equiv -/** Saved inbox delivery with its immutable sent prompt when recorded by this Host. */ -interface ScheduleDeliveryRecord extends ScheduleDeliveryReceipt { - /** Prompt sent for this occurrence; unavailable for legacy receipts. */ - readonly prompt?: string -} -``` +New tasks start with known empty history. An old row without `deliveryHistory` exposes its latest receipt, if present, and sets `earlierRecordsUnavailable: true`; it does not invent lost history or prompt snapshots. An omitted `earlierRecordsPruned` reads as false. Duplicate message ids or disagreement between the latest saved record and `lastDelivery` reject decoding. -```ts type-equiv -/** Explicitly bounded saved-delivery query within one Session binding. */ -interface ScheduleDeliveryHistoryRequest extends ScheduleDeleteRequest { - /** Required safe-integer page size from 1 through 100. */ - limit: number - /** Message identity of the oldest entry in the previous page; excluded from this page. */ - before?: MessageId -} -``` - -```ts type-equiv -/** Configured limits applied when appending one task's delivery receipt. */ -interface DeliveryRetentionBounds { - /** Retained window in days, measured back from the acknowledgment being appended. */ - readonly days: number - /** Maximum retained records per task; the newest survive. */ - readonly records: number -} -``` - -```ts type-equiv -/** Newest-first saved deliveries, or a non-mutating task/cursor lookup failure. */ -type ScheduleDeliveryHistoryResult = - | { - readonly id: ScheduleId - readonly records: ScheduleDeliveryRecord[] - /** Whether earlier delivery records may be unavailable; missing receipts are never reconstructed. */ - readonly earlierRecordsUnavailable: boolean - /** True only after an append removed saved records; absent legacy evidence is false. */ - readonly earlierRecordsPruned: boolean - /** Current Host retention configuration, also used by the delivery writer. */ - readonly retention: DeliveryRetentionBounds - /** Oldest returned message identity, present only when older saved records remain. */ - readonly nextBefore?: MessageId - } - | { readonly id: ScheduleId; readonly code: 'schedule_not_found' | 'delivery_cursor_not_found' } -``` - -New tasks initialize an empty history. Older task rows without history expose only their existing latest receipt, mark earlier records unavailable, and are not rewritten by reads. Future acknowledgments preserve that receipt and append actual new receipts with instruction snapshots. Lost history and missing legacy instruction snapshots are never reconstructed. The same task-row write commits history, latest receipt, status, and next target; explicit task deletion stops future delivery, removes the task row together with its saved receipts, and takes it out of `list` and `catalog`; conversation messages are unaffected. Saved delivery records are pruned on append to the configured `deliveryHistoryDays` window, measured back from each receipt's `deliveredAt`, and to the `deliveryHistoryRecords` cap; the appended latest receipt always survives, and a pruned window marks earlier records unavailable. Pagination bounds returned record count rather than storage size or instruction bytes. +History follows append order despite clock rollback. Acknowledgment appends and prunes in the same task commit, keeping at most 200 records and 30 days by default while retaining the latest receipt. Query pages are newest first and use an exclusive message-id cursor. Hard deletion removes the task and its history without removing already queued Session messages. + ## Host delivery -The Host reads persisted tasks at startup and sets its timer to the earliest active target. Inactive tasks remain queryable but never schedule another delivery. At delivery it resolves the original Session, including cold Sessions, through `schedule/resolve-agent`. The embedding owns activation: the SDK handler waits for initialization and retains its Session handle and model options; without a handler, the Web Session controller restores the Session. The composition waits for its activation provider before starting Schedule. After restoration it samples the wall clock again and excludes members that are no longer due after a rollback; those tasks retain their timer obligation. Neither a Goal nor a separate Run completion record participates in dispatch. +One Host timer drives active tasks. Runtime and management writes share one FIFO. Existing and reserved Sessions resolve through `schedule/resolve-agent`, so the embedding owns activation and the injected Web controller is the fallback. Reused-Session tasks hold their execution slot until the target Agent becomes idle; intervening occurrences coalesce. A `new` target permits executions beside one another. Due recurring records targeting the same existing Session share one message; `after` and `at` deliver separately. -Plugin-sourced `followup()` synchronously appends the message to the Session inbox. After a successful Session flush, one task-record put appends a saved delivery with its instruction snapshot and stores the latest `ScheduleDeliveryReceipt` together with the one-shot's `inactive` status or the recurring task's next target and status. Recurring tasks in the same batch share the receipt's `messageId`; each receipt retains that task's delivered occurrence time. Delivery never steers or cancels the current turn and does not wait for model completion. +Timed and manual deliveries obey a per-task minimum interval of 60 seconds. `newSessionIntervalSeconds` can raise it for `new` targets, up to one week. The floor uses the last occurrence when the saved successor preserves the interval, otherwise the last acknowledgment, so delivery latency does not move the rule's anchor. Reads expose `executionActive` and `deliveryFloorEndsAt` only while applicable. -A failure to resolve the Session, enqueue the message, or confirm persistence leaves the task stored and reports a Host warning. A later management change or Host restart retries it. Session persistence and the task put are not atomic across stores. A crash after inbox persistence but before the task put can repeat delivery; the receipt does not close this gap. Schedule provides no model-result acknowledgement, execution cancellation, or external notification channel. +Session inbox persistence precedes the task receipt write, so a crash between stores can repeat a delivery. The Host must be running. An active task targeting a Session contributes archive-admission activity; an archive stop deletes those active tasks. + +After a committed management change, Schedule queues a best-effort notice to each involved loaded Agent except the actor. Notices join the next model step without opening a turn, and their Session I/O does not hold the management/delivery queue. New-per-delivery Sessions are not accumulated in involvement metadata. + + +## Historical Session changes + +Historical version-1 `schedule/change` events retain the frozen `LegacyScheduleRecord` types: `after`, `at`, and `every`, including old optional titles. They remain recorded Session data without a Schedule interpreter, warning hook, importer, or timer. Existing Host tasks in `schedule.json` still use the normal decoder and evaluator. @@ -457,64 +149,87 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.schedule` — `ScheduleService` -Shared management service; reads, deletion, and timing edits never activate a Session. +Shared management service; reads and management writes never activate a Session, and only delivery creates or resumes one. -`sessionPersistence` is a load-order requirement rather than a directly called service: a delivery commits only when `ctx.sessions.flush()` reports that a `session/flush` listener participated, and the persistence backend providing this service is the plugin that registers that listener. +`sessionPersistence` supplies header-only target validation and the `session/flush` listener that acknowledges durable inbox delivery through `ctx.sessions.flush()`. ```ts cordis-catalog +/** Read effective delivery limits without loading or activating a task. + * @returns The configured minimum spacing between deliveries that each create a Session, in seconds. + */ +@Remote('deliveryLimits') deliveryLimits(): { readonly newSessionIntervalSeconds: number } + /** - * Create a reminder bound to the caller-selected Session without activating it. + * Create one task with a Host-generated identity for a human Remote caller. + * @param request - Title, prompt, recurrence, and delivery destination. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The stored task. Cancellation does not roll back an in-flight write. + */ +@Remote('create') async remoteCreate(request: ScheduleCreateRequest, signal?: AbortSignal): Promise + +/** + * Create one task and record the acting Agent's Session as involved; the Remote form omits that Session. * - * The request must supply a title; a missing, blank-after-trim, or over-long - * title rejects with `invalid_prompt` instead of deriving one from the prompt. - * A Session a delegated child owns rejects with `subagent_session`, because delivery - * can never reach it: the child is one whose delegation depth is above zero. - * The record is built from the clock reading taken before the request joins the - * serialized queue, so a create that waits behind a longer operation keeps its - * request-time anchor and may already be due when the queue reaches it. - * @param sessionId - Original Session receiving the reminder. - * @param request - Validated tool selector, required title, and reminder content. - * @param signal - Optional cancellation checked before persistence begins, including after FIFO waits. - * @returns The durably stored schedule. Cancellation does not roll back an in-flight write. + * The record is built from the clock reading taken before the request joins the serialized queue. A `session` + * target must exist and must not belong to a delegated child; a `new_once` target reserves its Session identity. + * @param request - Title, prompt, recurrence, and delivery destination. + * @param actorSessionId - Session of the acting Agent, or undefined for a human caller. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The stored task. Cancellation does not roll back an in-flight write. */ -async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: AbortSignal): Promise +async create( request: ScheduleCreateRequest, actorSessionId?: SessionId, signal?: AbortSignal, ): Promise /** - * Read the selected Session's active tasks without resuming its Agent. - * @param request - Session whose task list is requested. - * @returns Persisted reminders in storage order. + * Read one page of Host tasks without activating target Sessions. + * @param request - Optional activity filter, page size, and offset. + * @returns The requested page and total matching task count. */ -@Remote('list') async list(request: ScheduleListRequest): Promise +async list(request: ScheduleListRequest = {}): Promise /** - * Read all active and inactive Host reminders with their original Session bindings. - * A deleted reminder has no row, so it is absent here. - * Does not activate Sessions or read Session history. - * @returns Reminders ordered by scheduledAt ascending, then lexicographically by id. + * Remote form of the shared Host-wide list. + * @param request - Optional activity filter, page size, and offset. + * @returns The requested page and total matching task count. + */ +@Remote('list') async remoteList(request: ScheduleListRequest): Promise + +/** + * Read every Host task without a page bound or Session activation. + * @returns All tasks, active first, with target and execution metadata. */ @Remote('catalog') async catalog(): Promise /** - * Read saved inbox deliveries without activating or reading the original Session. - * The task's own row supplies its binding, so its records stay readable through this lookup. - * @param request - Session binding, task identity, explicit limit, and optional exclusive message cursor. - * @returns Newest-first deliveries in append order, or a task/cursor lookup failure. - * @throws ScheduleInputError when limit is not a safe integer from 1 through 100. + * Read one task without activating its target Sessions. + * @param request - Task identity. + * @returns The task, or a non-mutating miss. */ -@Remote('history') async history(request: ScheduleDeliveryHistoryRequest): Promise +@Remote('view') async view(request: ScheduleViewRequest): Promise /** - * Delete one task belonging to the selected Session, leaving queued messages intact. - * - * The row is removed: the task no longer schedules, leaves `list` and `catalog`, and its - * saved delivery records go with it. A task bound to a Session a delegated child owns - * stays deletable even though creation and timing edits refuse that binding, so a task - * stored before that rule existed remains removable. - * @param request - Session and exact task identity. - * @param signal - Optional cancellation checked before persistence begins, including after FIFO waits. - * @returns Whether that Session owned a deleted task. Cancellation does not roll back an in-flight write. + * Read one page of saved deliveries without activating or reading a target Session. + * @param request - Task identity, explicit page size, and optional exclusive cursor. + * @returns Newest-first saved deliveries, or a task/cursor lookup failure. */ -@Remote('delete') async delete(request: ScheduleDeleteRequest, signal?: AbortSignal): Promise +async history(request: ScheduleDeliveryHistoryRequest): Promise + +/** + * Remote form of the target-based {@link ScheduleService.history}; an invalid limit rejects with + * `schedule/input-invalid`. + * @param request - Task identity, explicit limit, and optional exclusive message cursor. + * @returns Newest-first deliveries in append order, or a task/cursor lookup failure. + */ +@Remote('history') async remoteHistory(request: ScheduleDeliveryHistoryRequest): Promise + +/** + * Deliver one task now without consuming or moving its scheduled occurrence; an archived destination Session rejects + * with `schedule/target-archived`. + * @param request - Task identity. + * @param signal - Cancellation checked after entering the delivery transaction and before delivery. + * @returns Task state after Session persistence acknowledged the delivery, `schedule_execution_pending` while + * another execution of the task is queued, running, or inside its delivery floor, or a non-mutating miss. + */ +@Remote('run') async run(request: ScheduleRunRequest, signal?: AbortSignal): Promise /** * Delete every ended Host task, leaving active tasks armed. @@ -526,27 +241,32 @@ async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: Abor * failure rejects with every listed row still stored, while a backend * `unknown-state` failure may have removed rows and quarantines the Host * domain, so later schedule operations reject until the domain is reopened. - * Every rejection announces `schedule/changed` because it does not establish + * A successful nonempty batch emits `schedule/changed` without Agent notices. + * A rejected batch announces `schedule/changed` because it does not establish * which rows landed, and clients then re-read the catalog. * @returns Count of removed rows; zero when the Host held no ended task. */ @Remote('deleteInactive') async deleteInactive(): Promise /** - * Update the name, instruction, and timing of an active task within the original Session - * binding without activating the Session or changing saved deliveries. - * - * Each supplied field replaces its stored value; an omitted field keeps it. A name or - * instruction change alone does not reset the committed target. A Session a delegated - * child owns returns the non-mutating `subagent_session` result, so an edit cannot - * re-arm a task bound to a Session delivery can never reach, and the Web editor can - * explain the refusal through the ordinary result it already renders. - * @param request - Task binding, complete observed record, and any combination of timing, name, and instruction. - * @param signal - Cancellation checked after domain readiness and FIFO waits, before persistence begins. - * @returns The committed record, unchanged record for a no-op, or a non-mutating input/lookup/conflict/refusal result. - * Storage and lifecycle failures reject; cancellation after a write starts does not roll it back. + * Update or delete one task for a human Remote caller; an invalid patch rejects with `schedule/input-invalid`. + * @param request - Task identity and one update or delete operation. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The updated task, the deletion outcome, or a non-mutating miss or conflict. */ -@Remote('update') async update(request: ScheduleUpdateRequest, signal?: AbortSignal): Promise +@Remote('edit') async remoteEdit(request: ScheduleEditRequest, signal?: AbortSignal): Promise + +/** + * Update or delete one task and record the acting Agent's Session as involved; the Remote form omits that Session. + * + * An update applies every patch field in one write and recomputes the next occurrence when the rule changes or + * the task resumes. A supplied `expectedUpdatedAt` that differs from the stored value returns `schedule_conflict`. + * @param request - Task identity and one update or delete operation. + * @param actorSessionId - Session of the acting Agent, or undefined for a human caller. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The updated task, the deletion outcome, or a non-mutating miss or conflict. + */ +async edit( request: ScheduleEditRequest, actorSessionId?: SessionId, signal?: AbortSignal, ): Promise ``` Types: [SessionId](core.md) diff --git a/docs/subsystems/schedule.zh.md b/docs/subsystems/schedule.zh.md index 320ae8e743..7e71776dcb 100644 --- a/docs/subsystems/schedule.zh.md +++ b/docs/subsystems/schedule.zh.md @@ -2,448 +2,140 @@ [English](schedule.md) | 中文 -Schedule 独立于 Session 的加载状态存储提醒,并将其投递到原 Session。本页记录 [`types.ts`](../../packages/schedule/schedule/src/types.ts) 中的持久与模型可见类型;[包 README](../../packages/schedule/schedule/README.zh.md) 负责组合方式与提醒文本格式。 +Schedule 独立于 Session 的激活状态存储宿主任务。同一管理 API 按 id 操作任务,同一求值器处理七种权威时间类型:`after`、`at`、`every`、`daily`、`weekly`、`cron` 和 `rrule`。目标可以复用已有 Session、创建一个 Session 后复用,或每次投递创建 Session。[包 README](../../packages/schedule/schedule/README.zh.md) 负责组合与提醒格式;完整值类型和请求类型以 [`types.ts`](../../packages/schedule/schedule/src/types.ts) 为准。 -## 持久记录 + +## 持久任务 -`ScheduleId` 是全局唯一的[品牌化 ID](core.zh.md#branded-ids)。版本 1 的 `schedule` storage domain 的 `tasks` 表将每条 `ScheduleRecord` 与原始 `sessionId` 绑定,并存储 `status: 'active' | 'inactive'` 和可选的 `lastDelivery`。缺少状态的记录规范化为 `active`,不扫描或重建历史 Session。创建时将目标规范化为 RFC 3339 UTC `scheduledAt`;`after` 保留提交的延迟,`every` 保留固定间隔,`daily` 与 `weekly` 保留规范化后的本地 `time` 及显式 `timeZone`,`cron` 保留规范化后的五字段 `expression` 及显式 `timeZone`。每日、每周与 cron 记录解码保留已提交时点及已存储的时区拼写。已存储的任务记录声明必填的 `title`,即任务界面显示的短名称;创建时必须提供该字段,且绝不从指令派生。任何已存储记录都不得缺少标题:`title` 缺失、去除首尾空白后为空、带首尾空白或超过 120 个字符的已存储记录都会以 `ScheduleLogError` 拒绝持久化解码;schedule domain 未声明备份并跳过的策略,因此一条这样的已存储任务会拒绝整个 domain 的打开,而不是被丢弃。仅显式删除会移除任务;此前已物理删除的任务不会被恢复或虚构。 +插件 README 拥有当前 [v2 任务 schema、v1 默认值与持久 JSON 示例](../../packages/schedule/schedule/README.zh.md#storage-format)。领域保留名称、路由和整单元布局。七种时间类型均保持权威性;规范化保留已提交发生时点,不将 Cron 转为 RRULE。 -```ts type-equiv -/** Durable one-shot reminder created from a positive delay. */ -interface AfterScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a delayed one-shot reminder. */ - readonly kind: 'after' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Positive safe-integer delay accepted at creation. */ - readonly afterSeconds: number - /** Four-digit-year RFC 3339 UTC target. */ - readonly scheduledAt: string -} -``` +损坏的存储、无效行、与任务身份不一致的键及不支持的版本在任务激活前拒绝。打开失败不改变介质。文件不存在时从空域开始。目标 Session 缺失的任务仍在管理界面中可见;读取任务从不激活其 Session。 -```ts type-equiv -/** Durable one-shot reminder created from an absolute instant. */ -interface AtScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for an absolute one-shot reminder. */ - readonly kind: 'at' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Four-digit-year RFC 3339 UTC target. */ - readonly scheduledAt: string -} -``` + +## 存储版本 -```ts type-equiv -/** Durable fixed-rate reminder aligned to creation or its most recent interval edit. */ -interface EveryScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a fixed-rate recurring reminder. */ - readonly kind: 'every' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Fixed safe-integer interval, never below one minute. */ - readonly everySeconds: number - /** Next anchor-aligned occurrence while active, or final occurrence when inactive. */ - readonly scheduledAt: string -} -``` +README 定义[任务何时升级](../../packages/schedule/schedule/README.zh.md#storage-format)、SQLite 不变的物理 schema、修改成本以及未来兼容 v3。`compatibleVersions` 允许旧单元版本戳进入当前解码;正常编辑与投递持久化当前行。读取保持存储不变。共享的[领域版本策略](storage.zh.md#domain-versioning)同时适用于 JSON 和 SQLite。 -```ts type-equiv -/** Durable daily wall-clock reminder; gaps skip a date and overlaps use the earlier instant. */ -interface DailyScheduleRecord { - /** Globally unique task identity. */ - readonly id: ScheduleId - /** Rule discriminator for a daily wall-clock reminder. */ - readonly kind: 'daily' - /** Required stored task name; already trimmed, non-empty, and at most 120 characters. */ - readonly title: string - /** Trimmed reminder content supplied at creation. */ - readonly prompt: string - /** Local time normalized to HH:mm:ss.SSS. */ - readonly time: string - /** Explicit IANA zone; equivalent timing edits retain the stored spelling. */ - readonly timeZone: string - /** Committed next UTC instant while active, or final occurrence when inactive. */ - readonly scheduledAt: string -} -``` + +## 重复规则 -```ts type-equiv -/** One-shot task variants. */ -type OneShotScheduleRecord = AfterScheduleRecord | AtScheduleRecord -``` +[`dsh-util-time`](../../packages/util/time/README.zh.md) 负责可复用的 `Cron`、`RRule` 解析及有界发生时点计算。两种解析值均暴露其权威表达式、时区、`next(after)` 和 `resolve(scheduledAt, acceptedAt)`。解析器返回接受值或拒绝原因;Schedule 将原因映射为自身输入错误,并负责记录验证、准入限制、持久化与投递。 -```ts type-equiv -/** Recurring Host task variants. */ -type RecurringScheduleRecord = EveryScheduleRecord | DailyScheduleRecord | WeeklyScheduleRecord | CronScheduleRecord -``` +每个已存 `scheduledAt` 都是带毫秒精度、年份为 0001 至 9999 的规范 RFC 3339 UTC 时刻。解码不会根据当前时区数据重新计算它。只追赶最新一次的策略保留该已提交下界,投递最新到期时点一次,再提交第一个未来时点。规则耗尽后任务以 `ended` 状态保留。 -```ts type-equiv -/** Reminder rule and target, stored with its original Session binding. */ -type ScheduleRecord = OneShotScheduleRecord | RecurringScheduleRecord -``` +| 类型 | 权威时间字段 | +|---|---| +| `after` | 正整数 `afterSeconds` 和已提交的一次性 UTC 目标。 | +| `at` | 已提交的一次性 UTC 目标。输入接受显式偏移时刻,或本地日期、时间与显式时区。 | +| `every` | 不小于 60 的整数 `everySeconds`;发生时点始终对齐已提交的间隔锚点。 | +| `daily` | `HH:mm:ss.SSS` 形式的本地 `time` 与显式 `timeZone`。 | +| `weekly` | Daily 字段加非空、唯一、升序的 ISO `weekdays` 集合,周一为 1、周日为 7。 | +| `cron` | 规范五字段 `expression` 与显式 `timeZone`。 | +| `rrule` | `rrule` 中一条规范 `DTSTART` 和一条 `RRULE` 行;`DTSTART` 提供锚点与时区。 | +本地日历规则跳过不存在的墙钟时间,并在重叠时选择较早的时刻。固定间隔保留经过时间的含义。一次性延迟可短于一分钟;首次投递之后仍适用单任务最小投递间隔。 + + ## 绝对时间输入 -`at` 选择器可以是严格且带偏移量的 RFC 3339 字符串,也可以是精确的本地日历对象。本地形式让这种解释在工具边界保持显式: - -```ts type-equiv -/** Structured local-calendar input accepted by creation and timing edits. */ -interface LocalAtInput { - /** Four-digit ISO calendar date. */ - readonly date: string - /** Local wall-clock time with optional one-to-three digit milliseconds. */ - readonly time: string - /** Explicit UTC or IANA Area/Location zone. */ - readonly time_zone: string -} -``` - -```ts type-equiv -/** Absolute selector accepted by creation and timing edits. */ -type AtInput = string | LocalAtInput -``` - -随发行版交付的 Web 组合挂载 `schedule` 服务与 `ui-schedule` 任务页面。时钟读数与四个提醒工具归 preset 所有:`standard`、`cordis` 与 `ptc` 一同声明 `time-context` 与 `@deepseek-ai/dsh-tool-schedule`,`minimal` 两者都不声明。这三个 preset 中的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,且每个工具都以 `subagent_session` 拒绝被委派的调用方,因此被委派的子 agent 既看不到这些工具,其调用也不会被接受。当 open turn 只有一个无歧义的浏览器时区时,Time-context 会告诉模型按该请求本地时区解释未明确限定时区的自然语言日期和时间;浏览器时区记录混合或缺失时,则告诉模型询问用户。该指引不是持久 Session 默认值:模型仍必须在字符串形式中传入偏移量,或在本地形式中传入 `time_zone`;Schedule 绝不会读取浏览器、Session、进程或模型上下文。 - -Schedule 会拒绝无效偏移量与时区、不带偏移量的字符串、非未来目标,以及落在夏令时缺口内的本地时间。遇到夏令时重叠时,会选择第一次出现的较早时点。创建成功后只存储规范化后的 UTC `scheduledAt`,因此回放绝不依赖环境时区状态。 +`at` 选择器接受带显式 `Z` 或数字偏移的 RFC 3339 时刻,或 `{ date, time, time_zone }`。本地日期使用 `YYYY-MM-DD`;本地时间使用 `HH:mm:ss`,可带一至三位小数秒。歧义或不存在的日历值通过共享时间工具验证。新的绝对目标必须严格位于未来且可表示。 -## 每日本地钟表时间输入 +## 每日与每周输入 -`daily` 是与 `after_seconds`、`at`、`every_seconds`、`weekly` 和 `cron` 互斥的创建选择器之一。例如,`daily: { time: '23:00:00', time_zone: 'Asia/Shanghai' }` 选择该时区每个符合条件的本地日期的 23:00。对象必须精确包含以下字段,不包含日期、偏移量或间隔: +Daily 输入提供 `{ time, time_zone }`;Weekly 另加显式 `weekdays`。创建时选择第一个严格位于未来的实际发生时点。追赶选择最新实际到期时点,并推进到之后匹配的本地日期。等价编辑保留已存 IANA 别名和固定 UTC 目标,包括毫秒。 -```ts type-equiv -/** Daily local-time selector accepted by creation and timing edits. */ -interface DailyInput { - /** Local HH:mm:ss time with optional one-to-three fractional digits. */ - readonly time: string - /** Explicit UTC or IANA Area/Location zone. */ - readonly time_zone: string -} -``` + +## 固定频率输入与追赶 -创建时要求 `HH:mm:ss` 及可选的一至三位小数秒,拒绝闰秒和 `24:00`,将显式 IANA 时区规范化,并以 `HH:mm:ss.SSS` 存储 `time`。首个 `scheduledAt` 严格晚于创建时刻。不存在的本地时间或整个日期被跳过;重叠时间选择较早时点,每个本地日期一次。若较早时点已过去,较晚的重复时点不符合条件。仅 UTC 目标年份受 0001–9999 范围约束;UTC 范围边缘的本地日期可以落在第 0 年或第 10000 年。 - -已保存的下一目标是已提交的 UTC 时点。宿主解码器与重启保留该时点,不依据时区规则重新解析;规范名称变化后,有效的已存储时区别名仍可读取。后续目标使用宿主当前的 IANA 数据。下一目标必须晚于投递判断时刻,并且其本地日期晚于所选发生时点的日期。没有可表示的未来 UTC 目标时,创建以 `time_out_of_range` 失败。 - -## 固定速率输入与补偿 - -`every_seconds` 是至少 60 秒的安全整数间隔,与创建时间对齐。它衡量经过的时间,而不是每日本地钟表时间:发生偏移量变化时,`every_seconds: 86400` 不能替代 `daily`。协议不提供共享冷却时间或跨记录准入规则;下文描述的 cron 选择器是钟表时间语义,不是固定速率间隔。 - -宿主启动时若 Every、Daily、Weekly 或 Cron 记录已逾期,只发送最新一次到期发生时点。Every 推进到投递判断时刻之后第一个与当前间隔起算点对齐的目标;Daily、Weekly 和 Cron 遵循上文与下文的本地日期规则。错过的发生时点不会累积。若没有可表示的下一 UTC 目标,投递后保留未运行记录及最近一次回执。 - -一次性提醒各自产生一条 follow-up。同一次扫描中属于同一 Session 的到期重复记录共用由 `renderRecurringReminderBatchFraming` 渲染的一条 follow-up,每条记录各包含最新一次触发。一分钟下限仅适用于固定速率间隔;投递不等待目标 Agent 空闲。 +Every 输入提供 `every_seconds`。新间隔从接受时间开始;修改间隔会在编辑被接受时建立新锚点。不变的间隔或名称/指令编辑保留原锚点。停机后合并错过的间隔,而非逐次重放。 -## Cron 钟表时间输入 +## Cron 输入 -`cron` 是互斥的创建选择器之一。它的对象只携带严格的标准五字段 Vixie 表达式 `minute hour day-of-month month day-of-week` 和显式 IANA 时区,例如 `cron: { expression: '*/15 9-17 * * 1-5', time_zone: 'Asia/Shanghai' }`。字段取值范围如下: +Cron 输入提供 `{ expression, time_zone }`。五个数字字段依次为分钟、小时、月内日期、月份和星期。支持的原子形式为 `*`、单值、闭区间、星号或区间步长,以及逗号分隔列表。周日接受 0 或 7,规范为 0。拒绝名称、宏、秒字段和单值后跟步长的形式。 -| 字段 | 取值范围 | 说明 | -|---|---|---| -| minute | 0-59 | | -| hour | 0-23 | | -| day-of-month | 1-31 | | -| month | 1-12 | | -| day-of-week | 0-7 | `0` 和 `7` 都表示周日。 | +Cron 保留 Vixie 的日期匹配方式:两个日期字段都受限时,月内日期**或**星期任意一个匹配即可;任一字段以 `*` 开头(包括带步长的星号)时,两组匹配值均须匹配。规范化保留此差异。搜索受一个 400 年公历周期和四位 UTC 年份范围约束。启用时拒绝没有可表示未来时点的规则。 -每个字段接受 `*`、单个值、`a-b` 范围、`n >= 1` 的 `*/n` 与 `a-b/n` 步长,以及由这些形式组成的逗号分隔列表。其他写法一律以 `invalid_rule` 拒绝,且错误信息会指出违规字段:`L`、`W`、`#` 运算符,`JAN`/`MON` 名称,`@daily` 风格宏,带秒字段的六字段表达式,超出范围的值、反向范围、零步长和空字段。由于该方言只有五个字段,最小间隔为一分钟;亚分钟级调度仍然不受支持。 +Cron 记录从不转换为 RRULE。读取、描述性编辑、重新指定目标和重启均保留其已存表达式与时区作为权威来源。自定义编辑器接受五字段 Cron 表达式,并显示显式时区选择器。 -创建时会先规范化表达式再存储。规范化会把每个字段展开为匹配值集合,再确定性地重新编码该集合:重复值合并,相邻的值与范围合并,均匀步长写为 `a-b/n`,而以 `*` 开头的字段写为星号步长(匹配全部取值时写 `*`,否则写最宽的星号步长并追加其余取值),步长 `1` 被移除,周日统一写为 `0`。不以 `*` 开头的字段绝不会变成星号步长。保留每个字段的星号标志,正是下文 day-of-month/day-of-week 规则在存储的表达式上仍与 Vixie 一致的原因。持久化解码器会拒绝非规范化的已存储表达式。 + +## RRULE 输入 -首个目标是该时区内本地日期与时间匹配的第一个严格未来时点。它复用 Daily 与 Weekly 的本地时间解析:不存在的本地时间被跳过,重叠时间每个日期只取较早一次。已提交的 UTC `scheduledAt` 在重启时绝不重新计算。 +RRULE 接受有界的 RFC 5545 子集,以共享的 [`rrule.ts` 解析器](../../packages/util/time/src/rrule.ts)为准。输入恰好包含两条非空内容行:先 `DTSTART`,再 `RRULE`。开始时间为真实的 `YYYYMMDDTHHMMSS` 日期时间,使用 UTC `Z` 或显式 IANA `TZID`;拒绝浮动本地时间、数字偏移、仅日期值及额外内容行。引擎使用 `rrule` 2.8.1,支持 `MINUTELY`、`HOURLY`、`DAILY`、`WEEKLY`、`MONTHLY` 和 `YEARLY`。一次性投递使用 `COUNT=1`。 -day-of-month 与 day-of-week 遵循 Vixie 语义。字段文本以 `*` 开头即为星号字段,与它匹配的取值集合无关,因此 `*/1` 与 `*/2` 都是星号字段,而 `1-31` 与 `0-7` 受限。任一字段为星号字段时,本地日期只有在两个字段都匹配时才算匹配;两个字段都不是星号字段时,匹配任一字段即算匹配。 +只接受 `FREQ`、`INTERVAL`、`COUNT`、`UNTIL`、`WKST`、`BYSECOND`、`BYMINUTE`、`BYHOUR`、`BYDAY`、`BYMONTHDAY`、`BYYEARDAY`、`BYWEEKNO`、`BYMONTH` 和 `BYSETPOS`;字段名和列表值必须唯一。`INTERVAL` 为正安全整数。`WKST` 为 `MO` 至 `SU` 中的星期,默认 `MO`。数字列表须在解析器规定的范围内。分钟/小时规则不接受 `BY` 部分。`BYMONTHDAY` 和带序数的 `BYDAY` 仅用于每月或每年;`BYYEARDAY` 和 `BYWEEKNO` 仅用于每年。带序数的 `BYDAY` 不能与 `BYWEEKNO` 组合,`BYSETPOS` 必须搭配另一项 `BY`。 -cron 解码保留已提交时点及已存储的时区拼写,并拒绝非规范化的已存储表达式。cron 仅属于当前宿主的 `ScheduleRecord`;冻结的历史 Session 解码器不接受它。 +验证发生在枚举之前。拒绝 `SECONDLY`、多个 `BYSECOND` 值及一个频率周期中超过 10,080 个可能候选时点的规则。`COUNT` 为 1 至 1,000,不能与 `UNTIL` 共存;`UNTIL` 为以 `Z` 结尾的绝对 UTC 日期时间。开始与截止年份为 0100 至 9999。集合位置至多 31 个,每个位置为 −366 至 −1 或 1 至 366,且必须在有界周期内。较严格的新规则编写检查还会在周期至多有一个候选时点时拒绝 `BYSETPOS`;解码和恢复未改变的受支持规则仍使用正常求值器。 -## 历史 Session 变更 +不存在的本地 `DTSTART` 会被拒绝。后续不存在的本地发生时点会跳过,且不消耗 `COUNT`;重叠时间选择较早时刻。即使正负集合位置选中同一时点,`COUNT` 也仅计数一次。 -版本 1 的 `schedule/change` 事件仍可作为历史 Session 数据解码。其 create 和 fold 类型使用 `LegacyScheduleRecord`,仅接受 After、At 和 Every;Daily、Weekly 与 Cron 仅属于当前宿主的 `ScheduleRecord`。宿主记录解码器独立于冻结的历史解码器。在 title 出现之前写入的 create 记录不含 `title`,因此历史解码器接受该缺失成员,而宿主解码器仍要求它。历史事件不会填充 storage domain 或触发投递。这些事件中的已有提醒需要显式通过 `schedule_create` 重新创建;不会隐式迁移 Session 或转换旧 `at` 记录。 +自定义 RRULE 文本保留其 `DTSTART` 时区。面向模型的工具继续指导并接受 RRULE;共享管理 API 则显式接受每种时间类型。 -```ts type-equiv -/** - * Frozen Session event and fold vocabulary; daily rules belong only to Host storage. - * - * A version-1 event written before titles existed persists no `title` member, so - * `after`, `at`, and `every` decode without one and stay readable. The Host task - * record requires the member and never persists a record without it. - */ -type LegacyScheduleRecord = - | LegacyAfterScheduleRecord - | LegacyAtScheduleRecord - | LegacyEveryScheduleRecord -``` + +## 投递目标 -```ts type-equiv -/** Creates one durable reminder record. */ -interface ScheduleCreateChange { - readonly version: 1 - readonly operation: 'create' - readonly schedule: LegacyScheduleRecord -} -``` +| 目标 | 投递行为 | +|---|---| +| `session` | 投递到一个已有 Session。启用时在管理 FIFO 内检查其存在、未归档且不属于委托子 Agent。投递时再次检查归档状态。 | +| `new_once` | 首次投递前预留 Session id,需要时创建该 Session,然后保存为 `session` 并复用。重试和重启保留该预留标识。 | +| `new` | 每次投递创建 Session。创建前持久化 `pendingDelivery.targetSessionId`,使失败尝试重用同一 Session。 | -```ts type-equiv -/** Deletes one currently active reminder. */ -interface ScheduleDeleteChange { - readonly version: 1 - readonly operation: 'delete' - readonly id: ScheduleId -} -``` +创建时省略目标则默认 `new_once`。新增或替换 `new`、`new_once` 目标需要嵌入环境提供 Session 创建能力。SDK 组合缺少该能力时,在保存前以 `invalid_rule` 拒绝这些请求;已有 `session` 目标仍可使用。创建值 `cwd` 和 `agentPreset` 可省略,使用 Host 默认值。创建的 Session 会加入其目录已注册的 Workspace(如有),且尚无标题时使用任务标题;`new` 另加该规则时区中的创建分钟。加入或重命名失败会记录日志,但不阻断投递。 -```ts type-equiv -/** Records that one active one-shot reminder entered the durable dispatch history. */ -interface OneShotScheduleDispatchChange { - readonly version: 1 - readonly operation: 'dispatch' - readonly id: ScheduleId -} -``` + +## 任务管理 -```ts type-equiv -/** Records one fixed-rate decision and advances directly past missed occurrences. */ -interface EveryScheduleDispatchChange { - readonly version: 1 - readonly operation: 'dispatch' - readonly id: ScheduleId - /** Wall-clock decision time used to select the latest due occurrence. */ - readonly acceptedAt: string -} -``` +所有调用方使用相同的 `ScheduleCreateRequest`、`ScheduleCatalogEntry`、`ScheduleTiming` 和 `ScheduleEditRequest`。浏览器安全类型来自 `@deepseek-ai/dsh-schedule/client`。不存在 Session 绑定的管理入口或第二套类型别名。 -```ts type-equiv -/** Durable dispatch shapes supported by the current rule set. */ -type ScheduleDispatchChange = OneShotScheduleDispatchChange | EveryScheduleDispatchChange -``` +| 操作 | 行为 | +|---|---| +| `create(request, actorSessionId?, signal?)` | 分配 id 并保存标题、指令、带类型的 `timing` 及可选目标。 | +| `list(request?)` | 分页读取;默认 100、最多 500,可选 `active` 过滤及非负 `offset`。 | +| `catalog()` / `view({ id })` | 无分页上限读取所有任务,或读取一个任务。 | +| `history({ id, limit, before? })` | 不激活 Session 地读取已保存投递;limit 为 1 至 100。 | +| `edit(request, actorSessionId?, signal?)` | 按 id 原子应用 `update` patch 或 `delete`。 | +| `deleteInactive()` | 一次批量写入仅删除 `ended` 任务,保留活动和暂停任务,返回 `{ deleted }`。空集合不写入。 | +| `run({ id }, signal?)` | 经正常准入立即投递,不改变已计划发生时点或生命周期。 | +| `deliveryLimits()` | 读取 `new` 目标的配置最小间隔。 | -```ts type-equiv -/** Strict version-1 durable Schedule mutation union. */ -type ScheduleChange = ScheduleCreateChange | ScheduleDeleteChange | ScheduleDispatchChange -``` +Remote 路由提供 `create`、`list`、`catalog`、`view`、`history`、`edit`、`deleteInactive`、`run` 和 `deliveryLimits`;传输包装器委托给相同管理方法。Remote 验证失败使用带 Schedule 输入码的 `schedule/input-invalid`。原生调用方收到 `ScheduleInputError`。 -历史 decoder 与 fold 拒绝未知版本、额外字段、复用 ID 和无效转换。该事件仍编入[持久化目录](../persistence-catalog.zh.md#schedulechange--log-only)。Session 历史不负责决定当前活动任务。 +非空的 `deleteInactive` 批量写入成功后发出 `schedule/changed`,供读取方刷新;不向 Agent 排入通知。批量写入被拒绝时也发出该事件,让读取方丢弃旧状态。正常失败保留全部行;`unknown-state` 失败可能已移除行,并隔离领域直到重新打开。失败调用以拒绝结束,不返回删除数量。 -## 活动视图与管理 +更新可以替换标题、指令、带类型时间、目标或活动状态。省略字段保留原值。规则改变或显式恢复时,在 FIFO 接受时刻计算未来时点;等价时间及描述性编辑保留已提交目标。已投递的一次性任务需要新的未来时间才能恢复。重新指定目标不要求转换时间类型。 -工具值将存储记录与当前墙钟派生的时间状态组合。宿主在投递需要时恢复原 Session;列出和删除任务不会激活该 Session。 +`expectedUpdatedAt` 是可选的乐观比较。字符串与已存修订比较;显式 `null` 与缺失的修订比较。不一致时返回 `schedule_conflict`。编辑没有修订的行会创建修订;即使时钟回拨,后续修订仍单调递增。开始写入前检查取消,已经开始的持久写入不回滚。 -```ts type-equiv -/** Current delivery timing derived from the durable record and wall clock. */ -type ScheduleState = 'scheduled' | 'overdue' -``` + +## 时间编辑 -```ts type-equiv -/** Host-driven delivery resumes the original Session when needed. */ -type ScheduleDeliveryMode = 'host' -``` +`timing` 判别字段只选择其匹配的载荷,例如 `{ kind: "cron", cron: { expression: "0 9 * * 1-5", time_zone: "Asia/Shanghai" } }` 或 `{ kind: "rrule", rrule: "DTSTART:20990101T090000Z\nRRULE:FREQ=DAILY" }`。其他选择器使用 `after_seconds`、`at`、`every_seconds`、`daily` 或 `weekly`。持久化前拒绝无效组合。UI 经相同 API 保存带类型的 Cron/RRULE 输入,并保留未修改的时间规则。 -```ts type-equiv -/** Complete model-facing view of one active reminder. */ -type ScheduleView = ScheduleRecord & { - /** Whether the target remains in the future. */ - readonly state: ScheduleState - /** Reminder delivery never leaves the owning session. */ - readonly deliveryMode: ScheduleDeliveryMode -} -``` + +## 已保存投递记录 -[工具目录](../tool-catalog.zh.md#deepseek-aidsh-tool-schedule) 负责 `schedule_create`、`schedule_list`、`schedule_delete` 和 `schedule_update` 的 schema,这四个工具由 [`@deepseek-ai/dsh-tool-schedule`](../../packages/schedule/tool-schedule/README.zh.md) 在挂载它的每个 preset 中贡献;宿主服务拥有存储与投递。创建、删除和更新在 storage domain 写入确认后返回成功。宿主级队列将这些变更与到期投递串行化;删除任务不会移除已入队消息。模型工具操作当前 Session,共享宿主的 create、list、update 和 delete 方法接受显式 Session 绑定。`create` 与 `update` 在其委派深度大于零时以 `subagent_session` 拒绝被委派子 agent 拥有的 Session,且投递无法到达这样的 Session。四个模型工具在工具层拒绝被委派的调用方,而 `list`、`catalog`、`history` 与 `delete` 仍服务该 Session。创建必须提供 `title`,其去除首尾空白后必须非空且不超过 120 个字符;缺失、空白或过长的标题以 `invalid_prompt` 拒绝,且创建过程绝不从指令派生标题。create 和 list 视图在指令之外同时携带已存储的 `title`,且 `title` 缺失或非法的已存储记录在解码时被拒绝。 +回执记录 `scheduledAt`、`deliveredAt`、`messageId` 和 `targetSessionId`;它确认持久 Session 收件箱写入,而非模型完成。已保存记录还可含不可变的已发送 `prompt`。旧回执缺少目标 id 时,在任何重新指定目标的编辑之前使用已解析的可复用目标,因此后续目标不会重写其历史。 回执既没有显式目的地也没有已知复用目标时,拒绝解码;新默认预留不能证明历史目的地。 -```ts type-equiv -/** Reminder creation selector, shared by the model consumer and Host service. */ -interface ScheduleCreateRequest { - /** Non-empty reminder text. */ - prompt: string - /** Required task name of at most 120 characters, non-empty after trimming; names the card, detail heading, and task lists. */ - title: string - /** Relative one-shot delay in seconds. */ - after_seconds?: number - /** Absolute one-shot target. */ - at?: AtInput - /** Fixed recurrence interval in seconds. */ - every_seconds?: number - /** Daily wall-clock time in an explicit IANA zone. */ - daily?: DailyInput - /** Weekly wall-clock time and explicit ISO weekday set in an IANA zone. */ - weekly?: WeeklyInput - /** Five-field cron expression evaluated in an explicit IANA zone. */ - cron?: CronInput -} -``` +新任务从已知的空历史开始。旧行没有 `deliveryHistory` 时,暴露其最新回执(如有),并设置 `earlierRecordsUnavailable: true`;不会编造丢失的历史或指令快照。省略的 `earlierRecordsPruned` 读为 false。消息 id 重复,或最新保存记录与 `lastDelivery` 不一致,均拒绝解码。 -```ts type-equiv -/** Session-scoped task list, without Agent activation. */ -interface ScheduleListRequest { - /** Original Session binding. */ - sessionId: SessionId -} -``` - -```ts type-equiv -/** Delete request identifying a task within its original Session binding. */ -interface ScheduleDeleteRequest extends ScheduleListRequest { - /** Task to remove. */ - id: ScheduleId -} -``` - -```ts type-equiv -/** Successful `schedule_delete` value, including the non-mutating not-found result. */ -type ScheduleDeleteResult = - | { readonly id: ScheduleId; readonly deleted: true } - | { readonly id: ScheduleId; readonly deleted: false; readonly code: 'schedule_not_found' } -``` - -```ts type-equiv -/** Successful Host-wide removal of every ended task, whether or not any remained. */ -interface ScheduleDeleteInactiveResult { - /** Ended task rows this call removed; zero when the Host held none. */ - readonly deleted: number -} -``` - -## Web 目录 - -Remote 方法 `schedule.catalog()` 返回活动和未运行的宿主任务及其原始 Session 绑定,先按 `scheduledAt` 升序排列,再按 `id` 字典序排列。它只读取 Schedule domain,不激活 Session 或读取其历史。浏览器消费方接收以下可安全用于浏览器的类型: - -```ts type-equiv -/** Durable Session inbox delivery acknowledgment, not model execution completion. */ -interface ScheduleDeliveryReceipt { - /** Canonical UTC target of the delivered occurrence. */ - readonly scheduledAt: string - /** Canonical UTC time sampled after Session persistence acknowledged delivery. */ - readonly deliveredAt: string - /** Identity of the delivered message, shared by tasks in one recurring batch. */ - readonly messageId: MessageId -} -``` - -```ts type-equiv -/** Browser-safe retained reminder with its original Session binding. */ -type ScheduleCatalogEntry = ScheduleRecord & { - /** Session receiving this reminder when it becomes due. */ - readonly sessionId: SessionId - /** Inactive reminders remain visible but never schedule another delivery. */ - readonly status: 'active' | 'inactive' - /** Most recent durably acknowledged inbox delivery, when available. */ - readonly lastDelivery?: ScheduleDeliveryReceipt -} -``` - -Remote 方法 `schedule.list({ sessionId })`、模型 `schedule_list` 和 Session 页头目录仅返回活动任务。模型视图派生的时间 `state` 与存储的生命周期 `status` 仍是不同概念。删除通过 `schedule.delete({ sessionId, id })` 使用条目的原始绑定;绑定不匹配时返回未找到。模型工具传入当前 Agent 的 Session,全局用户界面则传入所选任务的绑定。仅校验绑定并不构成调用者鉴权。`schedule.deleteInactive()` 删除跨会话的全部未运行(已结束)任务,连同每行携带的已保存的发送记录;成功时以它移除的计数答复 `{ deleted }`;普通失败时不删除任何行;后端报告 `unknown-state` 时可能已移除部分行,并会隔离 Host 的 schedule 领域,之后该领域的操作都会拒绝,直到重新打开。任何拒绝都会先发出 `schedule/changed`,客户端重新读取。自动化任务页面的批量清理使用该方法。未运行任务从不会安排定时器,因此该删除不重算任何目标。无 payload 的 `schedule/changed` 事件通知客户端刷新列表;重新连接后,客户端再次获取当前状态。 - -随发行版交付的 Web 组合把 `ui-schedule` 与宿主能力一起挂载。[客户端包](../../packages/client/ui-schedule/README.zh.md) 负责目录、空状态与删除控件。页面单独筛选全部、活动和未运行任务,保留未运行任务详情及详情页签条内的原 Session 入口,并要求显式确认删除。“规则”和“任务运行记录”页签将任务设置与按需分页加载的已保存回执分开。回执与未运行状态均不确认模型执行。 - -## 修改时间 - -`schedule.update({ sessionId, id, expected, change })` 修改活动任务,不激活其 Session。`expected` 是完整的已观察 `ScheduleRecord`,不是附带额外元数据的目录条目。Host 在投递和删除共用的 FIFO 内将它与当前记录比较。正常投递可能在编辑期间推进目标;此时旧快照返回 `schedule_conflict`,不会覆盖当前规则。任务不存在或绑定不匹配时返回 `schedule_not_found`,未运行任务返回 `schedule_ended`。 - -```ts type-equiv -/** Timing-only edit; it may select a different recurrence kind than the stored record, and one-shot targets use an absolute `at`. */ -type ScheduleTimingChange = - | { readonly kind: 'at'; readonly at: AtInput } - | { readonly kind: 'every'; readonly every_seconds: number } - | { readonly kind: 'daily'; readonly daily: DailyInput } - | { readonly kind: 'weekly'; readonly weekly: WeeklyInput } - | { readonly kind: 'cron'; readonly cron: CronInput } -``` - -```ts type-equiv -/** Compare-and-update request within the original Session binding. */ -interface ScheduleUpdateRequest extends ScheduleDeleteRequest, ScheduleUpdateContent { - /** Complete record observed when editing began, including the committed target. */ - readonly expected: ScheduleRecord - /** New timing; its kind may differ from the stored record's kind, and an omitted value keeps the committed target. */ - readonly change?: ScheduleTimingChange -} -``` - -```ts type-equiv -/** Successful current record, non-mutating lookup/conflict failure, or invalid name/instruction/timing. */ -type ScheduleUpdateResult = - | { readonly id: ScheduleId; readonly updated: boolean; readonly record: ScheduleRecord } - | ScheduleUpdateMiss - | ScheduleToolError -``` - -Daily 规则改变后,沿用本地时间和时区语义计算严格晚于当前时间的首个目标。Cron 规则改变后,先规范化表达式,再按相同的本地日期、缺口与较早重叠规则计算首个严格未来目标。Every 间隔改变后,以接纳保存时刻加该间隔建立新的起点。After 或 At 任务可以在保留 id 的同时,通过 At 记录接收新的绝对目标。这些操作保留已存储的 `title`、指令、原始 Session 绑定、生命周期状态和全部已保存回执。变更也可以选择不同的重复类型,此时按新规则重算目标,并保留同一 id、标题、指令、Session 绑定、状态与全部已保存回执。归一化后等价的规则返回 `updated: false` 及未改变的记录,不重写存储、不重设目标,也不发出变更事件。写法不同但等价的 Cron 表达式就是这样的无变更,因为比较使用规范化表达式与规范化时区。 - -输入校验复用现有时间错误。改变后的绝对目标在 FIFO 槽位开始执行时仍须位于未来。任务 put 成功后才发出变更通知并重算 timer。存储和生命周期失败会 reject;取消检查发生在排队和初始化等待之后,但不能回滚已经开始的写入。一次性记录保留 UTC 时点,而非编辑表单中的 IANA 时区。时间编辑不追加历史 Session 事件:模型通过 `schedule_update` 做同样的原地修改,它与读取到的记录做比对,而不是删除后重建任务。 - -## 已保存的发送记录 - -`schedule.history({ sessionId, id, limit })` 读取已保存的回执,不激活 Session。显式 limit 必须是 1–100 的安全整数。分页按追加顺序逆序排列,不按墙钟排序;可选的消息 id 游标排除上一页最早的记录。新记录追加不会改变该游标的定位。任务不存在或 Session 绑定错误时返回 `schedule_not_found`;游标未知时返回 `delivery_cursor_not_found`,不会视为查询成功的空页。 - -```ts type-equiv -/** Saved inbox delivery with its immutable sent prompt when recorded by this Host. */ -interface ScheduleDeliveryRecord extends ScheduleDeliveryReceipt { - /** Prompt sent for this occurrence; unavailable for legacy receipts. */ - readonly prompt?: string -} -``` - -```ts type-equiv -/** Explicitly bounded saved-delivery query within one Session binding. */ -interface ScheduleDeliveryHistoryRequest extends ScheduleDeleteRequest { - /** Required safe-integer page size from 1 through 100. */ - limit: number - /** Message identity of the oldest entry in the previous page; excluded from this page. */ - before?: MessageId -} -``` - -```ts type-equiv -/** Configured limits applied when appending one task's delivery receipt. */ -interface DeliveryRetentionBounds { - /** Retained window in days, measured back from the acknowledgment being appended. */ - readonly days: number - /** Maximum retained records per task; the newest survive. */ - readonly records: number -} -``` - -```ts type-equiv -/** Newest-first saved deliveries, or a non-mutating task/cursor lookup failure. */ -type ScheduleDeliveryHistoryResult = - | { - readonly id: ScheduleId - readonly records: ScheduleDeliveryRecord[] - /** Whether earlier delivery records may be unavailable; missing receipts are never reconstructed. */ - readonly earlierRecordsUnavailable: boolean - /** True only after an append removed saved records; absent legacy evidence is false. */ - readonly earlierRecordsPruned: boolean - /** Current Host retention configuration, also used by the delivery writer. */ - readonly retention: DeliveryRetentionBounds - /** Oldest returned message identity, present only when older saved records remain. */ - readonly nextBefore?: MessageId - } - | { readonly id: ScheduleId; readonly code: 'schedule_not_found' | 'delivery_cursor_not_found' } -``` - -新任务初始化空历史。缺少历史字段的旧任务仅展示已有的最近一次回执,标明更早记录不可用,且读取不会重写任务行。后续确认会保留该回执,并追加带有指令快照的真实新回执。已丢失的历史与缺失的旧指令快照不会被重建。历史、最近回执、状态和下一目标由同一次任务行写入提交;显式删除任务会停止后续投递、把任务行连同其已保存的回执一并移除,并使其离开 `list` 与 `catalog`;对话消息不受影响。已保存的发送记录在追加确认时按配置的 `deliveryHistoryDays` 窗口(以每条回执的 `deliveredAt` 向前计算)与 `deliveryHistoryRecords` 条数上限裁剪;新追加的最近一次回执始终保留,发生裁剪时标记更早记录不可用。分页限制返回的记录数量,不限制存储大小或指令字节数。 +历史按追加顺序排列,不受时钟回拨影响。确认在同一任务提交中追加并裁剪,默认保留最多 200 条、30 天,同时保留最新回执。查询页从新到旧,使用不含游标自身的消息 id 游标。硬删除移除任务及历史,不移除已入队的 Session 消息。 + ## 宿主投递 -宿主启动时读取持久任务,并将定时器设为最早的活动目标。未运行任务仍可查询,但不会再次安排投递。投递通过 `schedule/resolve-agent` 解析原 Session,包括尚未激活的会话。嵌入方拥有激活过程:SDK 处理方等待初始化,并保留其 Session handle 和模型选项;没有处理方时由 Web Session controller 恢复会话。组合等待其激活提供方就绪后再启动 Schedule。恢复后重新采样实际时间,并排除时钟回拨后尚未到期的成员;这些任务仍保留定时义务。投递不涉及 Goal 或独立的 Run 完成记录。 +一个 Host 定时器驱动活动任务。运行时与管理写入共用一个 FIFO。已有和预留 Session 通过 `schedule/resolve-agent` 解析,由嵌入环境拥有激活,已注入的 Web 控制器作为后备。复用 Session 的任务占用执行槽,直到目标 Agent 空闲;期间发生的时点会合并。`new` 目标允许多个执行并行。到期且投向相同已有 Session 的重复记录共享一条消息;`after` 和 `at` 单独投递。 -插件来源的 `followup()` 同步将消息追加到 Session 收件箱。Session flush 成功后,一次任务记录 put 追加带有指令快照的发送记录,并同时存储最新的 `ScheduleDeliveryReceipt`,以及一次性任务的 `inactive` 状态或重复任务的下一目标和状态。同一批次的重复任务共享回执的 `messageId`;每条回执保留该任务已投递的发生时点。投递不会中途引导或取消当前轮次,也不等待模型完成。 +定时与手动投递均遵守单任务 60 秒最小间隔。`newSessionIntervalSeconds` 可为 `new` 目标提高间隔,最多一周。已存后继时点保持间隔时,下界从上次发生时点计算;否则从上次确认计算,因此投递延迟不会移动规则锚点。读取仅在适用时暴露 `executionActive` 和 `deliveryFloorEndsAt`。 -Session 获取、消息入队或持久化确认失败时,任务继续保存在存储中,并报告宿主警告。后续管理变更或宿主重启会重试。Session 持久化与任务 put 不具有跨存储原子性。收件箱已持久化、任务尚未 put 时发生崩溃,可能重复投递;回执并未消除这一间隔。Schedule 不提供模型结果回执、执行取消或外部通知渠道。 +Session 收件箱持久化先于任务回执写入,因此两份存储之间崩溃可能重复投递。Host 必须运行。指向某 Session 的活动任务会参与其归档准入;归档停止操作会删除这些活动任务。 + +管理变更提交后,Schedule 向除操作者之外的每个已加载相关 Agent 排队发送尽力而为的通知。通知加入下一模型步骤,不开启新轮次;其 Session I/O 不占用管理/投递队列。每次投递新建的 Session 不会累积到相关元数据中。 + + +## 历史 Session 变更 + +历史版本 1 的 `schedule/change` 事件保留冻结的 `LegacyScheduleRecord` 类型:`after`、`at`、`every`,包括原来的可选标题。它们仍是已保存的 Session 数据,Schedule 不为其保留解释器、警告钩子、导入器或定时器。`schedule.json` 中已有的 Host 任务仍使用正常的解码器与求值器。 @@ -457,64 +149,87 @@ Generated from source by `scripts/gen-cordis-catalog.ts` (verified fresh by `pnp ### `ctx.schedule` — `ScheduleService` -Shared management service; reads, deletion, and timing edits never activate a Session. +Shared management service; reads and management writes never activate a Session, and only delivery creates or resumes one. -`sessionPersistence` is a load-order requirement rather than a directly called service: a delivery commits only when `ctx.sessions.flush()` reports that a `session/flush` listener participated, and the persistence backend providing this service is the plugin that registers that listener. +`sessionPersistence` supplies header-only target validation and the `session/flush` listener that acknowledges durable inbox delivery through `ctx.sessions.flush()`. ```ts cordis-catalog +/** Read effective delivery limits without loading or activating a task. + * @returns The configured minimum spacing between deliveries that each create a Session, in seconds. + */ +@Remote('deliveryLimits') deliveryLimits(): { readonly newSessionIntervalSeconds: number } + /** - * Create a reminder bound to the caller-selected Session without activating it. + * Create one task with a Host-generated identity for a human Remote caller. + * @param request - Title, prompt, recurrence, and delivery destination. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The stored task. Cancellation does not roll back an in-flight write. + */ +@Remote('create') async remoteCreate(request: ScheduleCreateRequest, signal?: AbortSignal): Promise + +/** + * Create one task and record the acting Agent's Session as involved; the Remote form omits that Session. * - * The request must supply a title; a missing, blank-after-trim, or over-long - * title rejects with `invalid_prompt` instead of deriving one from the prompt. - * A Session a delegated child owns rejects with `subagent_session`, because delivery - * can never reach it: the child is one whose delegation depth is above zero. - * The record is built from the clock reading taken before the request joins the - * serialized queue, so a create that waits behind a longer operation keeps its - * request-time anchor and may already be due when the queue reaches it. - * @param sessionId - Original Session receiving the reminder. - * @param request - Validated tool selector, required title, and reminder content. - * @param signal - Optional cancellation checked before persistence begins, including after FIFO waits. - * @returns The durably stored schedule. Cancellation does not roll back an in-flight write. + * The record is built from the clock reading taken before the request joins the serialized queue. A `session` + * target must exist and must not belong to a delegated child; a `new_once` target reserves its Session identity. + * @param request - Title, prompt, recurrence, and delivery destination. + * @param actorSessionId - Session of the acting Agent, or undefined for a human caller. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The stored task. Cancellation does not roll back an in-flight write. */ -async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: AbortSignal): Promise +async create( request: ScheduleCreateRequest, actorSessionId?: SessionId, signal?: AbortSignal, ): Promise /** - * Read the selected Session's active tasks without resuming its Agent. - * @param request - Session whose task list is requested. - * @returns Persisted reminders in storage order. + * Read one page of Host tasks without activating target Sessions. + * @param request - Optional activity filter, page size, and offset. + * @returns The requested page and total matching task count. */ -@Remote('list') async list(request: ScheduleListRequest): Promise +async list(request: ScheduleListRequest = {}): Promise /** - * Read all active and inactive Host reminders with their original Session bindings. - * A deleted reminder has no row, so it is absent here. - * Does not activate Sessions or read Session history. - * @returns Reminders ordered by scheduledAt ascending, then lexicographically by id. + * Remote form of the shared Host-wide list. + * @param request - Optional activity filter, page size, and offset. + * @returns The requested page and total matching task count. + */ +@Remote('list') async remoteList(request: ScheduleListRequest): Promise + +/** + * Read every Host task without a page bound or Session activation. + * @returns All tasks, active first, with target and execution metadata. */ @Remote('catalog') async catalog(): Promise /** - * Read saved inbox deliveries without activating or reading the original Session. - * The task's own row supplies its binding, so its records stay readable through this lookup. - * @param request - Session binding, task identity, explicit limit, and optional exclusive message cursor. - * @returns Newest-first deliveries in append order, or a task/cursor lookup failure. - * @throws ScheduleInputError when limit is not a safe integer from 1 through 100. + * Read one task without activating its target Sessions. + * @param request - Task identity. + * @returns The task, or a non-mutating miss. */ -@Remote('history') async history(request: ScheduleDeliveryHistoryRequest): Promise +@Remote('view') async view(request: ScheduleViewRequest): Promise /** - * Delete one task belonging to the selected Session, leaving queued messages intact. - * - * The row is removed: the task no longer schedules, leaves `list` and `catalog`, and its - * saved delivery records go with it. A task bound to a Session a delegated child owns - * stays deletable even though creation and timing edits refuse that binding, so a task - * stored before that rule existed remains removable. - * @param request - Session and exact task identity. - * @param signal - Optional cancellation checked before persistence begins, including after FIFO waits. - * @returns Whether that Session owned a deleted task. Cancellation does not roll back an in-flight write. + * Read one page of saved deliveries without activating or reading a target Session. + * @param request - Task identity, explicit page size, and optional exclusive cursor. + * @returns Newest-first saved deliveries, or a task/cursor lookup failure. */ -@Remote('delete') async delete(request: ScheduleDeleteRequest, signal?: AbortSignal): Promise +async history(request: ScheduleDeliveryHistoryRequest): Promise + +/** + * Remote form of the target-based {@link ScheduleService.history}; an invalid limit rejects with + * `schedule/input-invalid`. + * @param request - Task identity, explicit limit, and optional exclusive message cursor. + * @returns Newest-first deliveries in append order, or a task/cursor lookup failure. + */ +@Remote('history') async remoteHistory(request: ScheduleDeliveryHistoryRequest): Promise + +/** + * Deliver one task now without consuming or moving its scheduled occurrence; an archived destination Session rejects + * with `schedule/target-archived`. + * @param request - Task identity. + * @param signal - Cancellation checked after entering the delivery transaction and before delivery. + * @returns Task state after Session persistence acknowledged the delivery, `schedule_execution_pending` while + * another execution of the task is queued, running, or inside its delivery floor, or a non-mutating miss. + */ +@Remote('run') async run(request: ScheduleRunRequest, signal?: AbortSignal): Promise /** * Delete every ended Host task, leaving active tasks armed. @@ -526,27 +241,32 @@ async create(sessionId: SessionId, request: ScheduleCreateRequest, signal?: Abor * failure rejects with every listed row still stored, while a backend * `unknown-state` failure may have removed rows and quarantines the Host * domain, so later schedule operations reject until the domain is reopened. - * Every rejection announces `schedule/changed` because it does not establish + * A successful nonempty batch emits `schedule/changed` without Agent notices. + * A rejected batch announces `schedule/changed` because it does not establish * which rows landed, and clients then re-read the catalog. * @returns Count of removed rows; zero when the Host held no ended task. */ @Remote('deleteInactive') async deleteInactive(): Promise /** - * Update the name, instruction, and timing of an active task within the original Session - * binding without activating the Session or changing saved deliveries. - * - * Each supplied field replaces its stored value; an omitted field keeps it. A name or - * instruction change alone does not reset the committed target. A Session a delegated - * child owns returns the non-mutating `subagent_session` result, so an edit cannot - * re-arm a task bound to a Session delivery can never reach, and the Web editor can - * explain the refusal through the ordinary result it already renders. - * @param request - Task binding, complete observed record, and any combination of timing, name, and instruction. - * @param signal - Cancellation checked after domain readiness and FIFO waits, before persistence begins. - * @returns The committed record, unchanged record for a no-op, or a non-mutating input/lookup/conflict/refusal result. - * Storage and lifecycle failures reject; cancellation after a write starts does not roll it back. + * Update or delete one task for a human Remote caller; an invalid patch rejects with `schedule/input-invalid`. + * @param request - Task identity and one update or delete operation. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The updated task, the deletion outcome, or a non-mutating miss or conflict. */ -@Remote('update') async update(request: ScheduleUpdateRequest, signal?: AbortSignal): Promise +@Remote('edit') async remoteEdit(request: ScheduleEditRequest, signal?: AbortSignal): Promise + +/** + * Update or delete one task and record the acting Agent's Session as involved; the Remote form omits that Session. + * + * An update applies every patch field in one write and recomputes the next occurrence when the rule changes or + * the task resumes. A supplied `expectedUpdatedAt` that differs from the stored value returns `schedule_conflict`. + * @param request - Task identity and one update or delete operation. + * @param actorSessionId - Session of the acting Agent, or undefined for a human caller. + * @param signal - Cancellation checked before the durable write begins, including after FIFO waits. + * @returns The updated task, the deletion outcome, or a non-mutating miss or conflict. + */ +async edit( request: ScheduleEditRequest, actorSessionId?: SessionId, signal?: AbortSignal, ): Promise ``` Types: [SessionId](core.zh.md) diff --git a/docs/subsystems/session-projection.i18n.yaml b/docs/subsystems/session-projection.i18n.yaml index b38666ddb4..917f2152fb 100644 --- a/docs/subsystems/session-projection.i18n.yaml +++ b/docs/subsystems/session-projection.i18n.yaml @@ -9,8 +9,8 @@ en: d48814d3ab0e997f zh: d0337d8eba097a63 /session-projections/the-snapshot-and-the-change-feed: - en: 630c1041f41f89bf - zh: a3361bdead116cd7 + en: bc9d438b90fc2baa + zh: df7cbea2dad3786b /session-projections/summary-reads: en: d2bc9bcc775acfb7 zh: b1d2ba74496305b8 diff --git a/docs/subsystems/session-projection.md b/docs/subsystems/session-projection.md index cee8103ef0..7ea7c06716 100644 --- a/docs/subsystems/session-projection.md +++ b/docs/subsystems/session-projection.md @@ -135,7 +135,22 @@ type ProjectionChangeListener = ( ) => void ``` -`snapshot(session)` is fully synchronous: a carrier reads it in the same tick as its page slice, so `asOfSeq` covers both reads at one sequence number. It returns only client views, and every value passes its unit's `viewSchema` before return. `handle.stateOf(session)` reads one live host state without computing unrelated views; callers must not mutate the borrowed reference. A state-reference change computes one cached raw view, and the change feed fires only when that result changes by `Object.is`; an object-valued view must preserve its reference to suppress publication across internal-only state changes. +```ts type-equiv +/** + * Event-level change-feed listener: one committed event changed the raw `view` + * result of at least one client-visible unit by `Object.is` for one session. + * `changes` holds one entry per such unit in registration order, each with the + * unit's `key` and its schema-validated view as `val`; `seq` is the seq of the + * causing event. + */ +type ProjectionEventChangeListener = ( + session: Session, + changes: readonly { readonly key: Extract; readonly val: unknown }[], + seq: SessionSeq, +) => void +``` + +`snapshot(session)` is fully synchronous: a carrier reads it in the same tick as its page slice, so `asOfSeq` covers both reads at one sequence number. It returns only client views, and every value passes its unit's `viewSchema` before return. `handle.stateOf(session)` reads one live host state without computing unrelated views; callers must not mutate the borrowed reference. A state-reference change computes one cached raw view, and the change feed fires only when that result changes by `Object.is`; an object-valued view must preserve its reference to suppress publication across internal-only state changes. After every unit has been driven for one committed event, the event-level feed calls each `onEventChanged` listener once with every client-visible key whose view the event changed; an event that changes no client view makes no event-level call. ## Summary reads @@ -346,6 +361,18 @@ register( definition: ProjectionDefinition & { key: E */ onChanged(listener: ProjectionChangeListener): () => void +/** + * Subscribe to the event-level change feed. The registration is an effect on + * the calling context's fiber. The listener runs synchronously inside the + * committed event's `session/event` handling, once after every unit has been + * driven and after every {@link onChanged} call for that event. If a unit or + * an {@link onChanged} listener throws during that drive, the listener still + * receives the changes made before the throw. + * @param listener - called once per committed event that changed at least one client-visible unit's raw view by `Object.is`. + * @returns the exact disposer that unsubscribes. + */ +onEventChanged(listener: ProjectionEventChangeListener): () => void + /** * One consistent cut over every registered client-visible unit for one session, read from * the watermark cache (missing cells fold lazily over the in-memory log). diff --git a/docs/subsystems/session-projection.zh.md b/docs/subsystems/session-projection.zh.md index 6e076a18a3..b84720e804 100644 --- a/docs/subsystems/session-projection.zh.md +++ b/docs/subsystems/session-projection.zh.md @@ -135,7 +135,22 @@ type ProjectionChangeListener = ( ) => void ``` -`snapshot(session)` 完全同步:载体在切出页面切片的同一 tick 内读取它,因此 `asOfSeq` 使两次读取使用同一个序号。它只返回客户端视图,并在返回前通过各单元的 `viewSchema` 校验。`handle.stateOf(session)` 可在不计算无关视图的情况下读取一份实时 host 状态;调用方不得修改这一借用引用。state 引用变化时,注册表计算并缓存一次原始 view;只有该结果通过 `Object.is` 判定为变化时才触发变更流,对象 view 若要在仅内部 state 变化时抑制发布就必须保留引用。 +```ts type-equiv +/** + * Event-level change-feed listener: one committed event changed the raw `view` + * result of at least one client-visible unit by `Object.is` for one session. + * `changes` holds one entry per such unit in registration order, each with the + * unit's `key` and its schema-validated view as `val`; `seq` is the seq of the + * causing event. + */ +type ProjectionEventChangeListener = ( + session: Session, + changes: readonly { readonly key: Extract; readonly val: unknown }[], + seq: SessionSeq, +) => void +``` + +`snapshot(session)` 完全同步:载体在切出页面切片的同一 tick 内读取它,因此 `asOfSeq` 使两次读取使用同一个序号。它只返回客户端视图,并在返回前通过各单元的 `viewSchema` 校验。`handle.stateOf(session)` 可在不计算无关视图的情况下读取一份实时 host 状态;调用方不得修改这一借用引用。state 引用变化时,注册表计算并缓存一次原始 view;只有该结果通过 `Object.is` 判定为变化时才触发变更流,对象 view 若要在仅内部 state 变化时抑制发布就必须保留引用。一个已提交事件驱动完所有单元后,事件级变更流以该事件改变了视图的全部客户端可见 key 调用每个 `onEventChanged` 监听器一次;未改变任何客户端视图的事件不产生事件级调用。 ## 摘要读取 @@ -346,6 +361,18 @@ register( definition: ProjectionDefinition & { key: E */ onChanged(listener: ProjectionChangeListener): () => void +/** + * Subscribe to the event-level change feed. The registration is an effect on + * the calling context's fiber. The listener runs synchronously inside the + * committed event's `session/event` handling, once after every unit has been + * driven and after every {@link onChanged} call for that event. If a unit or + * an {@link onChanged} listener throws during that drive, the listener still + * receives the changes made before the throw. + * @param listener - called once per committed event that changed at least one client-visible unit's raw view by `Object.is`. + * @returns the exact disposer that unsubscribes. + */ +onEventChanged(listener: ProjectionEventChangeListener): () => void + /** * One consistent cut over every registered client-visible unit for one session, read from * the watermark cache (missing cells fold lazily over the in-memory log). diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index fb3e56ee87..7a0ad908d9 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -998,10 +998,10 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable /** - * Subscribe to sparse Session projection changes. + * Subscribe to Session projection changes. * @param request - target Session. * @param signal - subscription cancellation. - * @returns readiness and sparse projection changes. + * @returns readiness followed by one projection change frame per committed event. */ @Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index fb26a5105c..ec9fab642f 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -1002,10 +1002,10 @@ workspaceDesktop(): { name: string; available: boolean; fileManager: 'finder' | @Remote({ mode: 'stream' }) observeEvent(request: SessionObserveEventRequest, signal: AbortSignal): AsyncIterable /** - * Subscribe to sparse Session projection changes. + * Subscribe to Session projection changes. * @param request - target Session. * @param signal - subscription cancellation. - * @returns readiness and sparse projection changes. + * @returns readiness followed by one projection change frame per committed event. */ @Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable diff --git a/docs/subsystems/slots.i18n.yaml b/docs/subsystems/slots.i18n.yaml index 0a2bb60f40..e5b5c959fc 100644 --- a/docs/subsystems/slots.i18n.yaml +++ b/docs/subsystems/slots.i18n.yaml @@ -3,8 +3,8 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/slots.md /web-client-slots: - en: 808a284f5a4280b5 - zh: 1650d6c3a94eae6e + en: 9df94e585e2e4809 + zh: ecc4f05a2cc54b31 /web-client-slots/declaration-and-lifecycle: en: f2d2c0d3b8f14ec7 zh: 441ed13ff3f81d2a diff --git a/docs/subsystems/slots.md b/docs/subsystems/slots.md index fe8589f685..87f36a0951 100644 --- a/docs/subsystems/slots.md +++ b/docs/subsystems/slots.md @@ -14,6 +14,8 @@ The root-scoped lists `sidebar.panellist.actions`, `conversation.session.header. [ui-workspace](../../packages/client/ui-workspace/README.md#understand-the-implementation) documents Session-row extension positions, visibility, and keyboard behavior. +[ui-settings](../../packages/client/ui-settings/README.md#filling-the-settings-slots) documents the settings page and navigation-icon extension points. + ## Declaration and lifecycle `SlotMap` is the compile-time registry. A package declaration-merges the key, cardinality, scope, owner props, keyed props, and optional slot-level inject face. The runtime declaration is the matching `children` entry on the component that owns the render location. diff --git a/docs/subsystems/slots.zh.md b/docs/subsystems/slots.zh.md index 288b4b85f1..8b70a28100 100644 --- a/docs/subsystems/slots.zh.md +++ b/docs/subsystems/slots.zh.md @@ -14,6 +14,8 @@ root 作用域的 list `sidebar.panellist.actions`、`conversation.session.heade [ui-workspace](../../packages/client/ui-workspace/README.zh.md#understand-the-implementation) 记录 Session 行的扩展位置、显示条件和键盘行为。 +[ui-settings](../../packages/client/ui-settings/README.zh.md#filling-the-settings-slots) 记录设置页面与导航图标扩展点。 + ## 声明与生命周期 `SlotMap` 是编译期注册表。包通过声明合并写入 key、cardinality(基数)、scope、owner props、keyed props 与可选的 slot 级 inject face。运行时声明则是拥有该渲染位置的组件在 `children` 中给出的对应条目。 diff --git a/docs/subsystems/subagent.i18n.yaml b/docs/subsystems/subagent.i18n.yaml index 21fa5dbbde..b2d7d88b37 100644 --- a/docs/subsystems/subagent.i18n.yaml +++ b/docs/subsystems/subagent.i18n.yaml @@ -3,26 +3,26 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write docs/subsystems/subagent.md /subagents: - en: 9d48a27a49585a3d - zh: 89da32c8a16c290a + en: 3d828004dee084c6 + zh: f71296b677691151 /subagents/capabilities-and-activation-requests: - en: 8c92b131f67997f6 - zh: c2dc606a0859420c + en: f09270fcd7bfa26a + zh: 082664920b3c65e2 /subagents/local-children-and-activations: en: 6f87231d18d82916 zh: 9f064b23058f8766 /subagents/messages-and-interruption: - en: 623b06b3c12540bc - zh: f56c6341e1c62768 + en: 9befacb931520842 + zh: c214b4fffa779b06 /subagents/durable-enumeration: - en: 30c3607a969696ce - zh: e6359cdf22b1e235 + en: e02e1703b183594c + zh: 130d475a4304f453 /subagents/results-and-backend-handles: en: 69ea5bed7d9fb64a zh: b187a822b813e80a /subagents/the-provider-contract-subagentprovider: en: 226ba8094a8cf96c zh: 719678662905d1eb -/subagents/durable-enumeration-listchildren-listdescendants-and-their-entries: - en: d8ce7969b65ad86e - zh: d39dac6592681bf2 +/subagents/durable-enumeration-listdescendants-and-catalog-entries: + en: 8000138f84fd15fa + zh: 32fa91d3aebd3d01 diff --git a/docs/subsystems/subagent.md b/docs/subsystems/subagent.md index b54ce57175..0e3235cf91 100644 --- a/docs/subsystems/subagent.md +++ b/docs/subsystems/subagent.md @@ -2,13 +2,13 @@ English | [中文](subagent.zh.md) -The unified activation API manages local conversations and external executions. +The unified activation API manages local conversations and external executions. Creation ancestry, runtime ownership, and communication belong to the subagent tree. [Subagent controls](../../packages/subagent/tool-subagent-control/README.md) own agent identity and exact-caller inbox waiting; Team tools add shared tasks and task policy. ## Capabilities and activation requests Every backend uses startActivation. Capability flags validate request options; prepareContinuable selects local Agent creation, while start selects one external execution. The model-facing tool uses parent delivery. Workflow and code mode consumers can await caller results without injecting another parent message. Historical children with unavailable descriptors remain discoverable as `mode: 'unknown'` without granting continuation capabilities; the [package README](../../packages/subagent/subagent/README.md) defines catalog persistence. -Optional `request.cwd` selects the child's initial directory; relative paths resolve against the parent's current effective directory. Omitting it captures that directory at admission. Local child Sessions retain the parent's original project, and cold resume retains their logged directory state. +Optional `cwd` selects the child's initial directory; relative paths resolve against the parent's current effective directory. Omitting it captures that directory at admission. Local child Sessions retain the parent's original project, and cold resume retains their logged directory state. ```ts type-equiv /** @@ -28,15 +28,13 @@ interface SubagentCapabilities { ```ts type-equiv /** One managed child execution and its result delivery policy. */ -interface SubagentActivationSpec { +interface SubagentActivationSpec extends Omit { /** Registered backend to use. */ readonly provider: string /** Short task label retained in cataloged child membership. */ readonly label: string /** Optional reserved identity for a local child; external backends allocate their own ids. */ readonly childId?: SessionId - /** Task, parent, and backend-supported execution options. */ - readonly request: Omit /** Cancellation before publication; callers own later cancellation through dispose. */ readonly signal: AbortSignal /** Parent delivery notifies the model; caller delivery only returns the result. Local children always enter the parent catalog. */ @@ -56,16 +54,15 @@ interface SubagentActivation { * Teardown failures are reported by dispose() without replacing a captured result. */ readonly result: Promise - /** Stop and release this activation and its owned descendants; rejects on teardown failure. */ + /** Stop and release only this activation; rejects on teardown failure. */ dispose(): Promise } ``` ```ts type-equiv /** - * Task and optional capabilities supplied to a backend. startActivation carries - * these fields in request while owning its label, cancellation, and delivery - * policy separately. + * Task and optional capabilities supplied to a backend. The activation spec + * shares these task options and defines its own label and cancellation policy. */ interface SubagentStartRequest { /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */ @@ -173,7 +170,7 @@ interface ContinuableCreateSpec { ## Messages and interruption -sendMessage authorizes the exact live sender and permits only adjacent local agents. Running children receive steering input; absent continuable children resume from persistence. External executions reject follow-ups. Both local and external executions automatically report their final text, structured result, diagnostic, and status in the parent settlement notice. Local children can also send messages through send_message. caller delivery suppresses settlement notices. drainDescendants and drainChildren await owned work teardown for local and external activations. +`sendMessage` requires the exact live sender and a target Session id in the same root tree. Root and continuable members can message across branches; admission revalidates the sender and root. Running targets receive Steer; only an absent target cold-resumes, while its creation ancestors may remain offline. External executions reject follow-ups. Local and external executions report final text, structured output, diagnostics, and status to their direct creator only while it is online; caller delivery suppresses those notices. `drainDescendants` awaits whole-tree teardown; an activation receipt’s `dispose()` releases only that execution. ```ts type-equiv /** Durable attribution for one model-authored message between Agents. */ @@ -200,13 +197,15 @@ interface SubagentSettledMessageSource { readonly form: 'notice' /** One-line account of how the child ended. */ readonly summary: string + /** Exact execution stop reason; absent on historical notices. Writers always include it. */ + readonly stopReason?: SubagentResult['stopReason'] /** Session id of the child that settled. */ readonly senderSessionId: SessionId } ``` ```ts type-equiv -/** Options for one model-authored message between adjacent Agents. */ +/** Options for one model-authored message within a subagent tree. */ interface SubagentSendMessageOptions { /** Caller cancellation, owning the operation only until inbox acceptance. */ readonly signal: AbortSignal @@ -215,18 +214,18 @@ interface SubagentSendMessageOptions { ```ts type-equiv /** - * Authority under which one interrupt request is admitted. `user` carries the - * durable direct-parent address a human client presented; `ancestor` carries - * the exact live Agent object whose recorded lineage must contain the caller. + * Authority under which one interrupt request is admitted. `user` is a trusted + * host operation; Remote callers need permission on the target Session before + * invoking it. `ancestor` carries an exact live Agent in the target's creation ancestry. */ type SubagentInterruptAuthority = - | { readonly kind: 'user'; readonly parentSessionId: SessionId } + | { readonly kind: 'user' } | { readonly kind: 'ancestor'; readonly agent: Agent } ``` ## Durable enumeration -`listChildren` reads the parent-owned catalog of all local children and parent-delivery external children. Caller-delivery external executions leave membership and result collection to their caller; local workflow children remain discoverable after completion. External entries carry `mode: 'external'` and cannot open a child Session or accept follow-ups. Catalog entries record membership at creation without execution status. `list_agents` exposes direct continuable children with `running` or `inactive` activity; see the [control tool](../../packages/subagent/tool-subagent-control/README.md#list_agents). +The parent-owned `subagentCatalog` projection lists all local children and parent-delivery external children. Caller-delivery external executions leave membership and result collection to their caller; local workflow children remain discoverable after completion. External entries carry `mode: 'external'` and cannot open a child Session or accept follow-ups. Catalog entries record membership at creation without execution status. `list_agents` exposes the root and reachable continuable descendants with `running` or `inactive` activity; see the [control tool](../../packages/subagent/tool-subagent-control/README.md#list_agents). ## Results and backend handles @@ -372,11 +371,11 @@ interface SubagentProvider { } ``` -## Durable enumeration: `listChildren()`, `listDescendants()`, and their entries +## Durable enumeration: `listDescendants()` and catalog entries The model-facing `list_agents` adapter reports current activity as `running` or `inactive`. These values do not describe task completion or guarantee that `send_message` will succeed. -`SubagentRuntime.listChildren(parentSessionId, signal?)` reads the parent's `subagentCatalog` view through a live-preferred Session observation and releases that observation on success or failure. It returns direct-child entries in parent event order without reading child logs or enumerating the Session corpus. Query failures propagate; a missing catalog projection fails explicitly. Browser rows derive membership from the shared projection store and add activity from Session status; the control stream pushes complete catalog updates. `listDescendants()` recursively reads those catalogs and derives `hasChildren` from each child catalog. [The parent-catalog Agent Note](../../.agents/notes/implemented/architecture/2026-09-01-parent-owned-subagent-catalog.md) owns creation, fork isolation, ordering, and persistence costs. +Direct-child entries are available as `observation.projections?.values.subagentCatalog` through `ctx.sessionQuery.observeSession(parentSessionId, { signal })`; callers release the observation with `using`. Entries follow parent event order without reading child logs or enumerating the Session corpus. Query failures propagate; a missing catalog projection means discovery is unavailable. Browser rows derive membership from the shared projection store and add activity from Session status; the control stream pushes complete catalog updates. `listDescendants()` recursively reads those catalogs and derives `hasChildren` from each child catalog. [The parent-catalog Agent Note](../../.agents/notes/implemented/architecture/2026-09-01-parent-owned-subagent-catalog.md) owns creation, fork isolation, ordering, and persistence costs. `SubagentRuntime.listDescendants(rootSessionId)` recursively calls the same catalog reader in stable pre-order, preserving each parent's event order. External entries are leaves without local Sessions. One-shot and unknown-mode entries remain traversal nodes; unknown modes produce `unsupported` diagnostics. An unreadable child catalog produces `corrupt` or `unavailable` and stops only that branch. Root read failures, missing services or projections, and cancellation reject the listing. Each reachable catalog is observed once and released before the next read; repeated ids and cycles are skipped. Sessions absent from reachable catalogs are not discovered, including ordinary Session forks and any subagents below those forks. Each row carries its catalog parent and root-relative depth: @@ -437,32 +436,39 @@ startActivation(spec: SubagentActivationSpec & { readonly childId: SessionId }): startActivation(spec: SubagentActivationSpec): Promise /** - * Join progressing descendants without cancelling them. Idle descendants whose - * inboxes require a later wake stay resident and do not delay host completion. - * @param parent - the exact parent whose descendant work is observed. - * @returns whether work was joined; hosts recheck parent idle after true. + * Resolve the root shared by an Agent and its other agents in its subagent tree. + * @param caller - exact live Agent whose subagent ancestry selects the tree. + * @returns the live root; ordinary Session forks lead independent trees. + * @throws when the caller or its runtime owner is unavailable. */ -async waitForChildren(parent: Agent): Promise +rootOf(caller: Agent): Agent /** - * Steer one model-authored message to the sender's direct parent or direct - * continuable child. A running target admits it at the nearest step boundary; - * an idle target starts a turn, and an absent direct child cold-resumes from - * persistence. The service derives durable sender attribution from the exact - * live sender. Caller cancellation stops only pre-acceptance work. - * @param sender - exact live Agent authorizing and originating the message. - * @param targetId - durable direct-parent or direct-child session id. + * Join progressing subagent tree work for its root. Idle members with parked input + * stay resident without delaying host completion. Ordinary members return false. + * @param root - exact live subagent tree root whose member work is awaited. + * @returns whether work was joined; hosts recheck root idle after true. + */ +async waitForTreeWork(root: Agent): Promise + +/** + * Steer one model-authored message to another member of the same subagent tree. + * A running target receives it at its next step; an idle target starts a turn. + * A cold target resumes under its runtime subagent tree root without restoring + * its creation ancestors. Sender identity is rechecked before inbox acceptance; cancellation + * stops only pre-acceptance work and never retracts an accepted message. + * @param sender - exact live root or resident continuable Agent originating the message. + * @param targetId - another root or continuable member's durable Session id. * @param content - model-authored content to deliver. * @param options - caller cancellation before inbox acceptance. * @returns the accepted message's inbox id. - * @throws when continuation services are unavailable, adjacency is rejected, - * or the message was not admitted. + * @throws when the target is outside the tree, cannot resume, or rejects input. */ async sendMessage( sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions, ): Promise /** - * Interrupt one live child's current execution under a human parent - * address or an exact live ancestor Agent. Fire-and-return: the cancel + * Interrupt one live child's current execution under a trusted user + * operation or an exact live ancestor Agent. Fire-and-return: the cancel * signal is issued before this returns, but the target may keep running * until it observes the signal. Unclaimed pending inbox work, the Activation, * and published descendants are preserved; claimed work is not requeued. @@ -471,47 +477,22 @@ async sendMessage( sender: Agent, targetId: SessionId, content: ContentBlock[], * is an accepted no-op, as is a manager-less composition, which cannot own a * live Activation. * @param targetSessionId - the durable child session id to interrupt. - * @param authority - the human parent address or exact live ancestor Agent. + * @param authority - a trusted user operation or exact live ancestor Agent. * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the * live target. */ interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void /** - * Close subagent admission below exact live parent Agents, stop only their - * visible descendant Activations synchronously, then await admitted scoped - * materializations and release those forests child-first. The scoped cutoff - * lasts until each exact parent leaves the registry; unrelated parent trees - * remain live. - * @param parents - exact host-owned parent Agents entering teardown. - * @returns once every retained descendant activation released its execution handle. + * Close admission and stop all instances in the selected subagent trees, then await + * pending startup and cleanup. Ordinary members are ignored. The cutoff lasts + * until each exact root leaves the registry; unrelated subagent trees remain live. + * @param parents - exact live subagent tree roots entering teardown. + * @returns once all admitted startup and member cleanup have settled. * @throws an aggregate error after all branches settle when any failed. */ async drainDescendants(parents: readonly Agent[]): Promise -/** - * Release selected resident direct children of one exact live - * parent. Other children of the same parent remain admitted and resident. - * Absent targets and a manager-less composition are accepted no-ops. - * @param parent - exact live direct parent authorizing the selected release. - * @param childIds - durable direct-child ids to release when resident. - * @returns once every selected activation released its execution handle. - * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a - * different parent or the supplied parent identity is stale. - */ -async drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise - -/** - * Read the parent's durable direct-child catalog without loading or resuming an Agent. - * The service owns and releases the live-preferred Session observation. - * @param parentSessionId - parent whose direct children are requested. - * @param signal - cancellation forwarded to the Session query. - * @returns catalog children in parent event order. - * @throws {@link SubagentError} when query or catalog projection is unavailable. - * @throws SessionQueryError when the parent cannot be read or the query is cancelled. - */ -listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise - /** * Recursively list reachable parent catalogs in stable pre-order, preserving * each catalog's event order. Each row carries its catalog parent and depth; @@ -531,8 +512,8 @@ listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise /** - * Deliver one browser-authored message to a continuable child through the - * exact live direct parent, retaining the caller-minted request identity and + * Deliver one browser-authored message to a continuable child through its + * live subagent tree root, retaining the caller-minted request identity and * validated browser zone on the accepted message. Success identifies the * message the child's inbox accepted; later execution is independent of this * call. Queue delivery targets a later turn; steer delivery targets the @@ -540,31 +521,27 @@ listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise +@Remote({ name: 'prompt', resources: { session: request => request.childSessionId } }) async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise /** - * Remote face of {@link interrupt} under one durable parent address. No - * catalog, history, persistence, or parent Agent lookup runs: the core - * primitive alone authorizes the address against the live Activation, which - * is what keeps a live child interruptible while its parent Agent is offline. + * Remote face of {@link interrupt}, authorized on the target Session by the Gateway. + * No catalog, history, persistence, or parent Agent lookup runs. * Absent, idle, and already-completed targets are accepted no-ops there. * @param childSessionId - durable child session id to interrupt. - * @param parentSessionId - durable direct parent whose authority is claimed. - * @param mode - required continuable-address discriminator. * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent. * @throws {RemoteError} `gateway/bad-request` for an empty id, - * `subagent/unauthorized` when the address does not own the live target, * otherwise `gateway/internal`. */ -@Remote('interruptByParent') interruptByParent( childSessionId: SessionId, parentSessionId: SessionId, mode: 'continuable', ): SubagentInterruptReceipt +@Remote({ name: 'interruptByUser', resources: { session: childSessionId => childSessionId } }) interruptByUser(childSessionId: SessionId): SubagentInterruptReceipt /** * Register a provider under its name. Registration is effect-scoped and HMR @@ -582,12 +559,6 @@ registerProvider(provider: SubagentProvider): () => void * @returns the provider, or undefined when absent. */ getProvider(name: string): SubagentProvider | undefined - -/** - * List registered provider names in insertion order. - * @returns the registered names. - */ -list(): string[] ``` Types: [Agent](core.md) · [ContentBlock](llm-streaming.md) · [MessageId](llm-streaming.md) · [SessionId](core.md) @@ -602,14 +573,14 @@ Source: [`packages/subagent/subagent/src/index.ts`](../../packages/subagent/suba #### `subagent/end` — emit -A published child settled. Scope-filtered dispatch uses the same delegating parent carrier as `subagent/start`, so the lifecycle pair reaches the same scoped audience. +A published child settled. Scope-filtered dispatch uses the same subagent tree-root carrier as `subagent/start`, so the lifecycle pair reaches the same scoped audience. ```ts cordis-catalog /** - * A published child settled. Scope-filtered dispatch uses the same delegating - * parent carrier as `subagent/start`, so the lifecycle pair reaches the + * A published child settled. Scope-filtered dispatch uses the same subagent tree-root + * carrier as `subagent/start`, so the lifecycle pair reaches the * same scoped audience. - * @param info - the run identity and terminal outcome. + * @param info - run identity, durable direct creator `parentSessionId`, and terminal outcome. * @mode emit */ 'subagent/end'(this: Scoped, info: SubagentRunEndInfo): void @@ -657,16 +628,16 @@ Source: [`packages/subagent/subagent/src/index.ts`](../../packages/subagent/suba #### `subagent/start` — emit -A provider established a published child. For in-process providers, `ctx.agents.get(info.id)` resolves during this notification. Scope-filtered dispatch keys the carrier by the delegating parent, so a parent-scoped listener observes only its own delegations. Paired with `subagent/end`. +A provider established a published child. For in-process providers, `ctx.agents.get(info.id)` resolves during this notification. Scope-filtered dispatch keys the carrier by the subagent tree root, so a root-scoped listener observes all subagent tree activations. Paired with `subagent/end`. ```ts cordis-catalog /** * A provider established a published child. For in-process providers, * `ctx.agents.get(info.id)` resolves during this notification. - * Scope-filtered dispatch keys the carrier by the delegating parent, so a - * parent-scoped listener observes only its own delegations. Paired with + * Scope-filtered dispatch keys the carrier by the subagent tree root, so a + * root-scoped listener observes all subagent tree activations. Paired with * `subagent/end`. - * @param info - the provider and published child identity. + * @param info - provider, child identity, and durable direct creator `parentSessionId`. * @mode emit */ 'subagent/start'(this: Scoped, info: SubagentRunInfo): void diff --git a/docs/subsystems/subagent.zh.md b/docs/subsystems/subagent.zh.md index 0ca87c8503..785644d1cf 100644 --- a/docs/subsystems/subagent.zh.md +++ b/docs/subsystems/subagent.zh.md @@ -2,13 +2,13 @@ [English](subagent.md) | 中文 -统一的 activation API 管理本地会话和外部执行。 +统一的 activation API 管理本地对话和外部执行。创建祖先关系、运行归属和通信由 subagent 树管理。[subagent 控制工具](../../packages/subagent/tool-subagent-control/README.zh.md)负责 agent 身份和当前调用者的收件箱等待;Team 工具添加共享任务与任务策略。 ## 能力与 activation 请求 所有后端都使用 startActivation。能力标记校验请求选项;prepareContinuable 选择本地 Agent 创建,start 选择一次外部执行。面向模型的工具采用 parent 回传。Workflow 与 code mode 消费者可以等待 caller 结果,不额外向父代理注入消息。历史子会话的 descriptor 不可用时,以 `mode: 'unknown'` 保持可发现性,但不授予继续执行能力;[包 README](../../packages/subagent/subagent/README.zh.md) 定义目录持久化语义。 -可选的 `request.cwd` 指定子级的初始目录;相对路径以父级当前有效目录为基准解析。省略时,在准入阶段捕获该目录。本地子 Session 保留父级的原始项目,冷恢复保留其日志中的目录状态。 +可选的 `cwd` 指定子级的初始目录;相对路径以父级当前有效目录为基准解析。省略时,在准入阶段捕获该目录。本地子 Session 保留父级的原始项目,冷恢复保留其日志中的目录状态。 ```ts type-equiv /** @@ -28,15 +28,13 @@ interface SubagentCapabilities { ```ts type-equiv /** One managed child execution and its result delivery policy. */ -interface SubagentActivationSpec { +interface SubagentActivationSpec extends Omit { /** Registered backend to use. */ readonly provider: string /** Short task label retained in cataloged child membership. */ readonly label: string /** Optional reserved identity for a local child; external backends allocate their own ids. */ readonly childId?: SessionId - /** Task, parent, and backend-supported execution options. */ - readonly request: Omit /** Cancellation before publication; callers own later cancellation through dispose. */ readonly signal: AbortSignal /** Parent delivery notifies the model; caller delivery only returns the result. Local children always enter the parent catalog. */ @@ -56,16 +54,15 @@ interface SubagentActivation { * Teardown failures are reported by dispose() without replacing a captured result. */ readonly result: Promise - /** Stop and release this activation and its owned descendants; rejects on teardown failure. */ + /** Stop and release only this activation; rejects on teardown failure. */ dispose(): Promise } ``` ```ts type-equiv /** - * Task and optional capabilities supplied to a backend. startActivation carries - * these fields in request while owning its label, cancellation, and delivery - * policy separately. + * Task and optional capabilities supplied to a backend. The activation spec + * shares these task options and defines its own label and cancellation policy. */ interface SubagentStartRequest { /** Initial child directory; relative paths resolve against the parent's current directory. Omitted inherits that directory at start. */ @@ -173,7 +170,7 @@ interface ContinuableCreateSpec { ## 消息与中断 -sendMessage 根据确切的在线发送者实例授权,仅允许相邻本地代理通信。运行中的子代理接收引导输入;不在线的可继续子代理从持久化恢复。外部执行拒绝后续消息。本地与外部执行都会通过父级结束通知自动回传最终文本、结构化结果、诊断和状态。本地子代理也可以通过 send_message 发送消息。caller 回传会抑制结束通知。drainDescendants 与 drainChildren 对本地和外部 activation 都等待所属任务清理完成。 +`sendMessage` 要求确切在线发送方和同一根树中的目标 Session id。根和可继续成员可跨分支发消息;接纳时重新校验发送方和根。运行中目标接收 Steer;只冷恢复不在线的目标,其创建祖先可以保持离线。外部执行拒绝后续输入。本地和外部执行仅向仍在线的直接创建者报告最终文本、结构化输出、诊断和状态;caller 投递抑制这些通知。`drainDescendants` 等待整棵树释放;activation 回执的 `dispose()` 仅释放那一次执行。 ```ts type-equiv /** Durable attribution for one model-authored message between Agents. */ @@ -200,13 +197,15 @@ interface SubagentSettledMessageSource { readonly form: 'notice' /** One-line account of how the child ended. */ readonly summary: string + /** Exact execution stop reason; absent on historical notices. Writers always include it. */ + readonly stopReason?: SubagentResult['stopReason'] /** Session id of the child that settled. */ readonly senderSessionId: SessionId } ``` ```ts type-equiv -/** Options for one model-authored message between adjacent Agents. */ +/** Options for one model-authored message within a subagent tree. */ interface SubagentSendMessageOptions { /** Caller cancellation, owning the operation only until inbox acceptance. */ readonly signal: AbortSignal @@ -215,18 +214,18 @@ interface SubagentSendMessageOptions { ```ts type-equiv /** - * Authority under which one interrupt request is admitted. `user` carries the - * durable direct-parent address a human client presented; `ancestor` carries - * the exact live Agent object whose recorded lineage must contain the caller. + * Authority under which one interrupt request is admitted. `user` is a trusted + * host operation; Remote callers need permission on the target Session before + * invoking it. `ancestor` carries an exact live Agent in the target's creation ancestry. */ type SubagentInterruptAuthority = - | { readonly kind: 'user'; readonly parentSessionId: SessionId } + | { readonly kind: 'user' } | { readonly kind: 'ancestor'; readonly agent: Agent } ``` ## 持久枚举 -`listChildren` 读取父级拥有的目录,其中包含所有本地子级及 parent 投递的外部子级。caller 投递的外部执行由调用方负责成员关系与结果收集;本地工作流子级在完成后仍可被发现。外部条目携带 `mode: 'external'`,不能打开子 Session 或接受后续消息。目录在创建时记录成员关系,不携带执行状态。`list_agents` 展示可继续的直接子级,其活跃状态为 `running` 或 `inactive`;参见[控制工具](../../packages/subagent/tool-subagent-control/README.zh.md#list_agents)。 +父级拥有的 `subagentCatalog` 投影列出所有本地子级及 parent 投递的外部子级。caller 投递的外部执行由调用方负责成员关系与结果收集;本地工作流子级在完成后仍可被发现。外部条目携带 `mode: 'external'`,不能打开子 Session 或接受后续消息。目录在创建时记录成员关系,不携带执行状态。`list_agents` 展示根和可达的可继续后代,其活跃状态为 `running` 或 `inactive`;参见[控制工具](../../packages/subagent/tool-subagent-control/README.zh.md#list_agents)。 ## 结果与后端句柄 @@ -372,11 +371,11 @@ interface SubagentProvider { } ``` -## 持久化枚举:`listChildren()`、`listDescendants()` 与其条目 +## 持久化枚举:`listDescendants()` 与目录条目 模型侧的 `list_agents` 适配器将当前活动表示为 `running` 或 `inactive`。这些值不描述任务完成情况,也不保证 `send_message` 会成功。 -`SubagentRuntime.listChildren(parentSessionId, signal?)` 通过优先使用在线 Session 的观察读取父会话的 `subagentCatalog` 视图,并在成功或失败时释放观察。它按父会话事件顺序返回直接子级条目,不读取子级日志,也不枚举 Session 语料库。查询失败直接传播;缺少目录投影时显式失败。浏览器条目从共享 projection store 派生成员关系,并从 Session 状态补充活动状态;control stream 推送完整目录更新。`listDescendants()` 递归读取这些目录,并从每个子级目录推导 `hasChildren`。[父目录 Agent Note](../../.agents/notes/implemented/architecture/2026-09-01-parent-owned-subagent-catalog.zh.md) 说明创建、fork 隔离、排序和持久化成本。 +通过 `ctx.sessionQuery.observeSession(parentSessionId, { signal })`,可从 `observation.projections?.values.subagentCatalog` 获取直接子级条目;调用方使用 `using` 释放观察对象。条目遵循父会话事件顺序,不读取子级日志,也不枚举 Session 语料库。查询失败直接传播;缺少目录投影意味着发现功能不可用。浏览器条目从共享 projection store 派生成员关系,并从 Session 状态补充活动状态;control stream 推送完整目录更新。`listDescendants()` 递归读取这些目录,并从每个子级目录推导 `hasChildren`。[父目录 Agent Note](../../.agents/notes/implemented/architecture/2026-09-01-parent-owned-subagent-catalog.zh.md) 说明创建、fork 隔离、排序和持久化成本。 `SubagentRuntime.listDescendants(rootSessionId)` 以稳定前序递归调用同一目录读取函数,保留每个父级的事件顺序。外部条目是没有本地 Session 的叶节点。一次性和未知模式条目仍是遍历节点;未知模式产生 `unsupported` 诊断。无法读取的子级目录产生 `corrupt` 或 `unavailable`,只停止该分支。根读取失败、服务或投影缺失、取消会使整个查询失败。每个可达目录只观察一次,并在下一次读取前释放;重复 id 和循环引用会被跳过。可达目录中不存在的 Session 不会被发现,包括普通 Session fork 及其下的子 agent。每行携带目录中的父级和相对根的深度: @@ -439,32 +438,39 @@ startActivation(spec: SubagentActivationSpec & { readonly childId: SessionId }): startActivation(spec: SubagentActivationSpec): Promise /** - * Join progressing descendants without cancelling them. Idle descendants whose - * inboxes require a later wake stay resident and do not delay host completion. - * @param parent - the exact parent whose descendant work is observed. - * @returns whether work was joined; hosts recheck parent idle after true. + * Resolve the root shared by an Agent and its other agents in its subagent tree. + * @param caller - exact live Agent whose subagent ancestry selects the tree. + * @returns the live root; ordinary Session forks lead independent trees. + * @throws when the caller or its runtime owner is unavailable. */ -async waitForChildren(parent: Agent): Promise +rootOf(caller: Agent): Agent /** - * Steer one model-authored message to the sender's direct parent or direct - * continuable child. A running target admits it at the nearest step boundary; - * an idle target starts a turn, and an absent direct child cold-resumes from - * persistence. The service derives durable sender attribution from the exact - * live sender. Caller cancellation stops only pre-acceptance work. - * @param sender - exact live Agent authorizing and originating the message. - * @param targetId - durable direct-parent or direct-child session id. + * Join progressing subagent tree work for its root. Idle members with parked input + * stay resident without delaying host completion. Ordinary members return false. + * @param root - exact live subagent tree root whose member work is awaited. + * @returns whether work was joined; hosts recheck root idle after true. + */ +async waitForTreeWork(root: Agent): Promise + +/** + * Steer one model-authored message to another member of the same subagent tree. + * A running target receives it at its next step; an idle target starts a turn. + * A cold target resumes under its runtime subagent tree root without restoring + * its creation ancestors. Sender identity is rechecked before inbox acceptance; cancellation + * stops only pre-acceptance work and never retracts an accepted message. + * @param sender - exact live root or resident continuable Agent originating the message. + * @param targetId - another root or continuable member's durable Session id. * @param content - model-authored content to deliver. * @param options - caller cancellation before inbox acceptance. * @returns the accepted message's inbox id. - * @throws when continuation services are unavailable, adjacency is rejected, - * or the message was not admitted. + * @throws when the target is outside the tree, cannot resume, or rejects input. */ async sendMessage( sender: Agent, targetId: SessionId, content: ContentBlock[], options: SubagentSendMessageOptions, ): Promise /** - * Interrupt one live child's current execution under a human parent - * address or an exact live ancestor Agent. Fire-and-return: the cancel + * Interrupt one live child's current execution under a trusted user + * operation or an exact live ancestor Agent. Fire-and-return: the cancel * signal is issued before this returns, but the target may keep running * until it observes the signal. Unclaimed pending inbox work, the Activation, * and published descendants are preserved; claimed work is not requeued. @@ -473,47 +479,22 @@ async sendMessage( sender: Agent, targetId: SessionId, content: ContentBlock[], * is an accepted no-op, as is a manager-less composition, which cannot own a * live Activation. * @param targetSessionId - the durable child session id to interrupt. - * @param authority - the human parent address or exact live ancestor Agent. + * @param authority - a trusted user operation or exact live ancestor Agent. * @throws {SubagentError} `UNAUTHORIZED` when the authority does not own the * live target. */ interrupt(targetSessionId: SessionId, authority: SubagentInterruptAuthority): void /** - * Close subagent admission below exact live parent Agents, stop only their - * visible descendant Activations synchronously, then await admitted scoped - * materializations and release those forests child-first. The scoped cutoff - * lasts until each exact parent leaves the registry; unrelated parent trees - * remain live. - * @param parents - exact host-owned parent Agents entering teardown. - * @returns once every retained descendant activation released its execution handle. + * Close admission and stop all instances in the selected subagent trees, then await + * pending startup and cleanup. Ordinary members are ignored. The cutoff lasts + * until each exact root leaves the registry; unrelated subagent trees remain live. + * @param parents - exact live subagent tree roots entering teardown. + * @returns once all admitted startup and member cleanup have settled. * @throws an aggregate error after all branches settle when any failed. */ async drainDescendants(parents: readonly Agent[]): Promise -/** - * Release selected resident direct children of one exact live - * parent. Other children of the same parent remain admitted and resident. - * Absent targets and a manager-less composition are accepted no-ops. - * @param parent - exact live direct parent authorizing the selected release. - * @param childIds - durable direct-child ids to release when resident. - * @returns once every selected activation released its execution handle. - * @throws {SubagentError} `UNAUTHORIZED` when a resident target belongs to a - * different parent or the supplied parent identity is stale. - */ -async drainChildren(parent: Agent, childIds: readonly SessionId[]): Promise - -/** - * Read the parent's durable direct-child catalog without loading or resuming an Agent. - * The service owns and releases the live-preferred Session observation. - * @param parentSessionId - parent whose direct children are requested. - * @param signal - cancellation forwarded to the Session query. - * @returns catalog children in parent event order. - * @throws {@link SubagentError} when query or catalog projection is unavailable. - * @throws SessionQueryError when the parent cannot be read or the query is cancelled. - */ -listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise - /** * Recursively list reachable parent catalogs in stable pre-order, preserving * each catalog's event order. Each row carries its catalog parent and depth; @@ -533,8 +514,8 @@ listChildren(parentSessionId: SessionId, signal?: AbortSignal): Promise /** - * Deliver one browser-authored message to a continuable child through the - * exact live direct parent, retaining the caller-minted request identity and + * Deliver one browser-authored message to a continuable child through its + * live subagent tree root, retaining the caller-minted request identity and * validated browser zone on the accepted message. Success identifies the * message the child's inbox accepted; later execution is independent of this * call. Queue delivery targets a later turn; steer delivery targets the @@ -542,31 +523,27 @@ listDescendants(rootSessionId: SessionId, signal?: AbortSignal): Promise +@Remote({ name: 'prompt', resources: { session: request => request.childSessionId } }) async prompt(request: SubagentPromptRequest, signal: AbortSignal): Promise /** - * Remote face of {@link interrupt} under one durable parent address. No - * catalog, history, persistence, or parent Agent lookup runs: the core - * primitive alone authorizes the address against the live Activation, which - * is what keeps a live child interruptible while its parent Agent is offline. + * Remote face of {@link interrupt}, authorized on the target Session by the Gateway. + * No catalog, history, persistence, or parent Agent lookup runs. * Absent, idle, and already-completed targets are accepted no-ops there. * @param childSessionId - durable child session id to interrupt. - * @param parentSessionId - durable direct parent whose authority is claimed. - * @param mode - required continuable-address discriminator. * @returns acknowledgement that the cancel signal was admitted, not that the target is quiescent. * @throws {RemoteError} `gateway/bad-request` for an empty id, - * `subagent/unauthorized` when the address does not own the live target, * otherwise `gateway/internal`. */ -@Remote('interruptByParent') interruptByParent( childSessionId: SessionId, parentSessionId: SessionId, mode: 'continuable', ): SubagentInterruptReceipt +@Remote({ name: 'interruptByUser', resources: { session: childSessionId => childSessionId } }) interruptByUser(childSessionId: SessionId): SubagentInterruptReceipt /** * Register a provider under its name. Registration is effect-scoped and HMR @@ -584,12 +561,6 @@ registerProvider(provider: SubagentProvider): () => void * @returns the provider, or undefined when absent. */ getProvider(name: string): SubagentProvider | undefined - -/** - * List registered provider names in insertion order. - * @returns the registered names. - */ -list(): string[] ``` Types: [Agent](core.zh.md) · [ContentBlock](llm-streaming.zh.md) · [MessageId](llm-streaming.zh.md) · [SessionId](core.zh.md) @@ -604,14 +575,14 @@ Source: [`packages/subagent/subagent/src/index.ts`](../../packages/subagent/suba #### `subagent/end` — emit -A published child settled. Scope-filtered dispatch uses the same delegating parent carrier as `subagent/start`, so the lifecycle pair reaches the same scoped audience. +A published child settled. Scope-filtered dispatch uses the same subagent tree-root carrier as `subagent/start`, so the lifecycle pair reaches the same scoped audience. ```ts cordis-catalog /** - * A published child settled. Scope-filtered dispatch uses the same delegating - * parent carrier as `subagent/start`, so the lifecycle pair reaches the + * A published child settled. Scope-filtered dispatch uses the same subagent tree-root + * carrier as `subagent/start`, so the lifecycle pair reaches the * same scoped audience. - * @param info - the run identity and terminal outcome. + * @param info - run identity, durable direct creator `parentSessionId`, and terminal outcome. * @mode emit */ 'subagent/end'(this: Scoped, info: SubagentRunEndInfo): void @@ -659,16 +630,16 @@ Source: [`packages/subagent/subagent/src/index.ts`](../../packages/subagent/suba #### `subagent/start` — emit -A provider established a published child. For in-process providers, `ctx.agents.get(info.id)` resolves during this notification. Scope-filtered dispatch keys the carrier by the delegating parent, so a parent-scoped listener observes only its own delegations. Paired with `subagent/end`. +A provider established a published child. For in-process providers, `ctx.agents.get(info.id)` resolves during this notification. Scope-filtered dispatch keys the carrier by the subagent tree root, so a root-scoped listener observes all subagent tree activations. Paired with `subagent/end`. ```ts cordis-catalog /** * A provider established a published child. For in-process providers, * `ctx.agents.get(info.id)` resolves during this notification. - * Scope-filtered dispatch keys the carrier by the delegating parent, so a - * parent-scoped listener observes only its own delegations. Paired with + * Scope-filtered dispatch keys the carrier by the subagent tree root, so a + * root-scoped listener observes all subagent tree activations. Paired with * `subagent/end`. - * @param info - the provider and published child identity. + * @param info - provider, child identity, and durable direct creator `parentSessionId`. * @mode emit */ 'subagent/start'(this: Scoped, info: SubagentRunInfo): void diff --git a/docs/subsystems/system-prompt.i18n.yaml b/docs/subsystems/system-prompt.i18n.yaml index acd90cbb02..707a80dd3a 100644 --- a/docs/subsystems/system-prompt.i18n.yaml +++ b/docs/subsystems/system-prompt.i18n.yaml @@ -6,8 +6,8 @@ en: 7ad02b2146520e7b zh: 93cb93c7aa12ceb4 /system-prompt-assembly/assembly-context: - en: a5d904293afc7fcb - zh: 555883610ac09646 + en: 26585a8664060a19 + zh: 2bbe792ef28f40e3 /system-prompt-assembly/tool-provider-result: en: 89cb015bf2e3e7a5 zh: b4340e853b34c777 diff --git a/docs/subsystems/system-prompt.md b/docs/subsystems/system-prompt.md index ee803c1dfc..b29547379a 100644 --- a/docs/subsystems/system-prompt.md +++ b/docs/subsystems/system-prompt.md @@ -23,6 +23,8 @@ interface AssembleContext { } ``` +`TOOL_APPLY_PATCH` takes order 1350 between `TOOL_EDIT` (1300) and `TOOL_GLOB` (1400). + ## Tool-provider result `ToolProviderResult.schemas` is the model-visible set for the current assembly. `knownNames` is the provider's pre-restriction name universe used to distinguish a configured-name typo from a known tool that is deliberately hidden in this scope. diff --git a/docs/subsystems/system-prompt.zh.md b/docs/subsystems/system-prompt.zh.md index fad3105e64..83c6d7564b 100644 --- a/docs/subsystems/system-prompt.zh.md +++ b/docs/subsystems/system-prompt.zh.md @@ -23,6 +23,8 @@ interface AssembleContext { } ``` +`TOOL_APPLY_PATCH` 的顺序为 1350,位于 `TOOL_EDIT`(1300)与 `TOOL_GLOB`(1400)之间。 + ## 工具提供方结果 `ToolProviderResult.schemas` 是当前组装中对模型可见的工具 schema 集合。`knownNames` 是提供方在限制前的名称全集,用于区分「配置名拼写错误」与「已知工具在此作用域中被有意隐藏」。 diff --git a/docs/subsystems/user-questions.md b/docs/subsystems/user-questions.md index 2a2463b475..2c86b22e1c 100644 --- a/docs/subsystems/user-questions.md +++ b/docs/subsystems/user-questions.md @@ -278,17 +278,16 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * Ask the scoped answerer waterfall and wait for the user's answer. * * When a caller supplies an agent, human interaction is valid only for the - * exact live runtime root. Runtime ownership, not durable session lineage, - * decides this boundary: an owned child has no human answerer and would - * block forever, while a lineage-bearing session resumed as a new runtime - * root may ask normally. + * exact live instance of an ordinary Session. Explicit subagent origin + * rejects delegated callers; historical ordinary forks may retain parent + * metadata and still ask normally. * * @param request Questions, owner agent, and abort signal. * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent is owned by another agent. + * that live agent has subagent origin. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/subsystems/user-questions.zh.md b/docs/subsystems/user-questions.zh.md index f433339045..ad39e1004f 100644 --- a/docs/subsystems/user-questions.zh.md +++ b/docs/subsystems/user-questions.zh.md @@ -278,17 +278,16 @@ async askTimed( request: AskUserQuestionRequest & { agent: Agent }, callId: Tool * Ask the scoped answerer waterfall and wait for the user's answer. * * When a caller supplies an agent, human interaction is valid only for the - * exact live runtime root. Runtime ownership, not durable session lineage, - * decides this boundary: an owned child has no human answerer and would - * block forever, while a lineage-bearing session resumed as a new runtime - * root may ask normally. + * exact live instance of an ordinary Session. Explicit subagent origin + * rejects delegated callers; historical ordinary forks may retain parent + * metadata and still ask normally. * * @param request Questions, owner agent, and abort signal. * @returns The answer chosen or typed by the human. * @throws {UserQuestionError} code `ASK_ABORTED` when the supplied signal * is already or becomes aborted, `CALLER_NOT_LIVE` when a supplied agent * is not the registry's exact live instance, or `DELEGATED_CALLER` when - * that live agent is owned by another agent. + * that live agent has subagent origin. */ async ask(request: AskUserQuestionRequest): Promise ``` diff --git a/docs/tool-catalog.i18n.yaml b/docs/tool-catalog.i18n.yaml index a41bd4c859..880989b55c 100644 --- a/docs/tool-catalog.i18n.yaml +++ b/docs/tool-catalog.i18n.yaml @@ -9,8 +9,8 @@ en: 6cc2cd9ced70bb09 zh: 1c0e6cb4ba2ed637 /tool-schema-catalog/tool-package-map: - en: 4d42222acd39d083 - zh: 8153a5065bf2ebd6 + en: 6e8419f195bc96a1 + zh: 564c4f04420d329a /tool-schema-catalog/deepseek-ai-dsh-plugin-manager: en: e0143916bb634762 zh: e0143916bb634762 @@ -128,6 +128,9 @@ /tool-schema-catalog/deepseek-ai-dsh-tool-fs: en: 07d595ce1f1a5184 zh: 07d595ce1f1a5184 +/tool-schema-catalog/deepseek-ai-dsh-tool-fs/apply-patch: + en: 882f2fa9fac236d6 + zh: e8320796a5cb038f /tool-schema-catalog/deepseek-ai-dsh-tool-fs/edit: en: 5b6a252adde51af6 zh: 7aa172a5d8b9cbd2 @@ -138,8 +141,8 @@ en: f6f7a1140066ce04 zh: d528e01a0939795a /tool-schema-catalog/deepseek-ai-dsh-tool-fs/write: - en: f80700c5d57e8d87 - zh: fb7cccbba0d8d486 + en: 22e7c232e157a1e2 + zh: 176da52cdd4765a9 /tool-schema-catalog/deepseek-ai-dsh-tool-fs-search: en: 703fea005ce84c50 zh: 703fea005ce84c50 @@ -186,17 +189,17 @@ en: 9fd2eccb1ee51372 zh: 9fd2eccb1ee51372 /tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-create: - en: 606fc2b8d62ba044 - zh: 7523e106168c2ab2 -/tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-delete: - en: 5fc994535c95cd6b - zh: 1910b545d7b92379 + en: 7237e492f01fb8fb + zh: 2fd2bea81919baf6 +/tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-edit: + en: 08db239b9e1c3e8f + zh: c3860a8f20a01965 /tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-list: - en: 5bcfc051e364df29 - zh: b77e60c123800eb1 -/tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-update: - en: b9f4691532157a1d - zh: 8a0597790dc5f999 + en: e2c657d431fd02a8 + zh: 7651bf05938eff69 +/tool-schema-catalog/deepseek-ai-dsh-tool-schedule/schedule-view: + en: 008cd46ab3c05305 + zh: 8ef5a0f40640013e /tool-schema-catalog/deepseek-ai-dsh-tool-lsp: en: 32982123b1f0e5bc zh: 32982123b1f0e5bc @@ -246,20 +249,23 @@ en: 207228068bc61885 zh: 36e9344ee1af8869 /tool-schema-catalog/deepseek-ai-dsh-tool-subagent/subagent: - en: 140c965c2b04d02f - zh: 95495dad5c77046d + en: 430672da3c1a6ca6 + zh: bd3a9ab4089f9dbb /tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control: en: ab82e130c3413f04 zh: ab82e130c3413f04 /tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/interrupt-agent: - en: 9190a32df5e10ddd + en: a622b15cc2598d51 zh: 48e1b05956d63e26 /tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/list-agents: - en: ae22e8543d123c39 - zh: 0991a73ef49bcdea + en: a56168133c21c6a0 + zh: f9df1c0fe49fa225 /tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/send-message: - en: 9d180d8811903366 - zh: d63f94cffcb952d1 + en: b53326fedeab850d + zh: ecb75b6ce31da009 +/tool-schema-catalog/deepseek-ai-dsh-tool-subagent-control/wait-agent: + en: f3cf5a0c56ddc07a + zh: 7f6754d71e1b4ae4 /tool-schema-catalog/deepseek-ai-dsh-tool-jobs: en: 9be673b1604d0114 zh: 9be673b1604d0114 @@ -270,38 +276,23 @@ en: 0c37fb1fed979d72 zh: 5ea9d07f5a4a8a6c /tool-schema-catalog/deepseek-ai-dsh-tool-jobs/job-output: - en: 1e084359a8cd42b3 - zh: 3f6c245dbbb2b920 -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team: - en: 6b1106f417b50db6 - zh: 6b1106f417b50db6 -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/interrupt-agent: - en: c3c7af05ceb9f8c9 - zh: ec379e0b42110c6a -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/list-agents: - en: f9457f033f75f00a - zh: a2d60ec44118c34c -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/send-message: - en: ec50e6a0b86aecc6 - zh: 29c8728536a5adf1 -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/spawn-teammate: - en: 02d6cc746e234b99 - zh: 49bc60ac098bca48 -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/team-task-create: - en: 91e84febe063c3bd - zh: 550555d0f44f603b -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/team-task-get: - en: 1c6ae0aba0b8041d - zh: f8d634387b74121d -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/team-task-list: - en: 2084d494aae8798a - zh: e4c136c91028a7b1 -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/team-task-update: - en: 2eac7360ba68b1bd - zh: b5d676bf288c245e -/tool-schema-catalog/deepseek-ai-dsh-experimental-tool-agent-team/wait-agent: - en: e70c77a45832bb28 - zh: 7d03bec294b65452 + en: 2977f731fb90d147 + zh: 4f422613ff720055 +/tool-schema-catalog/deepseek-ai-dsh-tool-agent-team: + en: 3f1a9c3509853972 + zh: 3f1a9c3509853972 +/tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-create: + en: ac9ed819b705b4b8 + zh: 306477d2d457369a +/tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-get: + en: bca1abf330638c19 + zh: 903bfa977f75c046 +/tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-list: + en: 8001eda7e9ff6a25 + zh: 2414761029f21404 +/tool-schema-catalog/deepseek-ai-dsh-tool-agent-team/team-task-update: + en: 9acd1c5b2fac9853 + zh: 3bd81e9cd1f1c28d /tool-schema-catalog/deepseek-ai-dsh-tool-todo: en: dea62d26fb18ff68 zh: dea62d26fb18ff68 diff --git a/docs/tool-catalog.md b/docs/tool-catalog.md index f3961a622e..1dea12b08f 100644 --- a/docs/tool-catalog.md +++ b/docs/tool-catalog.md @@ -30,20 +30,20 @@ This table connects model-visible tool names to the plugin package and service s | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent bash tool; deployment composition supplies the PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `an owning Agent at execution time` | `tool/call`, `PTY shell state`, `tool/result` | - | One owner-isolated persistent pwsh tool, the Windows counterpart of the persistent bash tool; deployment composition supplies a pwsh-dialect PTY backend and may override the model-facing environment description. | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`, `ctx.fs` | `tool/call`, `fs/observed after view presence/absence, edit absence, or successful mutation`, `tool/result` | - | Standalone view/create/unique literal replace/line insert tool over the filesystem seam; it composes with any shell or terminal API. | -| `@deepseek-ai/dsh-tool-fs` | `edit`, `read`, `read_image`, `write` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.systemPrompt`, `ctx.attachments (image-tool registration)`, `ctx.llm + an image-capable route (image-tool execution)` | `tool/call`, `fs/write-intent or fs/edit-intent for mutations`, `fs/observed after read presence/absence or successful file operation`, `durable attachment (read_image)`, `tool/result` | - | The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The image tool is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input. | +| `@deepseek-ai/dsh-tool-fs` | `apply_patch`, `edit`, `read`, `read_image`, `write` | `ctx.workingDirectory`, `ctx.tools`, `ctx.fs`, `ctx.systemPrompt`, `ctx.attachments (image-tool registration)`, `ctx.llm + an image-capable route (image-tool execution)` | `tool/call`, `fs/write-intent, fs/edit-intent, or fs/delete-intent for mutations`, `fs/observed after read presence/absence or successful file operation`, `durable attachment (read_image)`, `tool/result` | - | The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); the shipped compositions leave its row disabled, so mutations are unconditional unless a deployment enables it. The image tool is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input. `apply_patch` registers only with `applyPatch: true`; the catalog sets it so the schema is documented. `dsh-base` and the Web `standard` preset enable it; the Web `ptc` and `cordis` presets and the PTC overlay state `applyPatch: false`. | | `@deepseek-ai/dsh-tool-fs-search` | `glob`, `grep` | `ctx.workingDirectory`, `ctx.tools`, `ctx.subprocess`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | glob and grep are unconditional discovery tools that spawn the packaged ripgrep binary (`@vscode/ripgrep`) through ctx.subprocess as ordinary foreground calls (never background jobs) — no host `rg` install and no shell layer. The catalog uses `sampleOverCapGlobResults: true`; deployments must choose that behavior explicitly. Capped results save the complete formatted list through the optional ctx.spillStore backend; returned locators are follow-up-readable/searchable when the backend exposes local paths in co-located deployments. | | `@deepseek-ai/dsh-tool-terminal` | `terminal_close`, `terminal_list`, `terminal_open`, `terminal_read`, `terminal_send`, `terminal_signal` | `ctx.workingDirectory`, `ctx.tools`, `ctx.terminals`, `ctx.systemPrompt`, `ctx.jobs at call time for run_in_background` | `tool/call`, `tool/result` | - | The six terminal tools are opt-in and complement one-shot shell/filesystem tools. `terminal_send(run_in_background: true)` registers with `ctx.jobs`; TUI, named key sequences, BEL, resize, auto-start, and cross-agent sharing are absent from the schema. | | `@deepseek-ai/dsh-tool-goal` | `create_goal`, `get_goal`, `update_goal` | `ctx.tools`, `ctx.agents`, `ctx.goals`, `ctx.systemPrompt`, `a calling Agent in an authorized open turn` | `tool/call`, `goal/change for mutations`, `tool/result` | - | create, edit, pause, and resume require direct-human root authority; complete and blocked also accept the exact current goal round. The default blocked lower bound is three admitted rounds. | -| `@deepseek-ai/dsh-tool-schedule` | `schedule_create`, `schedule_delete`, `schedule_list`, `schedule_update` | `ctx.tools`, `ctx.schedule` | `tool/call`, `Schedule storage domain create, update, or delete`, `tool/result` | - | A preset or Agent scope mounts this package; the preset decides which agents receive the four management tools. Each call acts on the calling Agent's Session. Accepts after_seconds, explicit absolute at, bounded fixed-rate every_seconds, daily and weekly local times in an explicit IANA zone, and cron as a five-field expression. Management uses the Host storage domain; due messages resume the original Session. | +| `@deepseek-ai/dsh-tool-schedule` | `schedule_create`, `schedule_edit`, `schedule_list`, `schedule_view` | `ctx.tools`, `ctx.schedule`, `ctx.systemPrompt` | `tool/call`, `Schedule storage domain create, update, or delete`, `tool/result` | - | A preset or Agent scope mounts this package and decides which agents receive its tools. Management reads and writes Host tasks by id across Sessions. Tasks store an RFC 5545 recurrence and an existing, first-created-and-reused, or per-run-new Session target. Delegated subagents cannot call these tools. | | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`, `ctx.tools`, `ctx.lsp`, `ctx.systemPrompt` | `tool/call`, `tool/result` | - | The lsp tool keeps provider selection and language-server subprocesses behind ctx.lsp, so its model-visible schema stays stable across providers. Requires a registered provider (e.g. `@deepseek-ai/dsh-lsp-stdio`) at runtime; without one, a query returns the structured `LSP_UNAVAILABLE` error rather than changing the schema. | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`, `ctx.workflowEngine`, `ctx.subagents`, `ctx.systemPrompt`, `a calling Agent (exec.agent parents every fresh round)` | `tool/call`, `tool/result`, `workflow and child session events during execution` | - | A fixed foreground workflow starts one fresh structured child per round; the model selects only the immutable objective and an optional round cap. | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`, `ctx.tools`, `ctx.agents`, `ctx.skills` | `tool/call`, `tool/result`, `user/message replacement catalogs via agent.inject()` | - | - | | `@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`, `ctx.agents`, `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. The package is opt-in; compositions that need enforced deadlines or bounded inline output also mount the generic timeout or spill policies. | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | The subagent_oar tool selects among configured aliases for external providers. This catalog shows Codex and Claude Code aliases; each deployment chooses its providers. Native model and permission settings belong to the selected provider configuration. | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`, `subagent` | `ctx.tools`, `ctx.subagents`, `ctx.systemPrompt`, `ctx.sessionProjections`, `ctx.llm for model discovery and selected-route validation` | `tool/call`, `tool/result`, `child session events through the chosen provider` | `subagent`, `subagent_fork` | The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns a child id promptly; local children accept follow-ups, while external backends report their single execution automatically. | -| `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message` | `ctx.tools`, `ctx.subagents`, `ctx.agents` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The globally named discovery, interruption, and local-message tools over managed subagents: provider-bound `tool-subagent` instances register distinct delegation tools, while one instance of this package registers `send_message`, `interrupt_agent`, and `list_agents`. | +| `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`, `list_agents`, `send_message`, `wait_agent` | `ctx.tools`, `ctx.subagents`, `ctx.agents` | `tool/call`, `tool/result`, `child session events through ctx.subagents` | - | The shared control tools discover and contact agents in the subagent tree, interrupt owned descendants, and wait for input in the caller’s inbox. Provider-bound `tool-subagent` instances supply delegation tools. | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`, `job_list`, `job_output` | `ctx.tools`, `ctx.jobs`, `ctx.systemPrompt` | `tool/call`, `tool/result`, `user/message via agent.inject() for background completion notices` | - | The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. | -| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`, `list_agents`, `send_message`, `spawn_teammate`, `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update`, `wait_agent` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `an exact live Team member Agent` | `tool/call`, `team/member`, `team/task`, `agent/inbox/spliced`, `user/message on inbox claim`, `tool/result` | - | All nine tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names. | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. | | `@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. `allowParallelInProgress` is required with no default, so the catalog states its choice: `true`, whose description invites several `in_progress` items. A deployment choosing `false` receives the same tool with a description asking for exactly one active task. | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | Reads or changes the calling Session directory. Existing shells and processes retain their own directories; origin metadata and permission roots stay fixed. | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | Explicit experimental composition only. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout. | @@ -1043,6 +1043,27 @@ Standalone view/create/unique literal replace/line insert tool over the filesyst ## `@deepseek-ai/dsh-tool-fs` +### `apply_patch` + +Create, update, delete, or move UTF-8 text files with one Codex-style patch; prefer it over multiple edit calls when a change spans several files or separated regions. + +```json +{ + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + } + }, + "required": [ + "input" + ] +} +``` + +Source: [`packages/fs/tool-fs/src/index.ts`](../packages/fs/tool-fs/src/index.ts) + ### `edit` Edit an existing UTF-8 text file by replacing literal text. @@ -1154,7 +1175,7 @@ Create or fully replace a UTF-8 text file. Source: [`packages/fs/tool-fs/src/index.ts`](../packages/fs/tool-fs/src/index.ts) -The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); a deployment that loads these tools is expected to also load it. The image tool is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input. +The read-before-write/edit policy is added by `@deepseek-ai/dsh-fs-observation-policy` (an `fs/*` event-gate plugin, no schema change); the shipped compositions leave its row disabled, so mutations are unconditional unless a deployment enables it. The image tool is not registered without `ctx.attachments`; its schema is route-independent, and execution refuses unless the exact routed model declares image input. `apply_patch` registers only with `applyPatch: true`; the catalog sets it so the schema is documented. `dsh-base` and the Web `standard` preset enable it; the Web `ptc` and `cordis` presets and the PTC overlay state `applyPatch: false`. @@ -1481,134 +1502,48 @@ create, edit, pause, and resume require direct-human root authority; complete an ### `schedule_create` -Create a reminder in the current session that delivers prompt when it becomes due. Supply exactly one timing parameter: after_seconds, at, every_seconds, daily, weekly, or cron. Local times that do not exist in the zone are skipped; repeated local times fire once, at the earlier instant. After downtime, a recurring reminder delivers only its latest missed occurrence. Delivery can repeat after a crash. +Create a scheduled task. At each occurrence of rrule, prompt is delivered to the target session as a scheduled message from the user. The result includes the task id and the next occurrence as scheduledAt in UTC and scheduledAtLocal in the zone of rrule. After downtime, only the latest missed occurrence is delivered. Delivery can repeat after a crash. ```json { "type": "object", "properties": { - "prompt": { - "type": "string", - "description": "Reminder content to present when the target becomes due." - }, "title": { "type": "string", - "description": "Concise task name in the user's language, at most 120 characters. Name only the core action and subject; keep essential target identifiers such as PR numbers and branch names. Do not include execution frequency (e.g. daily, hourly), scheduled dates/times, time zones, task status, or configuration and execution details (e.g. read-only mode, profile-tag filters), even when embedded in the requested or existing title. Do not append parenthetical notes. Put scheduling information in the timing parameters and execution instructions in prompt." + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." }, - "after_seconds": { - "type": "number", - "description": "Delay in whole seconds." + "prompt": { + "type": "string", + "description": "Instruction delivered at each occurrence." }, - "every_seconds": { - "type": "number", - "description": "Fixed-rate interval in whole seconds, at least 60, aligned to the creation time; changing it with schedule_update re-aligns it to the save time." + "rrule": { + "type": "string", + "description": "Supported RFC 5545 subset: one DTSTART line, a newline, and one RRULE line. DTSTART ends in Z for UTC or carries TZID with an IANA time zone; a fixed offset such as UTC+5 is Etc/GMT-5, with the sign reversed. DTSTART must name an existing local time. A TZID rule keeps local clock time across daylight-saving changes; generated nonexistent local times are skipped, and repeated ones occur once, at the earlier instant. DTSTART may be in the past; delivery starts with the first occurrence after creation. A one-time delivery is RRULE:FREQ=DAILY;COUNT=1. No SECONDLY; BYSECOND takes one value. COUNT is at most 1000; use UNTIL for longer rules. MINUTELY and HOURLY accept no BY parts, so select clock times with DAILY or WEEKLY plus BYHOUR and BYMINUTE. BYMONTHDAY and ordinal BYDAY require MONTHLY or YEARLY; BYYEARDAY and BYWEEKNO require YEARLY. Ordinal BYDAY cannot combine with BYWEEKNO. Each FREQ period allows at most 10080 candidates before BYSETPOS, which accepts at most 31 values. UNTIL is a UTC instant ending in Z. Example: \"DTSTART;TZID=Asia/Singapore:20260901T080000\\nRRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1\"" }, - "daily": { - "type": "object", - "description": "Every day at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 23:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "time", - "time_zone" + "target": { + "type": "string", + "description": "this_session delivers to this session; new_once delivers to the same new session every time, opened at the first delivery; new opens a different new session for every delivery. New sessions use this session's working directory and preset. With this_session or new_once, a delivery waits until the previous one finishes, and only the latest occurrence that passed meanwhile is delivered. Use this_session for reminders and for follow-ups to this conversation; use new_once or new for independent work, such as a recurring report, and whenever the user asks for a new conversation.", + "enum": [ + "this_session", + "new_once", + "new" ] - }, - "weekly": { - "type": "object", - "description": "On the given weekdays at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 09:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - }, - "weekdays": { - "type": "array", - "description": "ISO weekdays, Monday 1 through Sunday 7, without repetitions.", - "items": { - "type": "integer" - } - } - }, - "required": [ - "time", - "time_zone", - "weekdays" - ] - }, - "cron": { - "type": "object", - "description": "Five-field Vixie cron expression in a time zone.", - "additionalProperties": false, - "properties": { - "expression": { - "type": "string", - "description": "minute hour day-of-month month day-of-week, for example \"*/15 9-17 * * 1-5\". When both day fields are restricted, a date matches if either one matches." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "expression", - "time_zone" - ] - }, - "at": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "date": { - "type": "string" - }, - "time": { - "type": "string" - }, - "time_zone": { - "type": "string" - } - }, - "required": [ - "date", - "time", - "time_zone" - ] - } - ], - "description": "Absolute target: an RFC 3339 date-time with offset, or a local date, time, and IANA time_zone." } }, "required": [ + "title", "prompt", - "title" + "rrule", + "target" ] } ``` Source: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -### `schedule_delete` +### `schedule_edit` -Delete a reminder in the current session, active or inactive. Deletion does not retract a reminder message that is already queued. +Update, pause, resume, or delete one scheduled task by id. Deleting does not retract queued messages. ```json { @@ -1616,11 +1551,49 @@ Delete a reminder in the current session, active or inactive. Deletion does not "properties": { "id": { "type": "string", - "description": "Exact schedule id." + "description": "Task id." + }, + "action": { + "type": "string", + "description": "update applies the provided fields, at least one; delete removes the task.", + "enum": [ + "update", + "delete" + ] + }, + "title": { + "type": "string", + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." + }, + "prompt": { + "type": "string", + "description": "New instruction delivered at each occurrence." + }, + "rrule": { + "type": "string", + "description": "New recurrence in the schedule_create rrule format." + }, + "target": { + "type": "string", + "description": "Omit to retain the destination and its creation settings. Providing target replaces them; new_once reserves a different Session. New targets capture this Session's working directory and preset. Choices are the same as schedule_create.", + "enum": [ + "this_session", + "new_once", + "new" + ] + }, + "active": { + "type": "boolean", + "description": "false pauses the task; true resumes only if its timing has a future occurrence. Otherwise provide a new rrule." + }, + "expectedUpdatedAt": { + "type": "string", + "description": "updatedAt from the latest result that returned this task; if the task changed after that result, the result is schedule_conflict and nothing changes." } }, "required": [ - "id" + "id", + "action" ] } ``` @@ -1629,20 +1602,33 @@ Source: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/to ### `schedule_list` -List the active reminders in the current session. +List scheduled tasks, including tasks created from other sessions. Active tasks come first, ordered by scheduledAt. ```json { "type": "object", - "properties": {} + "properties": { + "active": { + "type": "boolean", + "description": "true for active tasks only; false for paused and ended tasks only; omitted for all tasks." + }, + "limit": { + "type": "integer", + "description": "Page size from 1 to 500; defaults to 100." + }, + "offset": { + "type": "integer", + "description": "Number of tasks to skip; defaults to 0." + } + } } ``` Source: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -### `schedule_update` +### `schedule_view` -Change a reminder in place, keeping its id. Supply a new title, prompt, or at most one timing parameter; omitted fields keep their stored values. To change a relative delay, create a new reminder. +View one scheduled task by id. ```json { @@ -1650,112 +1636,7 @@ Change a reminder in place, keeping its id. Supply a new title, prompt, or at mo "properties": { "id": { "type": "string", - "description": "Schedule id returned by schedule_list." - }, - "title": { - "type": "string", - "description": "New task name; follow the schedule_create title rules." - }, - "prompt": { - "type": "string", - "description": "New reminder content." - }, - "every_seconds": { - "type": "number", - "description": "Fixed-rate interval in whole seconds, at least 60, aligned to the creation time; changing it with schedule_update re-aligns it to the save time." - }, - "daily": { - "type": "object", - "description": "Every day at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 23:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "time", - "time_zone" - ] - }, - "weekly": { - "type": "object", - "description": "On the given weekdays at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 09:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - }, - "weekdays": { - "type": "array", - "description": "ISO weekdays, Monday 1 through Sunday 7, without repetitions.", - "items": { - "type": "integer" - } - } - }, - "required": [ - "time", - "time_zone", - "weekdays" - ] - }, - "cron": { - "type": "object", - "description": "Five-field Vixie cron expression in a time zone.", - "additionalProperties": false, - "properties": { - "expression": { - "type": "string", - "description": "minute hour day-of-month month day-of-week, for example \"*/15 9-17 * * 1-5\". When both day fields are restricted, a date matches if either one matches." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "expression", - "time_zone" - ] - }, - "at": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "date": { - "type": "string" - }, - "time": { - "type": "string" - }, - "time_zone": { - "type": "string" - } - }, - "required": [ - "date", - "time", - "time_zone" - ] - } - ], - "description": "Absolute target: an RFC 3339 date-time with offset, or a local date, time, and IANA time_zone." + "description": "Task id." } }, "required": [ @@ -1766,7 +1647,7 @@ Change a reminder in place, keeping its id. Supply a new title, prompt, or at mo Source: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -A preset or Agent scope mounts this package; the preset decides which agents receive the four management tools. Each call acts on the calling Agent's Session. Accepts after_seconds, explicit absolute at, bounded fixed-rate every_seconds, daily and weekly local times in an explicit IANA zone, and cron as a five-field expression. Management uses the Host storage domain; due messages resume the original Session. +A preset or Agent scope mounts this package and decides which agents receive its tools. Management reads and writes Host tasks by id across Sessions. Tasks store an RFC 5545 recurrence and an existing, first-created-and-reused, or per-run-new Session target. Delegated subagents cannot call these tools. @@ -2180,7 +2061,7 @@ Source: [`packages/subagent/tool-subagent/src/list-models.ts`](../packages/subag ### `subagent` -Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its id. The runtime notifies you when it finishes. The child reports results with `send_message`; use `send_message` to steer it while running or continue its conversation after it finishes. +Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its id. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes. ```json { @@ -2192,7 +2073,7 @@ Delegate a self-contained task to a subagent (a separate agent that works in its }, "description": { "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." }, "prompt": { "type": "string", @@ -2216,7 +2097,7 @@ The load-time `toolName` selects the delegation name (default `subagent`); `mode ### `interrupt_agent` -Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local direct child's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. +Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. ```json { @@ -2237,21 +2118,12 @@ Source: [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/sub ### `list_agents` -List subagents you started, with their ids, labels, and status. running means it is working; inactive means it is not currently working. You will be notified when a subagent finishes; there is no need to keep checking its status. Use send_message to continue the conversation. +List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry ids, descriptions, and status; descendant rows carry parent ids and depth from the root. You can message any other agent in the subagent tree listed as running or inactive. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation. ```json { "type": "object", - "properties": { - "scope": { - "type": "string", - "description": "children (default) lists direct children, which accept send_message in any status. descendants lists the whole tree below you with each entry's parent session id and depth; entries deeper than 1 accept only interrupt_agent.", - "enum": [ - "children", - "descendants" - ] - } - } + "properties": {} } ``` @@ -2259,7 +2131,7 @@ Source: [`packages/subagent/tool-subagent-control/src/list-agents.ts`](../packag ### `send_message` -Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation, not the agent's answer. +Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation. ```json { @@ -2267,7 +2139,7 @@ Send a message to an agent. A working agent receives it at its next step; an idl "properties": { "agent_id": { "type": "string", - "description": "The agent id of your direct continuable child, or your direct parent when you are a resident continuable child." + "description": "The agent id of another member of your subagent tree, as shown by list_agents." }, "message": { "type": "string", @@ -2283,7 +2155,25 @@ Send a message to an agent. A working agent receives it at its next step; an idl Source: [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) -The globally named discovery, interruption, and local-message tools over managed subagents: provider-bound `tool-subagent` instances register distinct delegation tools, while one instance of this package registers `send_message`, `interrupt_agent`, and `list_agents`. +### `wait_agent` + +Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately when that input is already pending. + +```json +{ + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } +} +``` + +Source: [`packages/subagent/tool-subagent-control/src/wait-agent.ts`](../packages/subagent/tool-subagent-control/src/wait-agent.ts) + +The shared control tools discover and contact agents in the subagent tree, interrupt owned descendants, and wait for input in the caller’s inbox. Provider-bound `tool-subagent` instances supply delegation tools. @@ -2358,108 +2248,9 @@ Source: [`packages/jobs/tool-jobs/src/index.ts`](../packages/jobs/tool-jobs/src/ The kind-agnostic background-job controller: background bash commands and PTY sends are read, listed, and killed through the same three tools. Loading the plugin attaches the controller that arms producers' `ctx.jobs.start()`. - + -## `@deepseek-ai/dsh-experimental-tool-agent-team` - -### `interrupt_agent` - -Interrupt one teammate's current turn while preserving its pending inbox. Team Lead only. - -```json -{ - "type": "object", - "properties": { - "target": { - "type": "string", - "description": "Teammate target returned by spawn_teammate or list_agents." - } - }, - "required": [ - "target" - ] -} -``` - -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `list_agents` - -List the Lead and every durable teammate with an addressable target and current availability. inactive means no turn is executing, not a task result. provisioning and failed describe member creation. - -```json -{ - "type": "object", - "properties": {} -} -``` - -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `send_message` - -Send one message to another Team member. A running target receives it at the nearest step boundary; an inactive target starts or resumes a turn. - -```json -{ - "type": "object", - "properties": { - "target": { - "type": "string", - "description": "Member target returned by spawn_teammate or list_agents, including lead." - }, - "message": { - "type": "string", - "description": "Self-contained message for the target." - } - }, - "required": [ - "target", - "message" - ] -} -``` - -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `spawn_teammate` - -Create one named, durable teammate. Only the Team Lead may call this tool. - -```json -{ - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Unique lower-kebab-case teammate name." - }, - "description": { - "type": "string", - "description": "Short description of the delegated responsibility." - }, - "prompt": { - "type": "string", - "description": "Complete initial task for the teammate." - }, - "context": { - "type": "string", - "description": "fresh starts without Lead history; fork inherits completed Lead turns. Defaults to fresh.", - "enum": [ - "fresh", - "fork" - ] - } - }, - "required": [ - "name", - "description", - "prompt" - ] -} -``` - -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +## `@deepseek-ai/dsh-tool-agent-team` ### `team_task_create` @@ -2499,7 +2290,7 @@ Create one unowned pending task on the shared Team task board. } ``` -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_get` @@ -2520,7 +2311,7 @@ Read the complete latest value of one shared task before changing or executing i } ``` -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_list` @@ -2541,7 +2332,7 @@ List shared tasks, including readiness, owner, revision, blockers, and write-sco }, "owner": { "type": "string", - "description": "Optional member target from spawn_teammate or list_agents, matching ownerName; use unowned for tasks without an owner." + "description": "Optional exact ownerId filter; use unowned for tasks without an owner." }, "ready": { "type": "boolean", @@ -2559,7 +2350,7 @@ List shared tasks, including readiness, owner, revision, blockers, and write-sco } ``` -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_update` @@ -2615,7 +2406,7 @@ Compare-and-set a shared task action using the latest revision from team_task_ge }, "owner": { "type": "string", - "description": "Member target from spawn_teammate or list_agents for Lead-only reassign; omit to unassign." + "description": "Agent id of the root or any continuable descendant for root-only reassign; omit to unassign." } }, "required": [ @@ -2626,27 +2417,9 @@ Compare-and-set a shared task action using the latest revision from team_task_ge } ``` -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +Source: [`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) -### `wait_agent` - -Wait for the next teammate status, message, or shared-task change after this call starts. This never wakes inactive members and returns noProgress immediately when no other member is running or provisioning. Re-list after wakeup or timeout instead of polling. - -```json -{ - "type": "object", - "properties": { - "timeout_ms": { - "type": "integer", - "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." - } - } -} -``` - -Source: [`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -All nine tools are scoped to implicit Team Leads and durable teammates. The shipped dsh-base bundle keeps the package disabled; the documented Agent Teams profile patch enables it while disabling the legacy continuable-child control names. +Four task-board tools share the subagent tree’s root Session. Enabling Team mode on the root Session adds task-board guidance alongside standard subagent delegation and control tools. Standard subagent controls provide required identity independently of Team mode. diff --git a/docs/tool-catalog.zh.md b/docs/tool-catalog.zh.md index eeb607a067..b9c2e6d41e 100644 --- a/docs/tool-catalog.zh.md +++ b/docs/tool-catalog.zh.md @@ -34,20 +34,20 @@ | `@deepseek-ai/dsh-tool-bash-persistent` | `bash` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 bash 工具;部署组合提供 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-pwsh-persistent` | `pwsh` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`an owning Agent at execution time` | `tool/call`、`PTY shell state`、`tool/result` | - | 一个按所有者隔离的持久 pwsh 工具,持久 bash 工具的 Windows 对应物;部署组合提供 pwsh 方言的 PTY 后端,并可覆盖面向模型的环境描述。 | | `@deepseek-ai/dsh-tool-str-replace-editor` | `str_replace_editor` | `ctx.tools`、`ctx.fs` | `tool/call`、`fs/observed after view presence/absence, edit absence, or successful mutation`、`tool/result` | - | 基于文件系统 seam 的独立查看/创建/唯一字面量替换/按行插入工具;可与任何 shell 或终端接口组合。 | -| `@deepseek-ai/dsh-tool-fs` | `edit`、`read`、`read_image`、`write` | `ctx.workingDirectory`、`ctx.tools`、`ctx.fs`、`ctx.systemPrompt`、`ctx.attachments (image-tool registration)`、`ctx.llm + an image-capable route (image-tool execution)` | `tool/call`、`fs/write-intent or fs/edit-intent for mutations`、`fs/observed after read presence/absence or successful file operation`、`durable attachment (read_image)`、`tool/result` | - | 先读后写/编辑策略由 `@deepseek-ai/dsh-fs-observation-policy` 添加;它是一个 `fs/*` 事件门禁插件,不会改变 schema。加载这些工具的部署按预期也应加载该插件。没有 `ctx.attachments` 时图片工具不会注册;其 schema 与路由无关,执行时除非确切路由的模型声明图片输入,否则拒绝。 | +| `@deepseek-ai/dsh-tool-fs` | `apply_patch`、`edit`、`read`、`read_image`、`write` | `ctx.workingDirectory`、`ctx.tools`、`ctx.fs`、`ctx.systemPrompt`、`ctx.attachments (image-tool registration)`、`ctx.llm + an image-capable route (image-tool execution)` | `tool/call`、`fs/write-intent, fs/edit-intent, or fs/delete-intent for mutations`、`fs/observed after read presence/absence or successful file operation`、`durable attachment (read_image)`、`tool/result` | - | 先读后写/编辑策略由 `@deepseek-ai/dsh-fs-observation-policy` 添加;它是一个 `fs/*` 事件门禁插件,不会改变 schema。随发行版交付的组合保持该行禁用,因此除非部署启用它,修改都是无条件的。没有 `ctx.attachments` 时图片工具不会注册;其 schema 与路由无关,执行时除非确切路由的模型声明图片输入,否则拒绝。`apply_patch` 仅在 `applyPatch: true` 时注册;目录为了记录其 schema 而开启该开关。`dsh-base` 与 Web 的 `standard` preset 开启它;Web 的 `ptc`、`cordis` preset 以及 PTC overlay 显式写出 `applyPatch: false`。 | | `@deepseek-ai/dsh-tool-fs-search` | `glob`、`grep` | `ctx.workingDirectory`、`ctx.tools`、`ctx.subprocess`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | glob 和 grep 是无条件可用的发现工具,通过 ctx.subprocess spawn 随包提供的 ripgrep 二进制文件(`@vscode/ripgrep`),并作为普通前台调用运行,绝不作为后台任务;无需在宿主机安装 `rg`,也不经过 shell 层。本目录使用 `sampleOverCapGlobResults: true`;部署必须显式选择该行为。结果超过上限时,会通过可选的 ctx.spillStore 后端保存完整的格式化列表;在共置部署中,如果后端公开本地路径,返回的定位信息可供后续读取/搜索。 | | `@deepseek-ai/dsh-tool-terminal` | `terminal_close`、`terminal_list`、`terminal_open`、`terminal_read`、`terminal_send`、`terminal_signal` | `ctx.workingDirectory`、`ctx.tools`、`ctx.terminals`、`ctx.systemPrompt`、`ctx.jobs at call time for run_in_background` | `tool/call`、`tool/result` | - | 这 6 个终端工具需要选择启用,用于补充一次性 bash/文件系统工具。`terminal_send(run_in_background: true)` 会注册到 `ctx.jobs`;schema 不包含 TUI、具名按键序列、BEL、调整尺寸、自动启动和跨 agent 共享。 | | `@deepseek-ai/dsh-tool-goal` | `create_goal`、`get_goal`、`update_goal` | `ctx.tools`、`ctx.agents`、`ctx.goals`、`ctx.systemPrompt`、`a calling Agent in an authorized open turn` | `tool/call`、`goal/change for mutations`、`tool/result` | - | create、edit、pause 和 resume 要求直接来自人类的根权限;complete 和 blocked 也接受确切的当前 Goal Round。blocked 的默认下限是 3 个获准的 Round。 | -| `@deepseek-ai/dsh-tool-schedule` | `schedule_create`、`schedule_delete`、`schedule_list`、`schedule_update` | `ctx.tools`、`ctx.schedule` | `tool/call`、Schedule storage domain 创建、更新或删除、`tool/result` | - | preset 或 Agent scope 挂载本包;由 preset 决定哪些 agent 获得这四个管理工具。每次调用都作用于调用方 Agent 的 Session。接受 after_seconds、显式绝对 at、有界固定速率 every_seconds、带显式 IANA 时区的每日与每周本地时间,以及作为五字段表达式的 cron。管理使用宿主 storage domain;到期消息会恢复原 Session。 | +| `@deepseek-ai/dsh-tool-schedule` | `schedule_create`、`schedule_edit`、`schedule_list`、`schedule_view` | `ctx.tools`、`ctx.schedule`、`ctx.systemPrompt` | `tool/call`、Schedule storage domain 创建、更新或删除、`tool/result` | - | preset 或 Agent scope 挂载本包,并决定哪些 Agent 获得工具。管理工具按 id 跨会话读写 Host 的任务。任务保存 RFC 5545 重复规则,执行位置可选已有会话、首次创建后复用的会话或每次运行新建的会话。委派子 Agent 不能调用这些工具。 | | `@deepseek-ai/dsh-tool-lsp` | `lsp` | `ctx.workingDirectory`、`ctx.tools`、`ctx.lsp`、`ctx.systemPrompt` | `tool/call`、`tool/result` | - | lsp 工具将提供方选择和语言服务器子进程置于 ctx.lsp 之后,因此其模型可见 schema 在更换提供方时保持稳定。运行时要求已注册提供方,例如 `@deepseek-ai/dsh-lsp-stdio`;如果没有提供方,查询会返回结构化 `LSP_UNAVAILABLE` 错误,而不会改变 schema。 | | `@deepseek-ai/dsh-tool-ralph` | `ralph` | `ctx.tools`、`ctx.workflowEngine`、`ctx.subagents`、`ctx.systemPrompt`、`a calling Agent (exec.agent parents every fresh round)` | `tool/call`、`tool/result`、`workflow and child session events during execution` | - | 固定的前台工作流会在每个 Round 启动一个全新的结构化子级;模型只能选择不可变目标和可选的 Round 上限。 | | `@deepseek-ai/dsh-tool-skill` | `skill` | `ctx.workingDirectory`、`ctx.tools`、`ctx.agents`、`ctx.skills` | `tool/call`、`tool/result`、`user/message replacement catalogs via agent.inject()` | - | - | | `@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` | - | 这 5 个只读工具会隐藏提供方游标,并根据不可变的调用 agent 会话为每个结果授权。该包需要选择启用;需要强制截止时间或限制行内输出的组合还会挂载通用超时或 spill 策略。 | | `@deepseek-ai/dsh-experimental-tool-subagent-oar` | `subagent_oar` | `ctx.tools`, `ctx.subagents` | `tool/call`, `tool/result`, `parent subagent catalog and completion notices` | - | subagent_oar 工具在为外部提供方配置的别名之间选择。本目录展示 Codex 和 Claude Code 别名;每个部署自行选择提供方。原生模型和权限设置由所选提供方的配置决定。 | | `@deepseek-ai/dsh-tool-subagent` | `list_subagent_models`、`subagent` | `ctx.tools`、`ctx.subagents`、`ctx.systemPrompt`、`ctx.sessionProjections`、`用于模型发现和所选路由校验的 ctx.llm` | `tool/call`、`tool/result`、`child session events through the chosen provider` | `subagent`、`subagent_fork` | 加载时的 `toolName` 选择委派名称(默认为 `subagent`);`modelSelection` 增加可选路由字段。`modelDiscovery` 默认关闭,每个作用域由一个实例注册共享发现工具。Web 与 Desktop preset 启用 spawn 发现和路由字段,并为 `subagent_fork` 保持路由字段关闭。Host 设置服务为每个新顶层 Session 记录授权;子 Session 继承该授权。没有已记录策略时,发现和显式选择只允许当前父级路由。每次委派都会立即返回子代理 id;本地子代理接受后续消息,外部后端自动汇报单次执行结果。 | -| `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message` | `ctx.tools`、`ctx.subagents`、`ctx.agents` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 这些是用于发现、中断托管 subagent 和向本地子代理发送消息的全局命名工具:绑定提供方的 `tool-subagent` 实例注册不同的委派工具;本包的一个实例注册 `send_message`、`interrupt_agent` 和 `list_agents`。 | +| `@deepseek-ai/dsh-tool-subagent-control` | `interrupt_agent`、`list_agents`、`send_message`、`wait_agent` | `ctx.tools`、`ctx.subagents`、`ctx.agents` | `tool/call`、`tool/result`、`child session events through ctx.subagents` | - | 共享控制工具发现并联系 subagent 树中的 Agent,中断有权控制的后代,并等待调用者收件箱中的输入。绑定提供方的 `tool-subagent` 实例提供委派工具。 | | `@deepseek-ai/dsh-tool-jobs` | `job_kill`、`job_list`、`job_output` | `ctx.tools`、`ctx.jobs`、`ctx.systemPrompt` | `tool/call`、`tool/result`、`user/message via agent.inject() for background completion notices` | - | 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 | -| `@deepseek-ai/dsh-experimental-tool-agent-team` | `interrupt_agent`、`list_agents`、`send_message`、`spawn_teammate`、`team_task_create`、`team_task_get`、`team_task_list`、`team_task_update`、`wait_agent` | `ctx.tools`、`ctx.systemPrompt`、`ctx.agentTeams`、`an exact live Team member Agent` | `tool/call`、`team/member`、`team/task`、`agent/inbox/spliced`、`user/message on inbox claim`、`tool/result` | - | 这 9 个工具限定于隐式 Team Lead 与持久 teammate 作用域。随产品发布的 dsh-base bundle 默认禁用该包;文档中的 Agent Teams profile patch 会启用它,并禁用旧 continuable child 的同名控制工具。 | +| `@deepseek-ai/dsh-tool-agent-team` | `team_task_create`, `team_task_get`, `team_task_list`, `team_task_update` | `ctx.tools`, `ctx.systemPrompt`, `ctx.agentTeams`, `ctx.subagents`, `an exact live Team member Agent` | `tool/call`, `team/task`, `tool/result` | - | 四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准 subagent 委派和控制工具之外增加任务板指导。标准 subagent 控制工具提供必需身份,不受 Team 模式影响。 | | `@deepseek-ai/dsh-tool-todo` | `todo_write` | `ctx.tools`、`owning Agent session` | `tool/call`、`todo/write`、`tool/result` | - | todo_write 是会话所有的状态;UI 将最新的 todo/write 事件渲染为检查清单。`allowParallelInProgress` 是没有默认值的必填项,因此本目录明确选择 `true`,对应描述允许同时存在多个 `in_progress` 项。选择 `false` 的部署会获得同一工具,但描述会要求只能有 1 个活动任务。 | | `@deepseek-ai/dsh-tool-working-directory` | `working_directory` | `ctx.tools`, `ctx.workingDirectory` | `tool/call`, `working-directory/change`, `user context for directory changes`, `tool/result` | - | 读取或改变调用方 Session 的目录。已有 shell 和进程保留自己的目录;原始元数据和权限根目录保持不变。 | | `@deepseek-ai/dsh-experimental-tool-worktree` | `create_worktree` | `ctx.tools`, `ctx.worktrees`, `a calling Agent` | `tool/call`, `Git branch and checkout`, `working-directory/change`, `tool/result` | - | 仅通过显式实验组合加载。在现有写权限下从固定的本地提交创建新分支与检出目录,再改变 Session 工作目录。离开时保留分支与检出目录。 | @@ -1049,6 +1049,27 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费 ## `@deepseek-ai/dsh-tool-fs` +### `apply_patch` + +用一个 Codex 风格补丁新增、更新、删除或移动 UTF-8 文本文件;变更跨越多个文件或分离区域时,优先于多次 edit 调用。 + +```json +{ + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Codex patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + } + }, + "required": [ + "input" + ] +} +``` + +来源: [`packages/fs/tool-fs/src/index.ts`](../packages/fs/tool-fs/src/index.ts) + ### `edit` 通过替换字面量文本来编辑现有 UTF-8 文本文件。 @@ -1160,7 +1181,7 @@ pwsh 工具是 Windows 组合中 bash 执行器 seam 的 PowerShell 方言消费 来源:[`packages/fs/tool-fs/src/index.ts`](../packages/fs/tool-fs/src/index.ts) -先读后写/编辑策略由 `@deepseek-ai/dsh-fs-observation-policy` 添加;它是一个 `fs/*` 事件门禁插件,不会改变 schema。加载这些工具的部署按预期也应加载该插件。没有 `ctx.attachments` 时图片工具不会注册;其 schema 与路由无关,执行时除非确切路由的模型声明图片输入,否则拒绝。 +先读后写/编辑策略由 `@deepseek-ai/dsh-fs-observation-policy` 添加;它是一个 `fs/*` 事件门禁插件,不会改变 schema。随发行版交付的组合保持该行禁用,因此除非部署启用它,修改都是无条件的。没有 `ctx.attachments` 时图片工具不会注册;其 schema 与路由无关,执行时除非确切路由的模型声明图片输入,否则拒绝。`apply_patch` 仅在 `applyPatch: true` 时注册;目录为了记录其 schema 而开启该开关。`dsh-base` 与 Web 的 `standard` preset 开启它;Web 的 `ptc`、`cordis` preset 以及 PTC overlay 显式写出 `applyPatch: false`。 @@ -1487,134 +1508,48 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete ### `schedule_create` -在当前会话中创建一条提醒,到期时投递 prompt。请恰好提供一个时间参数:after_seconds、at、every_seconds、daily、weekly 或 cron。时区中不存在的本地时间会被跳过;重复出现的本地时间只在较早的时刻触发一次。停机后,重复提醒只投递最近错过的一次。崩溃后可能重复投递。 +创建定时任务。rrule 的每次触发都会将 prompt 作为用户的定时消息投递到目标会话。结果包含任务 id 和下一次触发时间:scheduledAt 为 UTC 时间,scheduledAtLocal 为 rrule 所在时区的时间。停机后只补发最近一次错过的触发。崩溃后可能重复投递。 ```json { "type": "object", "properties": { - "prompt": { - "type": "string", - "description": "Reminder content to present when the target becomes due." - }, "title": { "type": "string", - "description": "Concise task name in the user's language, at most 120 characters. Name only the core action and subject; keep essential target identifiers such as PR numbers and branch names. Do not include execution frequency (e.g. daily, hourly), scheduled dates/times, time zones, task status, or configuration and execution details (e.g. read-only mode, profile-tag filters), even when embedded in the requested or existing title. Do not append parenthetical notes. Put scheduling information in the timing parameters and execution instructions in prompt." + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." }, - "after_seconds": { - "type": "number", - "description": "Delay in whole seconds." + "prompt": { + "type": "string", + "description": "Instruction delivered at each occurrence." }, - "every_seconds": { - "type": "number", - "description": "Fixed-rate interval in whole seconds, at least 60, aligned to the creation time; changing it with schedule_update re-aligns it to the save time." + "rrule": { + "type": "string", + "description": "Supported RFC 5545 subset: one DTSTART line, a newline, and one RRULE line. DTSTART ends in Z for UTC or carries TZID with an IANA time zone; a fixed offset such as UTC+5 is Etc/GMT-5, with the sign reversed. DTSTART must name an existing local time. A TZID rule keeps local clock time across daylight-saving changes; generated nonexistent local times are skipped, and repeated ones occur once, at the earlier instant. DTSTART may be in the past; delivery starts with the first occurrence after creation. A one-time delivery is RRULE:FREQ=DAILY;COUNT=1. No SECONDLY; BYSECOND takes one value. COUNT is at most 1000; use UNTIL for longer rules. MINUTELY and HOURLY accept no BY parts, so select clock times with DAILY or WEEKLY plus BYHOUR and BYMINUTE. BYMONTHDAY and ordinal BYDAY require MONTHLY or YEARLY; BYYEARDAY and BYWEEKNO require YEARLY. Ordinal BYDAY cannot combine with BYWEEKNO. Each FREQ period allows at most 10080 candidates before BYSETPOS, which accepts at most 31 values. UNTIL is a UTC instant ending in Z. Example: \"DTSTART;TZID=Asia/Singapore:20260901T080000\\nRRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1\"" }, - "daily": { - "type": "object", - "description": "Every day at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 23:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "time", - "time_zone" + "target": { + "type": "string", + "description": "this_session delivers to this session; new_once delivers to the same new session every time, opened at the first delivery; new opens a different new session for every delivery. New sessions use this session's working directory and preset. With this_session or new_once, a delivery waits until the previous one finishes, and only the latest occurrence that passed meanwhile is delivered. Use this_session for reminders and for follow-ups to this conversation; use new_once or new for independent work, such as a recurring report, and whenever the user asks for a new conversation.", + "enum": [ + "this_session", + "new_once", + "new" ] - }, - "weekly": { - "type": "object", - "description": "On the given weekdays at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 09:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - }, - "weekdays": { - "type": "array", - "description": "ISO weekdays, Monday 1 through Sunday 7, without repetitions.", - "items": { - "type": "integer" - } - } - }, - "required": [ - "time", - "time_zone", - "weekdays" - ] - }, - "cron": { - "type": "object", - "description": "Five-field Vixie cron expression in a time zone.", - "additionalProperties": false, - "properties": { - "expression": { - "type": "string", - "description": "minute hour day-of-month month day-of-week, for example \"*/15 9-17 * * 1-5\". When both day fields are restricted, a date matches if either one matches." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "expression", - "time_zone" - ] - }, - "at": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "date": { - "type": "string" - }, - "time": { - "type": "string" - }, - "time_zone": { - "type": "string" - } - }, - "required": [ - "date", - "time", - "time_zone" - ] - } - ], - "description": "Absolute target: an RFC 3339 date-time with offset, or a local date, time, and IANA time_zone." } }, "required": [ + "title", "prompt", - "title" + "rrule", + "target" ] } ``` -来源:[`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) +源码: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -### `schedule_delete` +### `schedule_edit` -删除当前会话中的一条提醒,活动或已结束的均可。删除不会撤回已经入队的提醒消息。 +按 id 更新、暂停、恢复或删除一个定时任务。删除不会撤回已排队的消息。 ```json { @@ -1622,33 +1557,84 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete "properties": { "id": { "type": "string", - "description": "Exact schedule id." + "description": "Task id." + }, + "action": { + "type": "string", + "description": "update applies the provided fields, at least one; delete removes the task.", + "enum": [ + "update", + "delete" + ] + }, + "title": { + "type": "string", + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." + }, + "prompt": { + "type": "string", + "description": "New instruction delivered at each occurrence." + }, + "rrule": { + "type": "string", + "description": "New recurrence in the schedule_create rrule format." + }, + "target": { + "type": "string", + "description": "Omit to retain the destination and its creation settings. Providing target replaces them; new_once reserves a different Session. New targets capture this Session's working directory and preset. Choices are the same as schedule_create.", + "enum": [ + "this_session", + "new_once", + "new" + ] + }, + "active": { + "type": "boolean", + "description": "false pauses the task; true resumes only if its timing has a future occurrence. Otherwise provide a new rrule." + }, + "expectedUpdatedAt": { + "type": "string", + "description": "updatedAt from the latest result that returned this task; if the task changed after that result, the result is schedule_conflict and nothing changes." } }, "required": [ - "id" + "id", + "action" ] } ``` -来源:[`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) +源码: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) ### `schedule_list` -列出当前会话中的活动提醒。 +列出定时任务,包括从其他会话创建的任务。活动任务排在前面,按 scheduledAt 排序。 ```json { "type": "object", - "properties": {} + "properties": { + "active": { + "type": "boolean", + "description": "true for active tasks only; false for paused and ended tasks only; omitted for all tasks." + }, + "limit": { + "type": "integer", + "description": "Page size from 1 to 500; defaults to 100." + }, + "offset": { + "type": "integer", + "description": "Number of tasks to skip; defaults to 0." + } + } } ``` -来源:[`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) +源码: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -### `schedule_update` +### `schedule_view` -原地修改一条提醒并保留其 id。提供新的 title、prompt,或至多一个时间参数;未提供的字段保持原值。需要相对延迟时请新建一条提醒。 +按 id 查看一个定时任务。 ```json { @@ -1656,112 +1642,7 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete "properties": { "id": { "type": "string", - "description": "Schedule id returned by schedule_list." - }, - "title": { - "type": "string", - "description": "New task name; follow the schedule_create title rules." - }, - "prompt": { - "type": "string", - "description": "New reminder content." - }, - "every_seconds": { - "type": "number", - "description": "Fixed-rate interval in whole seconds, at least 60, aligned to the creation time; changing it with schedule_update re-aligns it to the save time." - }, - "daily": { - "type": "object", - "description": "Every day at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 23:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "time", - "time_zone" - ] - }, - "weekly": { - "type": "object", - "description": "On the given weekdays at a local time.", - "additionalProperties": false, - "properties": { - "time": { - "type": "string", - "description": "HH:mm:ss with optional 1-3 fractional digits, for example 09:00:00." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - }, - "weekdays": { - "type": "array", - "description": "ISO weekdays, Monday 1 through Sunday 7, without repetitions.", - "items": { - "type": "integer" - } - } - }, - "required": [ - "time", - "time_zone", - "weekdays" - ] - }, - "cron": { - "type": "object", - "description": "Five-field Vixie cron expression in a time zone.", - "additionalProperties": false, - "properties": { - "expression": { - "type": "string", - "description": "minute hour day-of-month month day-of-week, for example \"*/15 9-17 * * 1-5\". When both day fields are restricted, a date matches if either one matches." - }, - "time_zone": { - "type": "string", - "description": "UTC or IANA Area/Location, for example Asia/Shanghai." - } - }, - "required": [ - "expression", - "time_zone" - ] - }, - "at": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "object", - "additionalProperties": false, - "properties": { - "date": { - "type": "string" - }, - "time": { - "type": "string" - }, - "time_zone": { - "type": "string" - } - }, - "required": [ - "date", - "time", - "time_zone" - ] - } - ], - "description": "Absolute target: an RFC 3339 date-time with offset, or a local date, time, and IANA time_zone." + "description": "Task id." } }, "required": [ @@ -1770,9 +1651,9 @@ create、edit、pause 和 resume 要求直接来自人类的根权限;complete } ``` -Source: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) +源码: [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) -preset 或 Agent scope 挂载本包;由 preset 决定哪些 agent 获得这四个管理工具。每次调用都作用于调用方 Agent 的 Session。接受 after_seconds、显式绝对 at、有界固定速率 every_seconds、带显式 IANA 时区的每日与每周本地时间,以及作为五字段表达式的 cron。管理使用宿主 storage domain;到期消息会恢复原 Session。 +preset 或 Agent scope 挂载本包,并决定哪些 Agent 获得工具。管理工具按 id 跨会话读写 Host 的任务。任务保存 RFC 5545 重复规则,执行位置可选已有会话、首次创建后复用的会话或每次运行新建的会话。委派子 Agent 不能调用这些工具。 @@ -2186,7 +2067,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 ### `subagent` -将一项自包含任务委派给 subagent(在自身上下文中工作的独立 agent),用它卸载聚焦且独立的工作,例如研究、限定范围的实现或分析,以免消耗当前对话的上下文。subagent 会返回结果,但不会返回中间步骤。此工具启动独立管理的 subagent 并立即返回其 id。运行时会在任务结束时通知你。子代理通过 `send_message` 汇报结果;你可以使用 `send_message` 在运行时引导它,或在结束后继续对话。 +将一项自包含任务委派给 subagent(在自身上下文中工作的独立 agent),用它卸载聚焦且独立的工作,例如研究、限定范围的实现或分析,以免消耗当前对话的上下文。subagent 会返回结果,但不会返回中间步骤。此工具启动独立管理的 subagent 并立即返回其 id。如果它结束时你仍在线,运行时会自动递送其完成通知。通知包含最终回答,除非子任务在结束前刚给你发过消息。你可以使用 `send_message` 在运行时引导它,或在结束后继续对话。 ```json { @@ -2198,7 +2079,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 }, "description": { "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display." + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." }, "prompt": { "type": "string", @@ -2243,21 +2124,12 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 ### `list_agents` -按持久 ID 和标签列出调用方目录中可继续的直接子代理。使用此工具回忆已启动的子代理,不要轮询完成状态;完成时会收到通知。状态来自在线注册表:running 表示当前正在工作;inactive 表示当前没有执行轮次,无论子代理已加载还是需要恢复,并不表示任务完成、成功、失败或正在等待其他代理。`send_message` 可在最近的步骤边界引导正在运行的子代理,或启动、恢复非活跃子代理的轮次;任何状态下的直接子级都可作为 `send_message` 的候选目标。列表快照不保证投递成功,`send_message` 仍进行权威检查,且可能失败。 +列出整棵 subagent 树:根代理和所有可达的可继续后代,包括调用方自身。行包含 id、描述和状态;后代行包含父级 id 和相对根的深度。可以向树中列为 running 或 inactive 的任意其他代理发送消息。running 表示正在工作;inactive 表示当前没有轮次在执行,不表示任务完成、成功或失败。自身仍在线时,直属子代理结束会收到通知,无需反复查询其状态。使用 send_message 继续对话。 ```json { "type": "object", - "properties": { - "scope": { - "type": "string", - "description": "children (default) lists direct children, which accept send_message in any status. descendants lists the whole tree below you with each entry's parent session id and depth; entries deeper than 1 accept only interrupt_agent.", - "enum": [ - "children", - "descendants" - ] - } - } + "properties": {} } ``` @@ -2265,7 +2137,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 ### `send_message` -根据 agent id 向直接可继续 child 发送消息。如果你是驻留的可继续 child,也可以把自己的直接 parent 作为目标。如果目标仍在工作,消息会 steer 其最近的 step;如果目标处于 idle,消息会启动一个轮次。此调用不会返回该 agent 的答案,只会确认消息已投递。调用失败表示消息**未**投递。 +向代理发消息。工作中的代理在下一步骤接收消息,空闲代理用消息启动新轮次。返回投递确认。 ```json { @@ -2273,7 +2145,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 "properties": { "agent_id": { "type": "string", - "description": "The agent id of your direct continuable child, or your direct parent when you are a resident continuable child." + "description": "The agent id of another member of your subagent tree, as shown by list_agents." }, "message": { "type": "string", @@ -2289,7 +2161,25 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 来源:[`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) -这些是用于发现、中断托管 subagent 和向本地子代理发送消息的全局命名工具:绑定提供方的 `tool-subagent` 实例注册不同的委派工具;本包的一个实例注册 `send_message`、`interrupt_agent` 和 `list_agents`。 +### `wait_agent` + +等待下一步可处理的输入,包括 Agent 消息、完成通知和用户引导。已有此类待处理输入时立即返回。 + +```json +{ + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } +} +``` + +来源:[`packages/subagent/tool-subagent-control/src/wait-agent.ts`](../packages/subagent/tool-subagent-control/src/wait-agent.ts) + +共享控制工具发现并联系 subagent 树中的 Agent,中断有权控制的后代,并等待调用者收件箱中的输入。绑定提供方的 `tool-subagent` 实例提供委派工具。 @@ -2364,108 +2254,9 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 与任务种类无关的后台任务控制器:后台 bash 命令与 PTY 发送 都通过相同的 3 个工具读取、列出和终止。加载该插件会挂接控制器,从而启用生产方的 `ctx.jobs.start()`。 - + -## `@deepseek-ai/dsh-experimental-tool-agent-team` - -### `interrupt_agent` - -中断一名 teammate 的当前 turn,同时保留其待处理 inbox。仅 Team Lead 可用。 - -```json -{ - "type": "object", - "properties": { - "target": { - "type": "string", - "description": "Teammate target returned by spawn_teammate or list_agents." - } - }, - "required": [ - "target" - ] -} -``` - -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `list_agents` - -列出 Lead 与所有持久 teammate,以及可用于寻址的 target 和当前可用状态。inactive 表示没有轮次在执行,不表示任务结果。provisioning 与 failed 描述成员创建状态。 - -```json -{ - "type": "object", - "properties": {} -} -``` - -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `send_message` - -向另一名 Team member 发送一条消息。running target 会在最近的步骤边界收到消息;inactive target 会启动或恢复一个 turn。 - -```json -{ - "type": "object", - "properties": { - "target": { - "type": "string", - "description": "Member target returned by spawn_teammate or list_agents, including lead." - }, - "message": { - "type": "string", - "description": "Self-contained message for the target." - } - }, - "required": [ - "target", - "message" - ] -} -``` - -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `spawn_teammate` - -创建一名具名、持久的 teammate。只有 Team Lead 可以调用此工具。 - -```json -{ - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "Unique lower-kebab-case teammate name." - }, - "description": { - "type": "string", - "description": "Short description of the delegated responsibility." - }, - "prompt": { - "type": "string", - "description": "Complete initial task for the teammate." - }, - "context": { - "type": "string", - "description": "fresh starts without Lead history; fork inherits completed Lead turns. Defaults to fresh.", - "enum": [ - "fresh", - "fork" - ] - } - }, - "required": [ - "name", - "description", - "prompt" - ] -} -``` - -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +## `@deepseek-ai/dsh-tool-agent-team` ### `team_task_create` @@ -2505,7 +2296,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 } ``` -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_get` @@ -2526,7 +2317,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 } ``` -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_list` @@ -2547,7 +2338,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 }, "owner": { "type": "string", - "description": "Optional member target from spawn_teammate or list_agents, matching ownerName; use unowned for tasks without an owner." + "description": "Optional exact ownerId filter; use unowned for tasks without an owner." }, "ready": { "type": "boolean", @@ -2565,7 +2356,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 } ``` -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) +来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) ### `team_task_update` @@ -2621,7 +2412,7 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 }, "owner": { "type": "string", - "description": "Member target from spawn_teammate or list_agents for Lead-only reassign; omit to unassign." + "description": "Agent id of the root or any continuable descendant for root-only reassign; omit to unassign." } }, "required": [ @@ -2632,28 +2423,9 @@ subagent_oar 工具在为外部提供方配置的别名之间选择。本目录 } ``` -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -### `wait_agent` - -等待本次调用开始后下一次 teammate 状态、消息或共享任务变更。它绝不会唤醒 inactive member;若没有其他 member 正在 running 或 provisioning,则立即返回 noProgress。唤醒或超时后应重新列出状态,而不是轮询。 - -```json -{ - "type": "object", - "properties": { - "timeout_ms": { - "type": "integer", - "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." - } - } -} -``` - -来源:[`packages/experimental/tool-agent-team/src/index.ts`](../packages/experimental/tool-agent-team/src/index.ts) - -这 10 个工具限定于隐式 Team Lead 与持久 teammate 作用域。随产品发布的 dsh-base bundle 默认禁用该包;文档中的 Agent Teams profile patch 会启用它,并禁用旧 continuable child 的同名控制工具。 +来源:[`packages/team/tool-agent-team/src/index.ts`](../packages/team/tool-agent-team/src/index.ts) +四个任务板工具共享 subagent 树的根 Session。在根 Session 开启 Team 模式,会在标准子代理委派和控制工具之外增加任务板指导。标准子代理控制工具提供必需身份,不受 Team 模式影响。 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml index 0f10d46677..fee15bfbc4 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 9968decf3dd340af zh: 736a32caac4b5103 /agent-teams-messages-use-target-inboxes/migration: - en: 7ffd442bfd55769e - zh: ffb11a143f11ce7f + en: a4b8999943c76cc4 + zh: 042927b5c857c8d5 diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md index 974c1aa13c..d2e03eacd5 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.md @@ -18,4 +18,4 @@ The `maxPendingMessagesPerMember` configuration key is removed. Historical `team 1. Before upgrading, let pending Team messages finish and confirm that their targets received them. After upgrading, explicitly resend any required undelivered message; check the target's history first to avoid duplicates. Do not edit historical Session records. 2. Remove `maxPendingMessagesPerMember` from the `@deepseek-ai/dsh-experimental-agent-team` plugin configuration in your `cordis.yml` or overlays. There is no replacement Team queue limit; `maxMessageBytes` still bounds each complete sender-framed message. 3. Update any consumer of `send_message` results to read `sent` instead of message IDs or delivery statuses, and handle send errors explicitly. Do not treat success as completed target work. The `ctx.agentTeams.sendMessage()` service still returns `messageId`. -4. Start your Team-enabled profile, send a message to another member, and confirm that the tool returns `{ "sent": true }` and that the target receives it. Consult the [package reference](../../../../packages/experimental/agent-team/README.md#use-this-package) for delivery semantics. +4. Start your Team-enabled profile, send a message to another member, and confirm that the tool returns `{ "sent": true }` and that the target receives it. Consult the [package reference](../../../../packages/team/agent-team/README.md#use-this-package) for delivery semantics. diff --git a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md index c10791fbf7..1f5014e0c7 100644 --- a/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md +++ b/docs/upgrade-guide/v0.2.1-alpha.1/team-direct-inbox/guide.zh.md @@ -18,4 +18,4 @@ description: "Agent Teams 移除待投递消息数量限制,并停止投递历 1. 升级前,让待投递的 Team 消息完成投递,并确认目标已收到。升级后,显式重发仍需处理的未投递消息;先检查目标历史,避免重复。不要编辑历史 Session 记录。 2. 从 `cordis.yml` 或覆盖配置中 `@deepseek-ai/dsh-experimental-agent-team` 插件的配置移除 `maxPendingMessagesPerMember`。没有替代的 Team 队列限制;`maxMessageBytes` 仍限制包含发送者标识的完整消息大小。 3. 更新所有读取 `send_message` 结果的调用方,改为读取 `sent` 而非消息 ID 或投递状态,并显式处理发送错误。不要把发送成功视为目标工作已完成。`ctx.agentTeams.sendMessage()` 服务仍返回 `messageId`。 -4. 启动启用 Team 的 profile,向其他成员发送消息,确认工具返回 `{ "sent": true }` 且目标收到消息。投递语义参见[包参考](../../../../packages/experimental/agent-team/README.zh.md#use-this-package)。 +4. 启动启用 Team 的 profile,向其他成员发送消息,确认工具返回 `{ "sent": true }` 且目标收到消息。投递语义参见[包参考](../../../../packages/team/agent-team/README.zh.md#use-this-package)。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.i18n.yaml new file mode 100644 index 0000000000..2374c0b447 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.md +/: + en: ced4d23952f772d5 + zh: f8e7e8c069266fa1 +/agent-runtime-ownership-uses-owneragent: + en: 8a1164f53b3627da + zh: 19fae50e43c4dca4 +/agent-runtime-ownership-uses-owneragent/change: + en: 88457ac32ffc2c7d + zh: 05ea7db957db119b +/agent-runtime-ownership-uses-owneragent/migration: + en: d25ad901f4601369 + zh: 96b556991249635b diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.md new file mode 100644 index 0000000000..4648667d9e --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Agent creation and resume options rename parentAgent to ownerAgent for runtime ownership." +--- + +# Agent runtime ownership uses `ownerAgent` + +English | [中文](guide.zh.md) + +## Change + +`CreateAgentOptions` and `ResumeAgentOptions` in `@deepseek-ai/dsh-agent` replace `parentAgent` with `ownerAgent`. This affects plugins and custom factories calling `ctx.agents.create()` or `ctx.agents.resume()`. The field selects the live Agent that owns the runtime instance; omitting it creates a runtime root. + +Session creation lineage remains in `meta.parentSession`. For a nested subagent, the runtime owner can be the tree root while the direct creator is another descendant. Persisted Session fields and formats are unchanged. + +## Migration + +1. Rename the `parentAgent` option to `ownerAgent` in creation and resume calls, and update custom `AgentFactory` implementations that read or forward it. Pass the same Agent as before. +2. Keep `meta.parentSession` and stored `parentSession` values unchanged. Do not substitute the runtime owner for the direct creator. +3. Typecheck consumers against the updated package, then verify that `ctx.agents.isOwnedBy(id, owner)` and `ctx.agents.roots()` report the same runtime relationships after creation and resume. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.zh.md new file mode 100644 index 0000000000..b1e36efd9f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-runtime-owner/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Agent 创建和恢复选项将表示运行归属的 parentAgent 改名为 ownerAgent。" +--- + +# Agent 运行归属使用 `ownerAgent` + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-agent` 中的 `CreateAgentOptions` 和 `ResumeAgentOptions` 将 `parentAgent` 替换为 `ownerAgent`。这影响调用 `ctx.agents.create()` 或 `ctx.agents.resume()` 的插件与自定义工厂。该字段指定拥有运行实例的在线 Agent;省略时创建运行时根。 + +Session 创建来源仍由 `meta.parentSession` 记录。嵌套子代理的运行归属者可以是树根,而直接创建者是另一个后代。持久化 Session 字段和格式保持不变。 + +## 迁移 + +1. 将创建和恢复调用中的 `parentAgent` 选项改名为 `ownerAgent`,并更新读取或透传该字段的自定义 `AgentFactory` 实现。继续传入原来的 Agent。 +2. 保持 `meta.parentSession` 和存储的 `parentSession` 值不变。不要用运行归属者替换直接创建者。 +3. 针对更新后的包对消费者运行类型检查,再验证创建和恢复后的 `ctx.agents.isOwnedBy(id, owner)` 与 `ctx.agents.roots()` 仍报告相同的运行归属关系。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.i18n.yaml new file mode 100644 index 0000000000..1b127d0026 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.md +/: + en: 1f073189776760d8 + zh: cfbb0403aea96f84 +/agent-teams-uses-subagents-and-session-ids: + en: 703c7766dd80e1d1 + zh: 157c67164c1cbc7d +/agent-teams-uses-subagents-and-session-ids/change: + en: d387c95a87d1bd6a + zh: 69dd000fbff0b6fa +/agent-teams-uses-subagents-and-session-ids/migration: + en: dcc698d29a4677f0 + zh: 2af5cea905ad4371 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.md new file mode 100644 index 0000000000..dedc7025fb --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.md @@ -0,0 +1,31 @@ +--- +kind: upgrade-guide +description: "Agent Teams uses the standard subagent tools and Session ids; Team-specific creation, messaging, listing, interruption, and their configuration keys are removed." +--- + +# Agent Teams uses subagents and Session ids + +English | [中文](guide.zh.md) + +## Change + +Descriptions label responsibilities; only Session ids identify recipients. + +- `spawn_teammate` and the Team-scoped `send_message`, `list_agents`, and `interrupt_agent` are removed. The standard control tools use `agent_id`, not `target`. Members of one root tree can message each other across branches by id; interruption remains ancestor-only. +- `list_agents` takes no arguments and lists the entire tree. Remove scripted `scope` arguments. Rows use `kind: root`, `kind: child`, or `kind: diagnostic`; descendants include parent ids and root-relative depth. +- Team supplies four task tools and policy; controls supply required identity. `wait_agent` moves to ordinary subagent controls and waits for the caller’s next-step inbox, including pending input. Status changes and unrelated inboxes do not wake it; `noProgress` is removed. Timeout bounds/default remain unchanged. +- `agent-team` rejects `maxMembers`, `maxMessageBytes`, and `disposalTimeoutMs`; `tool-agent-team` rejects `interrupt`, `freshProvider`, and `forkProvider`. +- `ctx.agentTeams` removes creation, messaging, interruption, roster, membership, and wait APIs. `TeamMembership`, `TeamMemberView`, spawn/send request/result types, and `TeamWaitResult` are removed. Task ownership uses `ownerId`, including the root’s Session id. +- Runtime instances share root ownership without changing creation ancestry. Member settlement does not dispose descendants. Messages restore only their target. Hosts close the tree when its root closes; members obtain required results explicitly. +- Cold resume uses saved presets and permissions, not the creator’s current generation. Missing presets fail restoration; historical targets without one use host composition plus descriptor overrides. Lifecycle dispatch uses the root scope while retaining the direct creator in `parentSessionId`. Browser continuation requires the root online; failure uses `subagent/delivery-unavailable`. +- Historical Team roster and mailbox records remain readable. Historical names do not resolve message recipients or task owners. Subagent catalog payloads are unchanged. +- The Web Team panel shows tasks only; subagent navigation owns member browsing. The wire `agentTeam.members` field and `TeamMemberProjection` are removed; persisted roster state still decodes. Task commits do not end waits, deliver messages, or start idle Agents. Message another Agent when it needs to act on task changes. + +## Migration + +1. Move `interrupt: false` from `tool-agent-team` to `tool-subagent-control`. Remove other obsolete keys and any patch rows that disable subagent tools solely for Team support. +2. Replace `spawn_teammate({ name, description, prompt, context })` with `subagent({ description, prompt })`, or `subagent_fork` for inherited conversation history. Save the returned agent id. +3. Use `send_message({ agent_id, message })` and `interrupt_agent({ agent_id })`. Discover all Team member ids with `list_agents`. +4. Pass member Session ids to task `owner` fields and read `ownerId` in results. Use the Lead's Session id instead of the alias `lead`. +5. Replace `spawnTeammate`, `sendMessage`, and `interrupt` with `ctx.subagents.startActivation`, `sendMessage`, and `interrupt`. Replace `membership`/`tryMembership` with `rootOf`, and `listMembers` with `listDescendants`. Replace `waitForChange` with `wait_agent`, then re-read tasks. +6. SDK `session/resume` rejects subagent sessions. Resume the root Session instead. Verify navigation, nested task assignment, and that messages end inbox waits while task commits do not. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.zh.md new file mode 100644 index 0000000000..177831b543 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/agent-team-subagents/guide.zh.md @@ -0,0 +1,31 @@ +--- +kind: upgrade-guide +description: "Agent Teams 使用标准 subagent 工具和 Session id;移除 Team 专属创建、消息、列举、中断操作及其配置键。" +--- + +# Agent Teams 使用子代理和 Session id + +[English](guide.md) | 中文 + +## 变更 + +描述标注职责;仅 Session id 标识接收者。 + +- 移除 `spawn_teammate` 以及 Team 作用域的 `send_message`、`list_agents` 和 `interrupt_agent`。标准控制工具使用 `agent_id` 而非 `target`。同一根下的成员可以通过 id 跨分支互发消息;中断仍只允许祖先执行。 +- `list_agents` 不接受参数,列出整棵树。移除脚本中的 `scope` 参数。行使用 `kind: root`、`kind: child` 或 `kind: diagnostic`;后代包含父 id 和相对根的深度。 +- Team 提供四个任务工具和策略;控制工具提供必需身份。`wait_agent` 移至普通 subagent 控制工具,等待调用者的下一步收件箱,包括待处理输入。状态变化和其他收件箱不会唤醒它;移除 `noProgress`。超时范围和默认值不变。 +- `agent-team` 拒绝 `maxMembers`、`maxMessageBytes` 和 `disposalTimeoutMs`;`tool-agent-team` 拒绝 `interrupt`、`freshProvider` 和 `forkProvider`。 +- `ctx.agentTeams` 移除创建、通信、中断、名册、成员关系和等待 API。`TeamMembership`、`TeamMemberView`、spawn/send 请求和结果类型以及 `TeamWaitResult` 被移除。任务归属使用 `ownerId`,包括根的 Session id。 +- 运行时实例共享根所有权,不改变创建祖先关系。成员收尾不释放后代。消息仅恢复目标。根关闭时 host 关闭整棵树;成员显式获取所需结果。 +- 冷恢复使用已保存的 preset 和权限,而非创建者当前代次。缺失 preset 会导致恢复失败;历史目标没有保存 preset 时,使用 host 组合及描述符覆盖。生命周期分派使用根作用域,同时在 `parentSessionId` 中保留直接创建者。浏览器继续执行需要根在线;失败使用 `subagent/delivery-unavailable`。 +- 历史 Team 名册和邮箱记录仍可读取。其中的名字仅作为历史数据,不用于解析消息收件人或任务所有者。Subagent catalog 载荷不变。 +- Web Team 面板仅显示任务;subagent 导航负责浏览成员。线上 `agentTeam.members` 字段与 `TeamMemberProjection` 被移除;持久化成员状态仍可解码。任务提交不结束等待、不投递消息,也不启动空闲 Agent。需要另一个 Agent 处理任务变更时,应发送消息。 + +## 迁移 + +1. 将 `interrupt: false` 从 `tool-agent-team` 移到 `tool-subagent-control`。删除其余废弃键,以及仅为支持 Team 而禁用 subagent 工具的 patch 行。 +2. 将 `spawn_teammate({ name, description, prompt, context })` 替换为 `subagent({ description, prompt })`;继承对话历史时使用 `subagent_fork`。保存返回的 agent id。 +3. 使用 `send_message({ agent_id, message })` 和 `interrupt_agent({ agent_id })`。通过 `list_agents` 查询所有 Team 成员的 id。 +4. 任务的 `owner` 字段传入成员 Session id,结果读取 `ownerId`。以 Lead 的 Session id 取代 `lead` 别名。 +5. 将 `spawnTeammate`、`sendMessage` 和 `interrupt` 替换为 `ctx.subagents.startActivation`、`sendMessage` 和 `interrupt`。将 `membership`/`tryMembership` 替换为 `rootOf`,将 `listMembers` 替换为 `listDescendants`。将 `waitForChange` 替换为 `wait_agent`,随后重新读取任务。 +6. SDK `session/resume` 拒绝子代理会话。改为恢复根 Session。验证导航、嵌套任务分配,以及消息结束收件箱等待而任务提交不会。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.i18n.yaml new file mode 100644 index 0000000000..badcbe4e11 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md +/: + en: 2b713df685f8b593 + zh: 4e185e636a3b5d99 +/select-agent-teams-per-session: + en: 9e82418f46f6275b + zh: d1282eec79b37b59 +/select-agent-teams-per-session/change: + en: 3ba5920179726841 + zh: 940e0d956a523dbc +/select-agent-teams-per-session/migration: + en: 7b6dc660602d9c3b + zh: 8f8459198300aa46 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md new file mode 100644 index 0000000000..8f275535b6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Agent Teams defaults off for new Sessions and uses a saved per-Session selection." +--- + +# Select Agent Teams per Session + +English | [中文](guide.zh.md) + +## Change + +Agent Teams ships with base-backed profiles; new Sessions default to off. The Plugins page has no separate Agent Teams switch. The root Session’s selection controls task tools and Team guidance throughout its subagent tree. The model and reasoning menu offers **Use Agent Teams**, and the root conversation’s Subagent header control opens members above shared tasks in one panel while enabled. Child conversations retain navigation without a shared task board. + +Disabling Team retains tasks and subagents. Admitted task operations finish; queued operations check the current mode when they start. The selection survives restart. A historical task board without a saved selection remains enabled. The required `team/mode` event records selections; older readers reject this unfamiliar event. See the [persistence acknowledgement](../../../persistence-changes/2026-10-19-session-team-mode.md). + +## Migration + +1. Start each existing profile once. Profile loading removes the retired `@deepseek-ai/dsh-experimental-agent-team-profile` bundle selection; the base and Web bundles supply its plugins. Keep `agent-team`, `tool-agent-team`, and `ui-agent-team` row overrides. Custom compositions replace package names `@deepseek-ai/dsh-experimental-agent-team`, `@deepseek-ai/dsh-experimental-tool-agent-team`, and `@deepseek-ai/dsh-experimental-client-ui-agent-team` with `@deepseek-ai/dsh-agent-team`, `@deepseek-ai/dsh-tool-agent-team`, and `@deepseek-ai/dsh-client-ui-agent-team`. +2. Toggle **Use Agent Teams** in the root conversation’s model and reasoning menu. The `/team on` and `/team off` commands are removed. +3. Verify that enabling shows shared tasks in the root conversation below the Subagent tree in the same panel and exposes four task tools. Reload the Session to confirm the saved selection. Re-enabling after disabling restores the existing tasks. + +Client plugin consumers replace `TeamActionProps` with `TeamBoardProps`; task content registers in `conversation.session.header.actions.subagent.footer` instead of the header actions slot. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md new file mode 100644 index 0000000000..65f149a2f2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Agent Teams 在新 Session 中默认关闭,并使用按 Session 保存的选择。" +--- + +# 按 Session 选择智能体团队 + +[English](guide.md) | 中文 + +## 变更 + +Agent Teams 随基于 base 的 profile 提供;新 Session 默认关闭。插件页不再提供独立的智能体团队开关。根 Session 的选择控制整棵子代理树中的任务工具和 Team 提示词。模型与推理等级菜单提供**使用智能体团队**开关,开启后通过根会话的 Subagent 页头入口,在同一面板中查看上方成员与下方共享任务。子会话保留导航,不显示共享任务板。 + +关闭 Team 保留任务和子代理。已经进入执行的任务操作继续完成;排队中的操作在开始时检查当前模式。选择在重启后仍有效。没有保存选择的历史任务板保持开启。必读事件 `team/mode` 记录选择;旧读取器会拒绝该未知事件。参见[持久化变更确认](../../../persistence-changes/2026-10-19-session-team-mode.zh.md)。 + +## 迁移 + +1. 启动每个已有 profile 一次。加载时会移除已停用的 `@deepseek-ai/dsh-experimental-agent-team-profile` 组合选项;base 与 Web 组合提供对应插件。保留 `agent-team`、`tool-agent-team` 与 `ui-agent-team` 行覆盖。自定义组合将包名 `@deepseek-ai/dsh-experimental-agent-team`、`@deepseek-ai/dsh-experimental-tool-agent-team`、`@deepseek-ai/dsh-experimental-client-ui-agent-team` 分别替换为 `@deepseek-ai/dsh-agent-team`、`@deepseek-ai/dsh-tool-agent-team`、`@deepseek-ai/dsh-client-ui-agent-team`。 +2. 在根会话的模型与推理等级菜单中切换**使用智能体团队**。`/team on` 与 `/team off` 命令已移除。 +3. 在根会话中确认开启后通过 Subagent 入口在树下方查看共享任务板,并提供四个任务工具。重新加载 Session,确认选择已保存。关闭后再开启会恢复已有任务。 + +Client 插件消费者将 `TeamActionProps` 替换为 `TeamBoardProps`;任务内容注册到 `conversation.session.header.actions.subagent.footer`,而非页头操作插槽。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.i18n.yaml new file mode 100644 index 0000000000..12139cd087 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.md +/: + en: b087162d9a24f772 + zh: a32f167c3529fb1c +/subagent-activation-options: + en: 20a5b01ef11bff72 + zh: 919de21bc865ee9e +/subagent-activation-options/change: + en: 7cc2554992e98c53 + zh: 434540bcd037d1f5 +/subagent-activation-options/migration: + en: 2243d08661eb457c + zh: a928a8e7fb3515ff diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.md new file mode 100644 index 0000000000..3f2a202b0c --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "SubagentActivationSpec accepts task options directly instead of a nested request object." +--- + +# Subagent activation options + +English | [中文](guide.zh.md) + +## Change + +Plugin code calling `ctx.subagents.startActivation()` must pass `prompt`, `parent`, and optional execution settings directly on `SubagentActivationSpec`. The nested `request` field is removed. Type names, provider requests, cancellation, and result delivery are unchanged. + +## Migration + +1. In each `startActivation()` call, move the fields from `request` to the outer object. For an existing task object, replace `request: task` with `...task`; keep the activation's `label` and `signal` after the spread so they take precedence. +2. Replace reads such as `spec.request.prompt` with `spec.prompt`. Keep backend `SubagentStartRequest` implementations unchanged. +3. Typecheck the plugin and run its delegation tests to verify the updated calls. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.zh.md new file mode 100644 index 0000000000..32c2785bcc --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-activation-options/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "SubagentActivationSpec 直接接受任务选项,不再使用嵌套的 request 对象。" +--- + +# 子代理 activation 选项 + +[English](guide.md) | 中文 + +## 变更 + +调用 `ctx.subagents.startActivation()` 的插件代码必须将 `prompt`、`parent` 和可选执行设置直接放在 `SubagentActivationSpec` 上。嵌套的 `request` 字段已移除。类型名称、提供方请求、取消和结果投递保持不变。 + +## 迁移 + +1. 在每个 `startActivation()` 调用中,将 `request` 内的字段移到外层对象。已有任务对象时,将 `request: task` 替换为 `...task`;将 activation 的 `label` 和 `signal` 放在展开操作之后,以确保它们优先生效。 +2. 将 `spec.request.prompt` 等读取替换为 `spec.prompt`。保持后端的 `SubagentStartRequest` 实现不变。 +3. 对插件运行类型检查和委派测试,验证更新后的调用。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.i18n.yaml new file mode 100644 index 0000000000..464cd3ccbe --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.md +/: + en: 6955b11d6f698e4c + zh: 8a8d4d6edd5dea0c +/subagent-service-method-removal: + en: 102f43348f7c8eb0 + zh: be09ff117c31ada1 +/subagent-service-method-removal/change: + en: 8cd7f93df401c417 + zh: 27313127c2059e6b +/subagent-service-method-removal/migration: + en: f0f0f921f284efec + zh: 8b9e88e9412282c2 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.md new file mode 100644 index 0000000000..a1eaad618b --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "The subagent service removes drainChildren, listChildren, and list." +--- + +# Subagent service method removal + +English | [中文](guide.zh.md) + +## Change + +`ctx.subagents` removes `drainChildren(parent, childIds)`, `listChildren(parentSessionId, signal?)`, and `list()`. This affects plugins that release resident children by id, read direct-child catalogs through the service, or enumerate registered provider names. + +## Migration + +1. Retain the activation returned by `startActivation()` and await its `dispose()` to release that exact execution. An old activation cannot release a later execution of the same Session. There is no replacement for releasing the current resident child by id; use `drainDescendants([root])` only when closing the entire tree. `interrupt()` stops current work but preserves a local Activation. +2. For direct-child entries, use `ctx.sessionQuery.observeSession(parentSessionId, { signal })`, read `observation.projections?.values.subagentCatalog`, and dispose the observation with `using`. Load Session Query and the subagent service, and treat a missing catalog projection as unavailable. Keep `listDescendants()` for recursive discovery; its rows differ from direct catalog entries. +3. Use `getProvider(name)` to check known provider names. The service no longer enumerates all registered names. +4. Rebuild plugins against the updated service declarations. Verify registration and unload checks, exact-activation disposal, and catalog observation cleanup. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.zh.md new file mode 100644 index 0000000000..ce24ef1b90 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-service-methods/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "子代理服务移除 drainChildren、listChildren 和 list。" +--- + +# 子代理服务方法移除 + +[English](guide.md) | 中文 + +## 变更 + +`ctx.subagents` 移除 `drainChildren(parent, childIds)`、`listChildren(parentSessionId, signal?)` 和 `list()`。这会影响按 id 释放驻留子代理、通过服务读取直接子级目录或枚举已注册 provider 名称的插件。 + +## 迁移 + +1. 保留 `startActivation()` 返回的 activation,并等待其 `dispose()` 完成以释放那一次执行。旧 activation 不能释放同一 Session 后来恢复的执行。按 id 释放当前驻留子代理没有替代方法;仅在关闭整棵树时使用 `drainDescendants([root])`。`interrupt()` 停止当前工作,但保留本地 Activation。 +2. 读取直接子级条目时,使用 `ctx.sessionQuery.observeSession(parentSessionId, { signal })`,读取 `observation.projections?.values.subagentCatalog`,并通过 `using` 释放观察对象。加载 Session Query 和子代理服务,并将缺失的目录投影视为不可用。递归发现继续使用 `listDescendants()`;它返回的行与直接目录条目不同。 +3. 使用 `getProvider(name)` 检查已知 provider 名称。服务不再枚举全部已注册名称。 +4. 根据更新后的服务声明重新构建插件,验证注册和卸载检查、指定 activation 的释放以及目录观察对象的清理。 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.i18n.yaml new file mode 100644 index 0000000000..1ef94f1d8f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md +/: + en: 9d77440fbd1ac5ee + zh: e51db37880a28684 +/subagent-user-controls-address-the-target-session: + en: 8f5fcee305e3a5d7 + zh: c6bb2c762cd2b86d +/subagent-user-controls-address-the-target-session/change: + en: 0a309d3a2a123b46 + zh: 416f075bfdb8664a +/subagent-user-controls-address-the-target-session/migration: + en: f3a61ba7c3a5110e + zh: 95c88d6f9d685fd4 diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md new file mode 100644 index 0000000000..9080ef5f66 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "Subagent user controls address only the target Session, rename the interrupt endpoint, and require target Session permissions instead of global permissions." +--- + +# Subagent user controls address the target Session + +English | [中文](guide.zh.md) + +## Change + +Browser and custom Remote callers send subagent prompts without `parentSessionId` or `mode`. `subagents/interruptByParent(childSessionId, parentSessionId, mode)` is replaced by `subagents/interruptByUser(childSessionId)`. Creation ancestry, history addresses, completion recipients, and persisted Session data are unchanged. + +Both operations name the child as a `session` access resource. Non-owner policies must grant the corresponding action on that Session; a `global` binding or a binding on its parent does not grant access. Owner behavior is unchanged. Model messages remain limited to one subagent tree, and model interruption remains ancestor-only. + +The same-process `SubagentInterruptAuthority` user variant is `{ kind: 'user' }`. The published `@deepseek-ai/dsh-subagent/internal` entry point is removed, including its host prompt adapters and tool identity markers. Remote authorization is performed by the Gateway. + +Old prompt payloads with extra fields inside `request` can decode on the new Host, subject to its new access rules. Old interrupt calls fail because the endpoint is removed. New callers require the new Host. Upgrade custom clients and hosts together; the bundled Web client is delivered with its Host. + +## Migration + +1. Remove `parentSessionId` and `mode` from subagent prompt requests. Keep `childSessionId`, `requestId`, `delivery`, `content`, and optional `clientTimeZone`. +2. Replace calls to `interruptByParent(childId, parentId, 'continuable')` with `interruptByUser(childId)`. +3. Update non-owner policies to grant `subagents/prompt` and/or `subagents/interruptByUser` on `{ kind: 'session', id: childId }`. Parent-to-child grants remain an explicit policy decision. +4. Remove `parentSessionId` from `{ kind: 'user' }` interrupt authorities. Replace imports from `@deepseek-ai/dsh-subagent/internal`: authenticated user prompts use `subagents/prompt`; model-authored messages use `ctx.subagents.sendMessage()`. There is no public arbitrary-source host prompt adapter. Custom tools own their instructions through tool descriptions and `systemPrompt.context()`, without identity markers. Keep parent ids in history addresses and creation records. +5. Verify that a target-authorized user can send and interrupt, while a user authorized only for the parent or global resource is refused before any input or cancellation is admitted. diff --git a/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.zh.md new file mode 100644 index 0000000000..8b9d8fab50 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.2/subagent-user-controls/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "子代理用户控制仅按目标 Session 寻址,重命名中断端点,并以目标 Session 权限替代 global 权限。" +--- + +# 子代理用户控制按目标 Session 寻址 + +[English](guide.md) | 中文 + +## 变更 + +浏览器和自定义 Remote 调用方发送子代理提示词时,不再提供 `parentSessionId` 或 `mode`。`subagents/interruptByParent(childSessionId, parentSessionId, mode)` 替换为 `subagents/interruptByUser(childSessionId)`。创建祖先、历史地址、完成通知接收者和持久化 Session 数据保持不变。 + +两个操作都将子会话声明为 `session` 访问资源。非 owner 策略必须授予该 Session 上对应操作的权限;`global` 绑定或父会话上的绑定不授予访问权。owner 行为保持不变。模型消息仍限于同一棵子代理树,模型中断仍仅允许祖先发起。 + +同进程 `SubagentInterruptAuthority` 的用户分支为 `{ kind: 'user' }`。已发布的 `@deepseek-ai/dsh-subagent/internal` 入口已删除,包括宿主 prompt 适配器和工具身份标记。远程授权由 Gateway 执行。 + +旧提示词载荷在 `request` 内多带字段时,可以在新 Host 上解码,但须满足新的访问规则。旧中断调用因端点已移除而失败。新调用方要求新 Host。自定义客户端和宿主应一起升级;内置 Web 客户端随 Host 一起交付。 + +## 迁移 + +1. 从子代理提示词请求中移除 `parentSessionId` 和 `mode`。保留 `childSessionId`、`requestId`、`delivery`、`content` 和可选的 `clientTimeZone`。 +2. 将 `interruptByParent(childId, parentId, 'continuable')` 调用替换为 `interruptByUser(childId)`。 +3. 更新非 owner 策略,在 `{ kind: 'session', id: childId }` 上授予 `subagents/prompt` 和/或 `subagents/interruptByUser` 权限。父会话到子会话的授权仍由策略显式决定。 +4. 从 `{ kind: 'user' }` 中断授权中移除 `parentSessionId`。替换 `@deepseek-ai/dsh-subagent/internal` 的导入:经过认证的用户 prompt 使用 `subagents/prompt`;模型编写的消息使用 `ctx.subagents.sendMessage()`。不再提供允许任意来源的公开宿主 prompt 适配器。自定义工具通过工具描述和 `systemPrompt.context()` 提供说明,无需身份标记。历史地址和创建记录仍保留父级 id。 +5. 验证获准操作目标的用户能够发送和中断,而仅获准操作父会话或 global 资源的用户在输入或取消被接纳前遭到拒绝。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.i18n.yaml new file mode 100644 index 0000000000..dadc616c76 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.md +/: + en: f09a5fde2cedb48c + zh: beec903a10ed62ee +/agent-waits-require-inbox-input: + en: 96c9f5fc6514557a + zh: aac52f37d543ed9b +/agent-waits-require-inbox-input/change: + en: 568583cb15f85337 + zh: 6c7e3028f23d1f3e +/agent-waits-require-inbox-input/migration: + en: 156a027d11ad3769 + zh: 301029cecd3ae640 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.md new file mode 100644 index 0000000000..9252add26b --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "Task-board changes no longer end wait_agent calls; send a message to request further work." +--- +# Agent waits require inbox input + +English | [中文](guide.zh.md) + +## Change + +`wait_agent` waits only for the calling Agent's next-step inbox. Task creation, assignment, completion, and other task updates no longer end an active wait. They do not add inbox messages or start idle Agents. Queued next-turn input and other Agents' status changes also leave the wait pending. + +Existing next-step input returns immediately; new messages, completion notifications, and user steering end the wait without consuming that input. Timeout and cancellation behavior remain unchanged. + +## Migration + +1. After changing a task, use `send_message` when its owner or another member needs to act on the update. Do not rely on a task mutation to release `wait_agent`. +2. Read current task state before acting; a task update is not a message or an instruction to begin a new turn. +3. Verify that a task update leaves an empty-inbox wait pending, then send a message and confirm that the wait returns with `timedOut: false`. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.zh.md new file mode 100644 index 0000000000..27bd015147 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/inbox-only-agent-wait/guide.zh.md @@ -0,0 +1,19 @@ +--- +kind: upgrade-guide +description: "任务板变更不再结束 wait_agent 调用;需要继续工作时发送消息。" +--- +# Agent 等待需要收件箱输入 + +[English](guide.md) | 中文 + +## 变更 + +`wait_agent` 仅等待调用 Agent 的下一步收件箱。任务创建、分配、完成和其他任务更新不再结束正在进行的等待,也不添加收件箱消息或启动空闲 Agent。排队的下一轮输入和其他 Agent 的状态变化同样不会结束等待。 + +已有下一步输入时立即返回;新消息、完成通知和用户引导会结束等待,但不消费输入。超时和取消行为保持不变。 + +## 迁移 + +1. 修改任务后,需要任务所有者或其他成员处理更新时使用 `send_message`。不要依赖任务修改来结束 `wait_agent`。 +2. 行动前读取当前任务状态;任务更新不是消息,也不是开始新轮次的指令。 +3. 验证任务更新不会结束空收件箱上的等待,然后发送消息,确认等待返回 `timedOut: false`。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.i18n.yaml new file mode 100644 index 0000000000..2972e9a489 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.md +/: + en: 10f7c9b47f2b39f2 + zh: 2c93aa4e6bef0f33 +/subagent-runtime-ownership: + en: 20c105e3d68b46ee + zh: 685c1ad4eef7eefb +/subagent-runtime-ownership/change: + en: bacb015157610964 + zh: 635055eab24394ac +/subagent-runtime-ownership/migration: + en: 3fb0ce93ad94074f + zh: 49e2f520191d6c53 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.md new file mode 100644 index 0000000000..2cc07287e3 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: Agent factory ownership parameters and registry tree queries are removed; subagent Activations own runtime tree membership. +--- + +# Subagent runtime ownership + +English | [中文](guide.zh.md) + +## Change + +`@deepseek-ai/dsh-agent` removes the create/resume runtime-owner parameter (`parentAgent` or `ownerAgent`), `AgentRegistry.isOwnedBy()`, `AgentRegistry.roots()`, and the owner argument of `enter()`. Direct factory creation no longer enrolls an Agent in a managed subagent tree. Custom factories no longer implement runtime tree ownership. + +The subagent service resolves runtime membership from its existing Activations through `rootOf(agent)`. The Session format and Cordis context ownership of handles are unchanged. + +## Migration + +1. Create delegated work through `ctx.subagents.startActivation()` with a registered provider. Remove ownership parameters from direct `ctx.agents.create()` and `resume()` calls; these operations create independent runtime instances. +2. Use `ctx.agents.get(id)` and `list()` for live lookup. To select ordinary live Agents, filter `list()` by `agent.session.header.origin !== 'subagent'`; historical ordinary forks can still have `parentSession`. +3. Query the live tree root with `ctx.subagents.rootOf(agent)` and compare Agent objects, not only ids. Ordinary live Agents resolve to themselves; unmanaged delegated or stale instances throw `SubagentError` with code `UNAUTHORIZED`. Read `session.header.parentSession` for the direct creator; use durable subagent catalogs when traversing offline creation ancestors. +4. Update custom factory implementations to call `ctx.agents.enter(agent)` after setup. Retain caller-context disposal, initialization rollback, and exact-instance registration checks. Runtime tree membership is available after managed activation publication; `agent/created` runs before that point. Verify stale instances cannot reuse a disposed instance's ownership. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.zh.md new file mode 100644 index 0000000000..ee212f5c96 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/subagent-runtime-ownership/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: Agent 工厂归属参数和注册表树查询已删除;subagent Activation 拥有运行时树成员关系。 +--- + +# Subagent 运行时归属 + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-agent` 删除 create/resume 的运行时归属参数(`parentAgent` 或 `ownerAgent`)、`AgentRegistry.isOwnedBy()`、`AgentRegistry.roots()` 以及 `enter()` 的 owner 参数。直接通过工厂创建 Agent 不再将其加入托管 subagent 树。自定义工厂不再实现运行时树归属。 + +subagent 服务通过 `rootOf(agent)` 从已有 Activation 解析运行时成员关系。Session 格式和 Cordis 上下文对句柄的所有权不变。 + +## 迁移 + +1. 通过 `ctx.subagents.startActivation()` 和已注册提供方创建委派工作。删除直接调用 `ctx.agents.create()` 与 `resume()` 时的归属参数;这些操作创建独立的运行时实例。 +2. 通过 `ctx.agents.get(id)` 与 `list()` 查询存活实例。筛选普通存活 Agent 时,用 `agent.session.header.origin !== 'subagent'` 过滤 `list()`;历史普通 fork 仍可能包含 `parentSession`。 +3. 通过 `ctx.subagents.rootOf(agent)` 查询存活树根,并比较 Agent 对象,而非仅比较 id。普通存活 Agent 返回自身;非托管的委派实例或失效实例抛出代码为 `UNAUTHORIZED` 的 `SubagentError`。直接创建者读取 `session.header.parentSession`;遍历离线创建祖先时使用持久化 subagent 目录。 +4. 更新自定义工厂,在 setup 后调用 `ctx.agents.enter(agent)`。保留调用方上下文释放、初始化回滚和确切实例注册检查。运行时树成员关系在托管 activation 发布后可用;`agent/created` 早于该时点。验证失效实例不能复用已释放实例的归属。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.i18n.yaml new file mode 100644 index 0000000000..8916474764 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.md +/: + en: 1c39dada6c6162a7 + zh: ab2f5e2824bfbf0c +/select-team-mode-from-the-conversation-menu: + en: d570d0f970f6a77a + zh: 7a722461f27bc620 +/select-team-mode-from-the-conversation-menu/change: + en: 37b569a98d41587d + zh: ce9c8ee4c35ac634 +/select-team-mode-from-the-conversation-menu/migration: + en: d548bbca6276ed74 + zh: 2468a89bd342b3ff diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.md new file mode 100644 index 0000000000..0d54d68096 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "The Team mode slash command is removed; use the root conversation menu." +--- + +# Select Team mode from the conversation menu + +English | [中文](guide.zh.md) + +## Change + +`/team on` and `/team off` are no longer registered. The root conversation’s **Use Agent Teams** switch calls `remote.agentTeams.setEnabled` directly. Saved selections, task retention, and root-only authorization are unchanged. + +## Migration + +1. Enable or disable **Use Agent Teams** in the root conversation’s model and reasoning menu. +2. Plugins that execute the command should call `ctx.agentTeams.setEnabled(rootAgent, enabled)` instead; browser clients call `remote.agentTeams.setEnabled(rootSessionId, enabled)`. +3. Confirm the switch reflects the saved selection after reloading the Session. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.zh.md new file mode 100644 index 0000000000..c8e847e91f --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-mode-menu/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Team 模式斜杠命令已移除,请使用根会话菜单。" +--- + +# 从会话菜单选择 Team 模式 + +[English](guide.md) | 中文 + +## 变更 + +`/team on` 和 `/team off` 不再注册。根会话的**使用智能体团队**开关直接调用 `remote.agentTeams.setEnabled`。保存的选择、任务保留以及仅允许根会话修改的授权规则不变。 + +## 迁移 + +1. 在根会话的模型与推理等级菜单中打开或关闭**使用智能体团队**。 +2. 执行该命令的插件改为调用 `ctx.agentTeams.setEnabled(rootAgent, enabled)`;浏览器客户端调用 `remote.agentTeams.setEnabled(rootSessionId, enabled)`。 +3. 重新加载 Session,确认开关反映已保存的选择。 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.i18n.yaml new file mode 100644 index 0000000000..b709e46f55 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.md +/: + en: 185304d86b229610 + zh: b98e40567653a55f +/team-projection-retains-tasks-and-mode: + en: c20510084cf9d412 + zh: ee26f2365ab5d216 +/team-projection-retains-tasks-and-mode/change: + en: 5b92baca861b7281 + zh: 57b4162fb425163c +/team-projection-retains-tasks-and-mode/migration: + en: 6c30148dea17af5e + zh: 81b7fa72cc118252 diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.md b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.md new file mode 100644 index 0000000000..fe0258e51e --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Team projection stops restoring historical teammates and mailbox state while retaining tasks and saved mode." +--- + +# Team projection retains tasks and mode + +English | [中文](guide.zh.md) + +## Change + +The `agentTeam` projection no longer restores `members`, `messages`, or `delivered` from historical `team/member` and `team/message/*` events. It ignores their payloads, so historical roster or mailbox validation failures no longer block task reads or writes. Historical teammates are not restored and queued mail is not delivered. + +Task revisions, task owners, deleted-task records, and the saved Team mode remain supported. Ordinary subagent discovery and messaging are unchanged. The Session format and committed log files do not change; projection checkpoint version 7 rebuilds older cached state from the log. + +## Migration + +1. No data conversion or configuration change is required. Open the Session normally to rebuild incompatible projection checkpoints. +2. Use `list_agents` and `send_message` for current teammates. Read historical roster or mailbox events from the original Session log if you need an archive; the Team projection no longer supplies these collections. +3. Confirm that the task board and saved Team mode are restored. Historical roster and mailbox records do not grant task-assignment authority. diff --git a/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.zh.md new file mode 100644 index 0000000000..b6b131599e --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.3/team-projection/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Team 投影停止恢复历史队友与邮箱状态,同时保留任务和保存的模式。" +--- + +# Team 投影保留任务与模式 + +[English](guide.md) | 中文 + +## 变更 + +`agentTeam` 投影不再从历史 `team/member` 和 `team/message/*` 事件恢复 `members`、`messages` 或 `delivered`。投影忽略这些载荷,因此历史名册或邮箱校验失败不再阻止任务读写。不恢复历史队友,也不投递排队邮件。 + +任务修订、任务所有者、已删除任务记录和保存的 Team 模式仍受支持。普通子代理发现与通信保持不变。Session 格式和已提交日志文件不变;投影检查点版本 7 从日志重建旧缓存状态。 + +## 迁移 + +1. 无需转换数据或修改配置。正常打开 Session 即可重建不兼容的投影检查点。 +2. 使用 `list_agents` 和 `send_message` 与当前队友协作。需要归档信息时,从原始 Session 日志读取历史名册或邮箱事件;Team 投影不再提供这些集合。 +3. 确认任务板和保存的 Team 模式已恢复。历史名册与邮箱记录不授予任务分配权限。 diff --git a/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.i18n.yaml b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.i18n.yaml new file mode 100644 index 0000000000..98ac4521b5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.md +/: + en: ec5a417eaedb6661 + zh: b5adde6bf6c32fd0 +/reasoning-body-slot-text-fields: + en: ea09fc75b8c4467e + zh: 64d548cbdb42792a +/reasoning-body-slot-text-fields/change: + en: ff40c45f886d47f5 + zh: 18d7bb5456b048e6 +/reasoning-body-slot-text-fields/migration: + en: 49cd6281b4aef73a + zh: 6bdf66c3f82bfa8b diff --git a/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.md b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.md new file mode 100644 index 0000000000..1aac016172 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "Reasoning Body Slot text carries display-ready content, with original output in rawText." +--- + +# Reasoning Body Slot text fields + +English | [中文](guide.zh.md) + +## Change + +Contributions to `conversation.chat.reasoning.body` receive the model output in the new `rawText` field. The existing `text` field supplies Chat's prepared display text instead of the original output. `running` is unchanged. This affects custom reasoning renderers and translation wrappers. + +The `conversation.chat.reasoning.content` Factory still accepts `text`, `running`, and optional `labels`. It renders the caller-selected Markdown. The [Chat README](../../../../packages/client/ui-chat/README.md#grouped-rendering) documents the Slot. + +## Migration + +1. Keep reading `text` for ordinary rendering, translation requests, and untranslated views. Update extensions that need the full model output to read `rawText`. +2. Pass the selected `text`, or its translation, to the Content Factory without repeating Chat's display processing. +3. Rebuild the extension and verify streamed and settled rendering, translation, and the untranslated view with each supported model format. diff --git a/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.zh.md b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.zh.md new file mode 100644 index 0000000000..9ebc9146c9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.1-rc.4/reasoning-body-props/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "推理 Body Slot 的 text 提供显示文本,rawText 保留原始输出。" +--- + +# 推理 Body Slot 的文本字段 + +[English](guide.md) | 中文 + +## 变更 + +`conversation.chat.reasoning.body` 扩展通过新增的 `rawText` 字段接收模型输出。现有的 `text` 字段提供 Chat 处理后的显示文本,替代原始输出。`running` 保持不变。这会影响自定义推理渲染器和翻译包装组件。 + +`conversation.chat.reasoning.content` Factory 仍接收 `text`、`running` 和可选的 `labels`。它渲染调用方选定的 Markdown。[Chat README](../../../../packages/client/ui-chat/README.zh.md#grouped-rendering) 介绍了该 Slot。 + +## 迁移 + +1. 在普通渲染、翻译请求和未翻译视图中继续读取 `text`。需要完整模型输出的扩展改为读取 `rawText`。 +2. 向 Content Factory 传入选定的 `text` 或其译文,不要重复执行 Chat 的显示处理。 +3. 重新构建扩展,使用每种支持的模型格式验证流式与完成后的渲染、翻译和未翻译视图。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.i18n.yaml new file mode 100644 index 0000000000..0ae0e63998 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md +/: + en: 94b863d7f57ffb37 + zh: 158af8a6f172ee5f +/filesystem-mutations-no-longer-require-a-prior-read-by-default: + en: e6dd0c06f99737e4 + zh: a706b0bbdea94aac +/filesystem-mutations-no-longer-require-a-prior-read-by-default/change: + en: d7a64f82068f7869 + zh: 8a42e9c0a56cd3e5 +/filesystem-mutations-no-longer-require-a-prior-read-by-default/migration: + en: c156c11ab737f75a + zh: faadea98c8558d07 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md new file mode 100644 index 0000000000..7e9c9a384e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "The fs-observation-policy row ships disabled, so write, edit, and apply_patch no longer require a prior read, and dsh-base plus the Web standard preset gain apply_patch." +--- + +# Filesystem mutations no longer require a prior read by default + +English | [中文](guide.zh.md) + +## Change + +In 0.2.2-alpha.2, `dsh-base` mounted `@deepseek-ai/dsh-fs-observation-policy`, so in every base-backed profile `write` refused to overwrite a file the model had not read, `edit` refused an unread or externally changed file, and the model's guidance named the policy. The `fs-observation-policy` row now ships `disabled: true`: `write` overwrites, `edit` replaces literal text, and the new `apply_patch` applies hunks on context match alone, each unconditionally. The `write` and `edit` guidance still asks for a prior read but no longer cites the policy. Review capture, sandbox confinement, and `fs/observed` events are unchanged. + +The `dsh-base` `tool-fs` row (headless, SDK, and ACP) and the Web `standard` preset now list `apply_patch` (`applyPatch: true`); the Web `ptc` and `cordis` presets keep `applyPatch: false`. + +Affected: the base-backed profiles (`headless`, `web`, `sdk`, `acp`; `sdk-minimal` stacks no `dsh-base`, never mounted the policy, and keeps its text tools off), profile patches that override the `fs-observation-policy` or `tool-fs` rows by id, and recorded expectations that include an `FS_NOT_OBSERVED` or `FS_STALE_VERSION` refusal. + +## Migration + +1. To keep read-before-write behavior, add to the profile's `cordis.patch.yml` (`$DSH_HOME/profiles//cordis.patch.yml`): + + ```yaml + - id: fs-observation-policy + disabled: false + ``` + + A profile patch that already carries this row with `disabled: false` needs no change; one that set `disabled: true` to opt out can drop that override. +2. To run without `apply_patch`, add `- {id: tool-fs, config: {applyPatch: false}}` to the profile's `cordis.patch.yml` for `headless`, `sdk`, and `acp` (the shipped [PTC overlay](../../../../apps/cli/config/examples/ptc.yml) already does so, matching the Web `ptc` preset); for the Web `standard` preset, edit it from the Agent presets settings page or set `applyPatch: false` on its `tool-fs` row in `packages/bundle/web-app/presets/standard.patch.yml`. +3. Confirm with `dsh --profile --dump-config`: the `fs-observation-policy` row shows the intended `disabled` value, and the `tool-fs` rows show the intended `applyPatch` value. In a session, an `edit` of a file that was not read succeeds with the row disabled and fails with `FS_NOT_OBSERVED` with it enabled. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md new file mode 100644 index 0000000000..2580df987b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "fs-observation-policy 行随发行版禁用,write、edit 与 apply_patch 不再要求先读,dsh-base 与 Web standard preset 新增 apply_patch。" +--- + +# 文件系统修改默认不再要求先读 + +[English](guide.md) | 中文 + +## 变更 + +在 0.2.2-alpha.2 中,`dsh-base` 挂载了 `@deepseek-ai/dsh-fs-observation-policy`,因此所有叠加 base 的 profile 中,`write` 拒绝覆盖模型未读过的文件,`edit` 拒绝未读或被外部修改的文件,模型提示语也点名该策略。现在 `fs-observation-policy` 行以 `disabled: true` 交付:`write` 直接覆盖,`edit` 直接替换字面文本,新增的 `apply_patch` 只凭上下文匹配应用 hunk,三者均无条件执行。`write` 与 `edit` 的提示语仍要求先读,但不再引用该策略。Review 采集、沙箱围栏与 `fs/observed` 事件不变。 + +`dsh-base` 的 `tool-fs` 行(headless、SDK、ACP)与 Web 的 `standard` preset 现在列出 `apply_patch`(`applyPatch: true`);Web 的 `ptc`、`cordis` preset 保持 `applyPatch: false`。 + +受影响范围:叠加 base 的 profile(`headless`、`web`、`sdk`、`acp`;`sdk-minimal` 不叠加 `dsh-base`,从未挂载该策略,文本工具保持关闭),按 id 覆盖 `fs-observation-policy` 或 `tool-fs` 行的 profile patch,以及包含 `FS_NOT_OBSERVED` 或 `FS_STALE_VERSION` 拒绝的录制期望。 + +## 迁移 + +1. 要保留先读后写行为,在 profile 的 `cordis.patch.yml`(`$DSH_HOME/profiles//cordis.patch.yml`)中加入: + + ```yaml + - id: fs-observation-policy + disabled: false + ``` + + 已带有该行且 `disabled: false` 的 profile patch 无需改动;为退出策略而写 `disabled: true` 的可以删掉该覆盖。 +2. 要在没有 `apply_patch` 的情况下运行,为 `headless`、`sdk`、`acp` 在 profile 的 `cordis.patch.yml` 中加入 `- {id: tool-fs, config: {applyPatch: false}}`(随发行版交付的 [PTC overlay](../../../../apps/cli/config/examples/ptc.yml) 已这样做,与 Web `ptc` preset 一致);对 Web `standard` preset,在 Agent presets 设置页编辑它,或在 `packages/bundle/web-app/presets/standard.patch.yml` 的 `tool-fs` 行上设置 `applyPatch: false`。 +3. 用 `dsh --profile --dump-config` 确认:`fs-observation-policy` 行显示预期的 `disabled` 值,`tool-fs` 行显示预期的 `applyPatch` 值。在会话中,行禁用时对未读文件执行 `edit` 成功,启用时以 `FS_NOT_OBSERVED` 失败。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.i18n.yaml new file mode 100644 index 0000000000..001398befb --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.md +/: + en: 18359b607f378e44 + zh: c94f503a30b8ebe0 +/pi-ai-request-image-count: + en: 8ed160da9859a7d0 + zh: 5252360ebf0a2c4d +/pi-ai-request-image-count/change: + en: c000351899001605 + zh: fd5048dba5987295 +/pi-ai-request-image-count/migration: + en: 1bdf29eb86d198ca + zh: a60f1719dccd6717 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.md new file mode 100644 index 0000000000..8607fdb21a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "pi-ai routes now offload the oldest history images once a request carries more than 50 retained images." +--- + +# pi-ai request image count + +English | [中文](guide.zh.md) + +## Change + +`llm-pi-ai` previously bounded request images only by `maxRequestImageBytes`, so every retained image was resent until that byte bound was reached. Each provider route now also has `maxRequestImages` (default 50) and `imageOffloadCountQuantum` (default 10). When a request carries more retained images than `maxRequestImages`, `dsh-compaction-image-offload` replaces the oldest `imageOffloadCountQuantum` images with placeholder text and retries. The omission is recorded in the Session and does not revert. This affects Sessions with more than 50 images on any pi-ai route, including providers that accept more images per request. + +## Migration + +1. Check the per-request image limit of each pi-ai provider. In the `llm-pi-ai` configuration in `cordis.patch.yml`, set `providers..maxRequestImages` to that limit when it is higher than 50. +2. To change how many images one overflow offloads, set `providers..imageOffloadCountQuantum`; it must not exceed `maxRequestImages`. +3. Reopen the profile configuration and confirm the saved values. See the [provider configuration reference](../../../../packages/llm/llm-pi-ai/README.md). diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.zh.md new file mode 100644 index 0000000000..22d8a92950 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/pi-ai-request-image-count/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "当请求保留的图片超过 50 张时,pi-ai 路由现在会省略历史中最老的图片。" +--- + +# pi-ai 请求图片数量 + +[English](guide.md) | 中文 + +## 变更 + +`llm-pi-ai` 原先只用 `maxRequestImageBytes` 限制请求图片,因此在达到该字节上限前会重发每张保留图片。现在每条提供方路由还有 `maxRequestImages`(默认 50)和 `imageOffloadCountQuantum`(默认 10)。请求保留的图片多于 `maxRequestImages` 时,`dsh-compaction-image-offload` 把最老的 `imageOffloadCountQuantum` 张图片替换为占位文本并重试。该省略记录在 Session 中,不会回退。这会影响任何 pi-ai 路由上超过 50 张图片的 Session,包括单次请求接受更多图片的提供方。 + +## 迁移 + +1. 核对每个 pi-ai 提供方的单次请求图片上限。上限高于 50 时,在 `cordis.patch.yml` 的 `llm-pi-ai` 配置中把 `providers..maxRequestImages` 设为该上限。 +2. 如需改变每次超限省略的图片数,设置 `providers..imageOffloadCountQuantum`;它不得超过 `maxRequestImages`。 +3. 重新打开 profile 配置,确认保存的数值。参见[提供方配置参考](../../../../packages/llm/llm-pi-ai/README.zh.md)。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.i18n.yaml new file mode 100644 index 0000000000..5adf2d9984 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.md +/: + en: e48b8561bd5e8c36 + zh: 250e816f38495c97 +/projection-frames-list-every-key-one-event-changed: + en: 3f22f3e46a3903db + zh: 7694cef52b9aa7f0 +/projection-frames-list-every-key-one-event-changed/change: + en: f0d17c8787e7da13 + zh: 3b193ae03232b6be +/projection-frames-list-every-key-one-event-changed/migration: + en: fa9b8d4e4c426754 + zh: 70f21eb8ec280fdd diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.md new file mode 100644 index 0000000000..54b292f15f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "Live Session projection frames list every key one committed event changed instead of carrying one key each." +--- + +# Projection frames list every key one event changed + +English | [中文](guide.zh.md) + +## Change + +Live `projection` frames on the `session/control` stream and change frames on the `session/observeProjections` stream carried one projection key each: `{ type: 'projection', sessionId, key, value, seq }`. An event that changed several keys produced several frames with the same `seq`. Each frame now carries every key one committed event changed: `{ type: 'projection', sessionId, seq, changes }` on `session/control`, and the same fields without `sessionId` on `session/observeProjections`. `changes` holds one `{ key, val }` entry per changed key, without duplicate keys, where `val` is the key's new value. A key absent from `changes` is unchanged. The exported types `SessionProjectionUpdate`, `SessionProjectionChange`, `SessionControlFrame`, and `SessionProjectionFrame` of `@deepseek-ai/dsh-api-session-controller` follow the new fields. + +Baseline frames, `session/projections` reads, and the Host listener `ctx.sessionProjections.onChanged` keep their behavior. The Host adds `ctx.sessionProjections.onEventChanged` for one call per committed event. + +This affects Remote clients that read either stream directly, such as test harnesses, proxies, and external dashboards. The bundled Web client and `@deepseek-ai/dsh-api-session-controller/client` read the new frames. + +## Migration + +1. Replace a call such as `apply(frame.key, frame.value, frame.seq)` with a loop over `frame.changes`: + + ```ts + import type { SessionControlFrame } from '@deepseek-ai/dsh-api-session-controller' + + declare const frame: Extract + declare function apply(key: string, value: unknown, seq: number): void + + for (const change of frame.changes) apply(change.key, change.val, frame.seq) + ``` + +2. Replace key tests such as `frame.key === 'inbox'` with `frame.changes.find(change => change.key === 'inbox')`, and read the value from that entry's `val`. +3. Confirm that one committed event yields at most one `projection` frame per Session, and that the values your client holds match a fresh `session/projections` read. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.zh.md new file mode 100644 index 0000000000..20b86923d2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/projection-event-frames/guide.zh.md @@ -0,0 +1,32 @@ +--- +kind: upgrade-guide +description: "实时 Session projection 帧改为列出一个已提交事件改变的全部 key,不再每帧只带一个 key。" +--- + +# Projection 帧列出一个事件改变的全部 key + +[English](guide.md) | 中文 + +## 变更 + +`session/control` 流上的实时 `projection` 帧与 `session/observeProjections` 流上的变更帧,原先每帧只带一个 projection key:`{ type: 'projection', sessionId, key, value, seq }`。一个事件改变多个 key 时,会产生多帧 `seq` 相同的帧。现在每帧携带一个已提交事件改变的全部 key:`session/control` 上是 `{ type: 'projection', sessionId, seq, changes }`,`session/observeProjections` 上是去掉 `sessionId` 的同样字段。`changes` 中每个变化的 key 一项 `{ key, val }`,key 不重复,`val` 是该 key 的新值。未出现在 `changes` 中的 key 没有变化。`@deepseek-ai/dsh-api-session-controller` 导出的 `SessionProjectionUpdate`、`SessionProjectionChange`、`SessionControlFrame` 与 `SessionProjectionFrame` 类型随新字段更新。 + +baseline 帧、`session/projections` 读取以及 Host 监听器 `ctx.sessionProjections.onChanged` 的行为不变。Host 新增 `ctx.sessionProjections.onEventChanged`,按每个已提交事件调用一次。 + +受影响的是直接读取这两条流的 Remote 客户端,例如测试 harness、代理和外部看板。内置 Web 客户端与 `@deepseek-ai/dsh-api-session-controller/client` 已读取新帧。 + +## 迁移 + +1. 把 `apply(frame.key, frame.value, frame.seq)` 这类调用改为遍历 `frame.changes`: + + ```ts + import type { SessionControlFrame } from '@deepseek-ai/dsh-api-session-controller' + + declare const frame: Extract + declare function apply(key: string, value: unknown, seq: number): void + + for (const change of frame.changes) apply(change.key, change.val, frame.seq) + ``` + +2. 把 `frame.key === 'inbox'` 这类 key 判断改为 `frame.changes.find(change => change.key === 'inbox')`,并从该项的 `val` 读取值。 +3. 确认一个已提交事件对每个 Session 至多产生一个 `projection` 帧,且客户端持有的值与重新调用 `session/projections` 读到的一致。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.i18n.yaml new file mode 100644 index 0000000000..33ebcae0fb --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.md +/: + en: 534c875c6423421f + zh: 041b62aed9b5689f +/schedule-tools-manage-every-host-task-by-rrule-and-target: + en: 390ea3dd55433b66 + zh: eb1b5e4cf2ae6551 +/schedule-tools-manage-every-host-task-by-rrule-and-target/change: + en: 3609120a0dee5cee + zh: 0b5d3c77c998e46d +/schedule-tools-manage-every-host-task-by-rrule-and-target/migration: + en: ca46aafc12815cc4 + zh: c99e9160e2bb871e diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.md new file mode 100644 index 0000000000..b9d8fd33ae --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.md @@ -0,0 +1,37 @@ +--- +kind: upgrade-guide +description: "The Schedule model tools become `schedule_create`, `schedule_list`, `schedule_view`, and `schedule_edit` over every Host task, and `schedule_update` and `schedule_delete` are removed." +--- + +# Schedule tools manage every Host task by RRULE and target + +English | [中文](guide.zh.md) + +## Change + +Earlier, `@deepseek-ai/dsh-tool-schedule` registered `schedule_create`, `schedule_list`, `schedule_update`, and `schedule_delete`. They managed only the reminders of the calling Session, and `schedule_create` took one timing selector: `after_seconds`, `at`, `every_seconds`, `daily`, `weekly`, or `cron`. + +The package now registers `schedule_create`, `schedule_list`, `schedule_view`, and `schedule_edit`: + +- `schedule_create` takes `title`, `prompt`, `rrule` (one `DTSTART` line and one `RRULE` line), and `target` (`this_session`, `new_once`, or `new`). It accepts no timing selector. +- `schedule_list` returns one page `{ items, shown, total, limit, offset }` of active, paused, and ended tasks instead of an array of active reminders. +- `schedule_view` reads one task by id. +- `schedule_edit` with `action: "update"` replaces `schedule_update` and can also change `rrule` and `target` or pause and resume a task; `action: "delete"` replaces `schedule_delete`. +- Each tool reads, changes, and deletes any Host task by id, not only the tasks of the calling Session. +- A call from a delegated subagent returns `subagent_session` with the message `A delegated subagent cannot use scheduled tasks.` + +Existing reminders keep their timing and delivery. Recorded Sessions keep their earlier calls and results, and the Web transcript still renders them. + +This affects: + +- prompts, skills, and scripts that tell a model to call `schedule_update`, `schedule_delete`, or a timing selector; +- deployments that rely on each Session seeing only its own reminders; +- TypeScript code that imports `scheduleView` from the root entry, or `ScheduleView`, `ScheduleState`, `ScheduleDeliveryMode`, `ScheduleCreateValue`, `ScheduleListValue`, `ScheduleDeleteRequest`, `ScheduleDeleteValue`, `ScheduleTimingChange`, `ScheduleUpdateContent`, `ScheduleUpdateMiss`, `ScheduleUpdateRequest`, `ScheduleUpdateResult`, or `ScheduleUpdateValue` from the root or `/client` entry of `@deepseek-ai/dsh-schedule`. + +## Migration + +1. In prompts, skills, and scripts, replace `schedule_update` and `schedule_delete` with `schedule_edit`, replace each timing selector with an RRULE, and supply the required `target` on creation. For example, `daily: { time: "09:00:00", time_zone: "Asia/Shanghai" }` becomes `rrule: "DTSTART;TZID=Asia/Shanghai:20261013T090000\nRRULE:FREQ=DAILY"`; use `target: "this_session"` to keep delivery in the calling Session. +2. If the agents of a preset must not manage the tasks of other Sessions, remove the `@deepseek-ai/dsh-tool-schedule` row from that preset. +3. In TypeScript code, use `ScheduleCreateRequest`, `ScheduleTiming`, `SchedulePatch`, and `ScheduleEditRequest` for writes, and `ScheduleViewResult`, `ScheduleListResult`, and `ScheduleEditResult` for reads and edits. Call `ScheduleService.view`, paged `list`, and `edit` instead of `scheduleView`, `update`, and `delete`. `ScheduleDeleteResult`, `ScheduleDeleteChange`, and `ScheduleDeleteInactiveResult` remain exported from the root and `/client`; the old request/value types above do not. The [Schedule service README](../../../../packages/schedule/schedule/README.md) describes these APIs. +4. Custom compositions must provide both `tools` and `systemPrompt` before mounting this consumer; registration also waits for `schedule`. The `tool:schedule` section supplies the shared authorization instruction. A `complete: true` prompt override must include that instruction itself. +5. Open a Session under each changed preset and confirm that its tool list shows the four tool names. Delegate a task and confirm that a Schedule tool call from the child returns `subagent_session`; the child's tool list includes the four names, as [Configure subagent composition through presets](../../v0.2.1-alpha.1/subagent-preset-composition/guide.md) describes. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.zh.md new file mode 100644 index 0000000000..e5aaa35c1e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-agent-tools/guide.zh.md @@ -0,0 +1,37 @@ +--- +kind: upgrade-guide +description: "Schedule 的模型工具改为面向宿主全部任务的 `schedule_create`、`schedule_list`、`schedule_view` 与 `schedule_edit`,并移除 `schedule_update` 与 `schedule_delete`。" +--- + +# Schedule 工具按 RRULE 与目标管理宿主的全部任务 + +[English](guide.md) | 中文 + +## 变更 + +较早时,`@deepseek-ai/dsh-tool-schedule` 注册 `schedule_create`、`schedule_list`、`schedule_update` 与 `schedule_delete`。它们只管理调用方 Session 的提醒,`schedule_create` 接受一个时间选择参数:`after_seconds`、`at`、`every_seconds`、`daily`、`weekly` 或 `cron`。 + +现在本包注册 `schedule_create`、`schedule_list`、`schedule_view` 与 `schedule_edit`: + +- `schedule_create` 接受 `title`、`prompt`、`rrule`(一行 `DTSTART` 与一行 `RRULE`)和 `target`(`this_session`、`new_once` 或 `new`)。它不接受任何时间选择参数。 +- `schedule_list` 返回一页 `{ items, shown, total, limit, offset }`,包含活动、暂停与已结束的任务,而不是活动提醒的数组。 +- `schedule_view` 按 id 读取一个任务。 +- 带 `action: "update"` 的 `schedule_edit` 取代 `schedule_update`,并且还能改变 `rrule` 与 `target`,或暂停与恢复任务;`action: "delete"` 取代 `schedule_delete`。 +- 每个工具都按 id 读取、改变和删除宿主的任意任务,而不只是调用方 Session 的任务。 +- 被委派的子 agent 发起的调用返回 `subagent_session`,消息为 `A delegated subagent cannot use scheduled tasks.` + +已有提醒保留其时间规则与投递方式。已录制的 Session 保留较早的调用与结果,Web transcript 仍会渲染它们。 + +受影响的对象: + +- 让模型调用 `schedule_update`、`schedule_delete` 或某个时间选择参数的提示词、skill 与脚本; +- 依赖“每个 Session 只看到自己的提醒”的部署; +- 从 `@deepseek-ai/dsh-schedule` 根入口导入 `scheduleView`,或从根入口或 `/client` 入口导入 `ScheduleView`、`ScheduleState`、`ScheduleDeliveryMode`、`ScheduleCreateValue`、`ScheduleListValue`、`ScheduleDeleteRequest`、`ScheduleDeleteValue`、`ScheduleTimingChange`、`ScheduleUpdateContent`、`ScheduleUpdateMiss`、`ScheduleUpdateRequest`、`ScheduleUpdateResult` 或 `ScheduleUpdateValue` 的 TypeScript 代码。 + +## 迁移 + +1. 在提示词、skill 与脚本中,把 `schedule_update` 与 `schedule_delete` 替换为 `schedule_edit`,把每个时间选择参数替换为 RRULE,并在创建时提供必填的 `target`。例如,`daily: { time: "09:00:00", time_zone: "Asia/Shanghai" }` 变为 `rrule: "DTSTART;TZID=Asia/Shanghai:20261013T090000\nRRULE:FREQ=DAILY"`;使用 `target: "this_session"` 将投递保留在调用方 Session。 +2. 如果某个 preset 的 agent 不应管理其他 Session 的任务,从该 preset 中移除 `@deepseek-ai/dsh-tool-schedule` 这一行。 +3. 在 TypeScript 代码中,写入使用 `ScheduleCreateRequest`、`ScheduleTiming`、`SchedulePatch` 和 `ScheduleEditRequest`,读取与编辑结果使用 `ScheduleViewResult`、`ScheduleListResult` 和 `ScheduleEditResult`。调用 `ScheduleService.view`、分页的 `list` 和 `edit`,替换 `scheduleView`、`update` 和 `delete`。根入口与 `/client` 仍导出 `ScheduleDeleteResult`、`ScheduleDeleteChange` 和 `ScheduleDeleteInactiveResult`,但不再导出上述旧请求/结果值类型。[Schedule 服务 README](../../../../packages/schedule/schedule/README.zh.md) 描述了这些 API。 +4. 自定义组合须先提供 `tools` 和 `systemPrompt`,再挂载此消费者;注册还会等待 `schedule`。`tool:schedule` 区段提供共用授权指令。使用 `complete: true` 的提示词覆盖时,须自行保留该指令。 +5. 在每个改动过的 preset 下打开一个 Session,确认其工具列表显示这四个工具名。委派一个任务,确认子 agent 调用 Schedule 工具时返回 `subagent_session`;子 agent 的工具列表包含这四个工具名,详见[通过 preset 配置子 Agent 组装](../../v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md)。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.i18n.yaml new file mode 100644 index 0000000000..b5e9bcbddf --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md +/: + en: 69c0cf0c8201d784 + zh: a7831ef117a6f20c +/schedule-uses-one-host-wide-management-api: + en: 380dae2dc6802943 + zh: dfdca40926880a67 +/schedule-uses-one-host-wide-management-api/change: + en: 8fab9b2c62b64745 + zh: b7cff45264a852f8 +/schedule-uses-one-host-wide-management-api/migration: + en: 2f20ccf5e82d299e + zh: b01fa9cd6d297f5e diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md new file mode 100644 index 0000000000..949ff96c1d --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Schedule clients use one Host-wide management API and typed timing records; stored Host tasks keep the existing domain and layout." +--- + +# Schedule uses one Host-wide management API + +English | [中文](guide.zh.md) + +## Change + +Schedule management addresses every Host task by id. The native and Remote APIs share one service; the previous Session-bound `delete` and `update` methods are removed. Native creation takes a typed `timing`, and catalog results discriminate After, At, Every, Daily, Weekly, Cron, and RRULE with `kind`. + +The existing `schedule` domain writes version 2 and reads version 1 without startup writes, retaining its route, envelope, and layout. SQLite's physical schema stays at version 1. Back up the store before upgrading: the first successful v2 write stamps the unit v2, which a v1 binary refuses to open. Downgrade requires restoring that backup. Edits and delivery save current rows without a separate migration command. The plugin README owns the [stored schema, upgrade timing, and costs](../../../../packages/schedule/schedule/README.md#storage-format). + +## Migration + +1. Native callers use `create({ title, prompt, timing, target? }, actorSessionId?, signal?)` and `edit(request, actorSessionId?, signal?)`. Remote callers use `schedule/create` and `schedule/edit` with a `request` argument. Wrap a Cron selector as `{ kind: "cron", cron: { expression, time_zone } }`, or RRULE as `{ kind: "rrule", rrule }`. Model tool arguments continue to expose RRULE. +2. Replace Session-bound deletion with `edit({ id, action: "delete" })`; replace updates with `edit({ id, action: "update", patch, expectedUpdatedAt? })`. Timing edits use `patch.timing`. Supply the read revision, or `null` to compare an absent revision; handle `schedule_conflict` by rereading. +3. `list({ active?, limit?, offset? })` returns `{ items, shown, total, limit, offset }` across the Host. `catalog()` returns all tasks; `view({ id })`, `history({ id, limit, before? })`, and `run({ id })` need no owner Session. Read a reusable destination from `target`, and each receipt destination from `targetSessionId`. +4. Use the unprefixed types exported by the package root or `/client`, including `ScheduleRecord`, `ScheduleTiming`, and `ScheduleCatalogEntry`. Narrow by `kind` before reading timing fields. Handle `paused` and `ended` instead of `inactive`, and allow absent creation/change timestamps. The root helpers `scheduleView`, `decodeScheduleChange`, `foldScheduleEvents`, and `SCHEDULE_CHANGE_VERSION` are removed; historical event types remain frozen data declarations. The [tool upgrade guide](../schedule-agent-tools/guide.md) lists the removed types and their replacements. +5. Verify that Automation tasks shows existing Cron and calendar tasks and that a metadata edit preserves their timing and history. Historical Session-log reminders still require explicit recreation; they are outside this Host-task change. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.zh.md new file mode 100644 index 0000000000..48d502829b --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Schedule 客户端改用统一的宿主管理 API 和带类型时间记录;已有宿主任务保留现有领域和布局。" +--- + +# Schedule 使用统一的宿主管理 API + +[English](guide.md) | 中文 + +## 变更 + +Schedule 管理按 id 寻址宿主全部任务。原生与 Remote API 共用一个服务;移除先前按 Session 绑定的 `delete` 和 `update` 方法。原生创建接收带类型的 `timing`,目录结果通过 `kind` 区分 After、At、Every、Daily、Weekly、Cron 和 RRULE。 + +现有 `schedule` 领域写入版本 2,读取版本 1 时不进行启动写入,保留路由、封套和布局。SQLite 物理 schema 保持版本 1。升级前备份存储:首次成功的 v2 写入将单元标记为 v2,v1 程序会拒绝打开。降级需要恢复该备份。编辑和投递保存当前行,无需独立迁移命令。插件 README 拥有[存储 schema、升级时机与成本](../../../../packages/schedule/schedule/README.zh.md#storage-format)。 + +## 迁移 + +1. 原生调用方使用 `create({ title, prompt, timing, target? }, actorSessionId?, signal?)` 和 `edit(request, actorSessionId?, signal?)`。Remote 调用方使用带 `request` 参数的 `schedule/create` 和 `schedule/edit`。Cron 选择器包装为 `{ kind: "cron", cron: { expression, time_zone } }`,RRULE 包装为 `{ kind: "rrule", rrule }`。模型工具参数继续暴露 RRULE。 +2. 将按 Session 绑定的删除替换为 `edit({ id, action: "delete" })`;更新替换为 `edit({ id, action: "update", patch, expectedUpdatedAt? })`。时间编辑使用 `patch.timing`。提供读取的版本,或以 `null` 比较缺失版本;遇到 `schedule_conflict` 时重新读取。 +3. `list({ active?, limit?, offset? })` 返回宿主范围的 `{ items, shown, total, limit, offset }`。`catalog()` 返回全部任务;`view({ id })`、`history({ id, limit, before? })` 和 `run({ id })` 无需所有者 Session。从 `target` 读取可复用目的地,从 `targetSessionId` 读取每条回执目的地。 +4. 使用包根入口或 `/client` 导出的无前缀类型,包括 `ScheduleRecord`、`ScheduleTiming` 和 `ScheduleCatalogEntry`。读取时间字段前先按 `kind` 收窄。用 `paused` 和 `ended` 替代 `inactive`,并允许创建/变更时间戳缺失。根入口助手 `scheduleView`、`decodeScheduleChange`、`foldScheduleEvents` 和 `SCHEDULE_CHANGE_VERSION` 已移除;历史事件类型仍是冻结的数据声明。[工具升级指南](../schedule-agent-tools/guide.zh.md)列出已移除类型及其替代方式。 +5. 确认自动化任务显示已有 Cron 和日历任务,且元数据编辑保留其时间规则与历史。历史 Session 日志提醒仍需显式重建;它们不属于本次宿主任务变更。 diff --git a/docs/user/guide/schedule.i18n.yaml b/docs/user/guide/schedule.i18n.yaml index 8e4486a3d6..31fba2c702 100644 --- a/docs/user/guide/schedule.i18n.yaml +++ b/docs/user/guide/schedule.i18n.yaml @@ -6,26 +6,26 @@ en: c3cb91d1d53b7603 zh: 715ced3f1a2e9dd5 /schedule-reminders/summary: - en: bc85e4ac935f2fd5 - zh: c39e54e4beaa3f9a + en: a2a838b22f6e0b9a + zh: b3f3664ba85cb86c /schedule-reminders/table-of-contents: - en: b3b2a6e0ce02bdee - zh: 2ddb168de79fd19c + en: c1d163bf7d366e24 + zh: 34dccfbb0bf3701d /schedule-reminders/create-reminders: - en: f6d1a21af61a44fc - zh: a92f177c97880b95 -/schedule-reminders/inspect-and-delete-tasks: - en: b74bc63a1273680b - zh: b6d806e91c361b99 -/schedule-reminders/edit-an-active-task: - en: b3426f5dbc185958 - zh: ccf118e2415a5e77 + en: 762ecb7a7743cd2d + zh: 1b163ae679601767 +/schedule-reminders/inspect-run-and-delete-tasks: + en: 9f1e9d732597aa28 + zh: 66feec44adf24332 +/schedule-reminders/edit-a-task: + en: fe8c59251f0b4620 + zh: a422e44f758adae1 /schedule-reminders/timing-and-delivery-reference: - en: 6e5aa8ae5906df4f - zh: afdf670a31fae2bb + en: acb84b04d567d15c + zh: c658a81d8c6875f4 /schedule-reminders/further-exploration: - en: b7eb797281f028c0 - zh: 3754f9d19127a3c5 + en: 39e252476ff2a2c8 + zh: fa803f0eb67abb2d /schedule-reminders/dev-note: en: b75c8458928b72b9 zh: 003ba4e17b4b5269 diff --git a/docs/user/guide/schedule.md b/docs/user/guide/schedule.md index 7213c9fad5..bdee6c86b3 100644 --- a/docs/user/guide/schedule.md +++ b/docs/user/guide/schedule.md @@ -4,13 +4,13 @@ English | [中文](schedule.zh.md) ## Summary -Create reminders in a conversation, then inspect active and inactive tasks and edit an active task's name, instruction, and run time from the Automation tasks page. Daily reminders follow a saved local time and time zone; fixed-rate reminders follow elapsed intervals. Delivered one-shot tasks remain available until you explicitly delete them. +Ask the model in a conversation to create, list, view, edit, pause, resume, or delete reminders. Each reminder repeats by its rule and delivers its instruction to an existing conversation, to one new conversation, or to a new conversation at every occurrence. The Automation tasks page lists every reminder of the Host and can create, edit, run, pause, resume, and delete one. Delivered one-shot tasks remain available until you explicitly delete them. ## Table of Contents - [Create reminders](#create-reminders) -- [Inspect and delete tasks](#manage-tasks) -- [Edit an active task](#edit-timing) +- [Inspect, run, and delete tasks](#manage-tasks) +- [Edit a task](#edit-timing) - [Timing and delivery reference](#timing-and-delivery) - [Further Exploration](#further-exploration) @@ -19,59 +19,78 @@ Create reminders in a conversation, then inspect active and inactive tasks and e The shipped Web profile includes the Host Schedule service and the Automation tasks page. Configure a model provider before asking it to create reminders. -The `standard`, `cordis`, and `ptc` presets declare the four reminder tools and the clock context that gives the model the current time and the browser's zone, so those presets provide `schedule_create`, `schedule_list`, `schedule_update`, and `schedule_delete`; the `minimal` preset declares neither. A delegated subagent sees none of the four tools, because the presets' delegation rows deny them; a call that reaches one anyway is refused. +The `standard`, `cordis`, and `ptc` presets declare the four reminder tools and the clock context that gives the model the current time and the browser's zone, so those presets provide `schedule_create`, `schedule_list`, `schedule_view`, and `schedule_edit`; the `minimal` preset declares neither. A delegated subagent sees the four tools, but each tool refuses a call from a delegated subagent, so a subagent cannot read or change reminders. -Ask the model to create, list, edit, or delete reminders. It uses `schedule_create`, `schedule_list`, `schedule_update`, and `schedule_delete` (update changes one reminder in place and keeps its id and saved delivery records); the Automation tasks page's New action opens a New Session for a creation instead, with the request already written in its composer. Supported choices are a one-time delay in positive whole seconds, an absolute date and time, a fixed interval of at least one minute, a daily local time with an IANA time zone, a weekly local time with an IANA time zone and ISO weekdays from Monday 1 through Sunday 7, or a five-field cron expression with an explicit IANA time zone, stored in canonical form. +Ask the model to create, list, view, edit, pause, resume, or delete reminders. It uses `schedule_create` to create one, `schedule_list` to list the reminders of every conversation, `schedule_view` to read one, and `schedule_edit` to change, pause, resume, or delete one; an edit keeps the reminder id and saved delivery records. A reminder that the model creates has a name, an instruction, a start time in UTC or in an IANA time zone, and an RFC 5545 repeat rule, such as every weekday at 09:00 or only once. It delivers to this conversation, to one new conversation that its first delivery creates, or to a new conversation at every delivery; a new conversation uses the working directory and preset of this conversation. Each delivery of a reminder comes at least one minute after the scheduled time of the previous delivery, or after the previous Run now; a reminder that opens a new conversation at every delivery waits for the Host's minimum run interval instead, one minute by default. A late delivery, for example after a Host restart, does not delay the next one. -For example, ask: “Remind me every day at 23:00 in Asia/Shanghai to check the weather.” Open Automation tasks and select the created reminder. Check that its frequency shows a daily rule and the requested zone, not Once. A one-time reminder does not become recurring after delivery. +A conversation that a delivery creates joins the Workspace registered at its working directory and takes the reminder name as its title. For a reminder that opens a new conversation at every delivery, the title also states the launch time in the zone of the reminder's rule, for example `Weekday digest · 2026-10-12 09:00`. + +For example, ask: “Remind me every day at 23:00 in Asia/Shanghai to check the weather.” Below the reply, a card shows the created reminder's name and frequency; Open shows its details in the right sidebar. Check that the frequency repeats every day at 23:00, not Once. A one-time reminder does not become recurring after delivery. After the reminder is deleted, the card shows Deleted and no longer opens it. + +To create a reminder without the model, open Automation tasks from the sidebar, open Choose a creation method beside New, and choose Create manually; when no task exists, New automation task opens the same editor. This editor also opens existing tasks and asks for an Automation task name, an Automation task instruction, Run in, Linked workspace, and Run time. It starts with Once at one hour from now in the browser's time zone and with Create a conversation and reuse it. Run in offers Create a conversation and reuse it, which creates one conversation at the first run and keeps using it, and New conversation for every run, which creates a separate conversation at each run and shows the Host's minimum run interval. Linked workspace lists each registered Workspace with its directory and selects the Workspace whose directory the new conversation uses; it starts at Default workspace, or at the first Workspace when the default Workspace is not registered. When no Workspace exists, Linked workspace shows Ungrouped and the Host project directory is used. The new conversation uses the default preset. Create creates the task and selects it in the list, and Discard closes the editor without creating one. If the Host refuses the task, the editor keeps your input and states the problem, for example that the date and time must be in the future. + +New, and Create in a conversation in the same menu, open a new conversation in the current or most recent Workspace; ask the model there to create the task. -## Inspect and delete tasks +## Inspect, run, and delete tasks -Open Automation tasks from the sidebar to view reminders across Sessions without activating their conversations. Search by the stored task name, the instruction, or the task's internal Session id, and filter by the single All, Enabled, or Inactive status row. An idle, unarchived Session row whose Session has at least one active task shows a clock mark; an archived row keeps that cell blank, with its live status on the hover card only. A long hover on a Session row with active tasks lists up to two of those tasks with their frequency and their next run as a device-zone time with its relative duration. The open Session's header shows an icon-only reminder clock while active reminders exist: it opens the sole task's details directly, or a list of the Session's reminders otherwise. +Ask the model to list reminders to see the reminders of every conversation, active ones first, or to show, pause, resume, or delete one reminder by its id. -Select a task to open Rules, then choose Records to load the newest 20 saved records. Each saved record reads as one compact row: a clock glyph, the occurrence time in the task's saved zone (the browser's zone for a one-shot or interval task), and the saved instruction when one was stored. Records without a saved instruction never show the current instruction in its place. Load older records adds the next page. Records follow newest-first saved order even if the clock moves backward; they do not describe model execution results. The original Session entry sits in the detail tab strip, so it stays visible while the Rules view scrolls. Unmodified Left/Right arrows and Home/End switch the focused tabs; Alt, Ctrl, Meta, and Shift combinations are not intercepted. Refreshing the task preserves the selected tab. +Open Automation tasks from the sidebar to view reminders across Sessions without activating their conversations. Search by the task name, the instruction, or the id of the task's conversation, and filter by Task status: All, Enabled, Paused, or Ended. Rows are ordered by their scheduled time, earliest first. Each row shows the task name and one summary line: the status of a paused or ended task, the frequency, and, for an enabled task, Next scheduled time with its local and relative time. -An empty record view means a successful query returned no saved records. Loading, request failure, a missing task, and an invalid older-record cursor have separate messages. Use Retry delivery records after a failed request or missing-task response; use Refresh delivery records after an invalid cursor to reload the newest page. Previously loaded records may remain visible with a warning while a request fails. A new latest delivery refreshes the newest page. Late responses for a task or view you have left do not replace the current view. +A Session's tasks are the tasks that deliver to it, including the latest run of a task that creates a new conversation for every run, and the tasks that its Agent created or edited. An idle, unarchived Session row whose Session has at least one active task shows a clock mark; an archived row keeps that cell blank, with its live status on the hover card only. A long hover on a Session row with active tasks lists up to two of those tasks with their frequency and their next run as a device-zone time with its relative duration. The open Session's header shows an icon-only reminder clock while the Session has active tasks: it opens the sole task's details in the right sidebar, or otherwise a list of those tasks in which each row opens the task's details or deletes the task. -For tasks without saved history, only an existing latest receipt can be shown until new deliveries add records; later deliveries do not recover the missing history or clear its notice. Unsaved earlier records and instruction snapshots cannot be recovered, and the current instruction is not substituted for a missing saved instruction. The earlier-history notice appears only when the Host marks earlier records unavailable; new tasks with no deliveries show the empty state without that notice. +Select a task to open its details. Rules shows the task name, Next run with its local and relative time or the status of a paused or ended task, the instruction, Repeat, and Run in, which shows Current linked conversation for a task that delivers to an existing conversation. The bottom of the details shows Linked session, or Latest run conversation for a task that creates a new conversation for every run. Its button opens that conversation when the Session is available and unarchived, and is disabled otherwise; before the first run creates the conversation, the entry shows Pending creation. For a task that delivers to an existing conversation, Rules states when that conversation is archived, unavailable, or still loading. The task details and deletion remain available even when a conversation cannot open. Browsing tasks does not unarchive Sessions. -Active tasks participate in scheduling. Inactive tasks do not schedule another delivery. A one-time task becomes inactive after its reminder is durably written to the conversation inbox; choose All tasks or Inactive to find it. The conversation-header catalog and model `schedule_list` show only active reminders, so disappearance from those views does not mean the retained task was deleted. +Choose Records to load the newest 20 saved records. Each record shows the occurrence time in the zone of the task's rule (the browser's zone when the rule names none), a button that opens the conversation that received the delivery when that conversation is available, and the saved instruction; Expand shows a long instruction in full. Records without a saved instruction never show the current instruction in its place. Load more adds the next page. Records follow newest-first saved order even if the clock moves backward; they do not describe model execution results. Left/Right arrows and Home/End switch the focused tabs. -The Linked session entry in the detail tab strip opens the original conversation when its metadata is ready and the Session is available and unarchived. Otherwise the entry is disabled with a reason. The task details and deletion action remain available even when its original Session cannot open. Browsing tasks does not unarchive Sessions. +An empty record view means a successful query returned no saved records. Loading, request failure, a missing task, and an invalid older-record cursor have separate messages. Use Retry after a failed request or missing-task response; use Refresh after an invalid cursor to reload the newest page. Previously loaded records may remain visible with a warning while a request fails. A new latest delivery refreshes the newest page. Late responses for a task or view you have left do not replace the current view. -Choose Delete task and confirm to stop future delivery and remove the task from the list, including for an inactive task. Deletion removes the task together with its saved delivery records, so the task's saved history is gone. Confirming the deletion closes the panel or tab that asked for it and reports the outcome in one app-wide notice — deleted, or a failure that leaves the task in place to retry; it does not remove the original conversation or retract a message already queued there. The row stays visible until a successful query confirms the remaining tasks. If a query fails, Retry reloads the catalog; the error is not an empty successful result. +When retention removed earlier records, the last page states that earlier delivery records have been cleared, and Retention rules shows how many records and how many days each task keeps. An older task without saved history shows only its latest delivery, without an instruction, until new deliveries add records. Unsaved earlier records and instruction snapshots cannot be recovered. + +Active tasks participate in scheduling. Paused and ended tasks do not schedule another delivery. A one-time task ends after its reminder is durably written to the conversation inbox, and a repeating task ends after the last occurrence of its rule; choose All or Ended in Task status to find an ended task. The Session header clock, the row mark, and the hover card show only active tasks, so disappearance from those views does not mean that the task was deleted. + +Pause in the details stops the future deliveries of an active task, and Resume restarts a paused task. Run now, in the Automation task actions menu, asks the Host to deliver the instruction once now and keeps the next scheduled run, also for a paused or ended task. While a delivery of a task that delivers to an existing conversation or to one new conversation is queued or running, the fields, Save changes, Pause, Resume, Run now, and Delete task are disabled, and the details state that the task is queued or running and that you manage it in its conversation, which the button at the bottom of the details opens. A task that creates a new conversation for every run is not disabled this way; its runs continue beside one another. After a delivery, Run now stays disabled until the task's minimum delivery interval ends; while only the interval holds it, hold the pointer on Run now or move the keyboard to it to see when it becomes available. If the Host refuses a run for one of these reasons, the details state that the task is queued, running, or was just delivered. Run now is also disabled while the conversation that the task delivers to is archived. If you stop the conversation while the task's instruction waits there, the instruction stays queued until your next message, the task's next scheduled run, or Run now starts it. + +Choose Delete task from the Automation task actions menu and confirm to stop future delivery and remove the task from the list, including for a paused or ended task. Deletion removes the task together with its saved delivery records, so the task's saved history is gone. Confirming the deletion reports the outcome in one app-wide notice — deleted, which also closes the details, or a failure that leaves the task in place to retry; it does not remove the conversations or retract a message already queued there. The row stays visible until a successful query confirms the remaining tasks. If a query fails, Retry reloads the catalog; the error is not an empty successful result. -## Edit an active task +## Edit a task -In Automation tasks, select an active task and open Rules to edit its name, instruction, and run time. Inactive tasks are read-only, and edits stay in a local draft until you choose Save changes. Editing keeps the task id, original conversation, latest delivery receipt, and all saved delivery records. +Ask the model to change a reminder's name, instruction, repeat rule, or delivery target, or to pause or resume it; the change keeps the reminder id and saved delivery records. -- Daily and Weekly: edit Time and Time zone; a weekly rule also toggles Weekday. A clock row shows whole seconds, an untouched row keeps a stored millisecond value for its submit, and the stored IANA zone is kept. A changed rule selects its first future occurrence using the DST rules below. -- Every: choose Every N hours, Every N minutes, or Every N seconds and enter the quantity in the unit the row states; the smallest accepted interval is 1 hour, 1 minute, or 60 seconds for that unit, and the submitted interval is whole seconds. A changed interval starts from the Host's accepted-save time, with the first target one new interval later. Time zones do not affect this elapsed interval. -- One-shot After/At: edit separate Date and Time rows and Time zone. The initial zone is the record's stored zone, or this device's zone when the record stores none, and the seeded clock names the same stored instant; a one-shot rule that stored no zone shows one hint stating that the selected zone interprets the entered date and time. Changing the zone keeps those clock values and changes the instant. A changed target saves as At with the same task id. The zone is not retained as recurrence metadata. +In Automation tasks, select a task to change its Automation task name, Automation task instruction, Run in, Linked workspace, and Run time, including for a paused or ended task. Edits stay in a local draft until you choose Save changes. Editing keeps the task id, latest delivery receipt, and all saved delivery records. A changed rule makes an ended task active again and keeps a paused task paused. For a task that delivers to an existing conversation, Run in shows Current linked conversation; choosing another option makes later runs create their conversations and sets Linked workspace to its starting value, as in Create manually. A task keeps its stored preset while its Workspace stays the same; a changed Workspace uses the default preset. -The rows change only a local draft. Save changes submits the name, instruction, and the complete rule in one update, and a save bar appears while the draft differs from the stored task; Cancel restores the stored values. The Repeat menu offers Weekly, Monday to Friday, Every day, Every N hours, Every N minutes, Every N seconds, Once, and Custom (cron), and the Host accepts any of them, so a one-shot After may save as At. An equivalent normalized rule performs no write or target reset: the same Every interval does not restart its timing, and an unchanged one-shot target preserves After or At. The rows are disabled while a save is in flight. Leaving the card does not roll back a Host write already begun. +- Once: Date opens a month calendar, Time opens Hour, Minute, and Second columns, and Time zone interprets them. The task runs once and then ends. +- Every N minutes and Every N hours: Interval sets the number of minutes or hours, at least 1. The interval counts from the minute at which you save the task. +- Every day: Interval sets the number of days, and Time opens Hour and Minute columns. +- Weekly and Monday to Friday: Interval sets the number of weeks, Weekday selects the days, and Time opens Hour, Minute, and Second columns. Monday to Friday selects those five days at once. +- Monthly: Interval sets the number of months, Day of the month selects a date from 1 through 31, and Time opens Hour, Minute, and Second columns. A month without the selected date runs on its last day. +- Custom: Custom rule holds the rule text. A rule that the other choices cannot reproduce opens in Custom. An existing task without editable rule text shows its original frequency and keeps that timing until you save a replacement. -A catalog refresh keeps the fields you have edited and takes every other field from the refreshed record, so a concurrent change to another field survives an unsaved edit. Invalid input is reported and blocks Save. If delivery or another edit changed the task, a conflict prevents overwriting that change; retry to edit the latest rule. An accepted update refreshes the catalog. A rejected or unconfirmed update is distinct from a catalog-loading error: use Retry to reload the catalog, not to repeat an acknowledged update. If the update itself cannot be confirmed, check the task before retrying. Late responses after closing details or switching tasks do not replace the current view. +Time zone lists recently selected zones first, marks the system zone, and searches by UTC offset, IANA ID, or city. It appears for guided choices and Custom expressions that use a separate zone; otherwise the Custom rule text supplies its zone. + +The fields change only a local draft. If the task targets an existing conversation, Current linked session remains available so you can undo a destination change without discarding other edits. While you edit, the bottom of the details shows Unsaved changes with Discard and Save changes; Save changes sends only the changed fields in one update, and Discard restores the stored values. A save sends a new rule only when the timing changed. Save changes stays disabled until a meaningful change has valid fields and timing. Invalid Custom text keeps the draft and shows a correction message; the Host also validates the rule on save. Pause, resume, Run now, and deletion wait until you save or discard unsaved changes. The fields are disabled while a save is in flight. Leaving the details does not roll back a Host write already begun. + +Switching tasks or leaving the page keeps unsaved drafts. A catalog refresh updates a pristine form; an edited form keeps all fields and its original version. If delivery or another edit changes the task, the details state that the task changed elsewhere and disable Save changes when the newer version arrives. The Host also checks the version on save. Review with my edits keeps the title, prompt, timing, and target groups you changed and loads the latest values for the other groups. Review the whole form before saving; this action alone does not save. If the same group changed elsewhere, your edits take precedence in the form. Discard replaces the whole draft with the latest stored values. If another save fails, the draft stays and the details ask you to try again; check the task before retrying an update whose outcome is unknown. An accepted update refreshes the catalog. Late responses after closing details or switching tasks do not replace the current view. ## Timing and delivery reference -Reminders remain stored when their Session is not open. While the Host runs, it restores the original Session when a reminder becomes due and queues a follow-up without interrupting current work. Restarting checks stored tasks and sends an overdue one-shot or only the latest missed occurrence of each recurring task. Closing the Host stops scheduling until it starts again. Due recurring tasks for the same Session can share one message. +Reminders remain stored when their Session is not open. While the Host runs, it restores or creates the target Session when a reminder becomes due and queues a follow-up without interrupting current work. Restarting checks stored tasks and sends an overdue one-shot or only the latest missed occurrence of each recurring task. Closing the Host stops scheduling until it starts again. Due recurring tasks for the same Session can share one message. -Fixed-rate reminders stay aligned to creation until their interval changes; a changed interval aligns to the accepted-save time. Daily reminders instead follow the saved local time and IANA zone. A daily local time or date that does not exist is skipped; an overlapping time uses the earlier instant once that day. An absolute-time request rejects a nonexistent local time and chooses the earlier instant during an overlap. The browser supplies its zone for interpreting natural-language requests; naming a zone explicitly avoids ambiguity. Task details keep a saved wall-clock rule's zone in its frequency text and show every next target as a device-zone clock; a one-shot task stores only the UTC instant, so its timestamps use the browser's zone. +A repeat rule in an IANA zone follows local wall time: it skips a local time that does not exist and uses the earlier instant of a repeated local time. Existing tasks keep their timing until you save a new rule: a fixed-rate reminder stays aligned to its creation time, and a daily, weekly, or cron reminder follows its saved local times in its IANA zone. The browser supplies its zone for interpreting natural-language requests; naming a zone explicitly avoids ambiguity. The Automation tasks page shows every next run as a browser-zone clock, and the frequency text names a rule's zone when it differs from the browser's zone; a rule that names no zone uses the browser's zone. -Saved delivery records confirm messages persisted in the conversation inbox, not that the model completed the requested work. Failed inbox persistence or task writes add no saved record. A crash or task-write failure after inbox persistence can leave a delivered message unrecorded and repeat a delivery; exactly-once delivery is not guaranteed. This is not an execution history or an external notification channel. +Saved delivery records confirm messages persisted in the conversation inbox, not that the model completed the requested work. Failed inbox persistence or task writes add no saved record. A crash or task-write failure after inbox persistence can leave a delivered message unrecorded and repeat a delivery; exactly-once delivery is not guaranteed. Closing the Host discards each message that still waits in a conversation inbox: its saved record remains, the model never receives that message, and the Host does not send it again. This is not an execution history or an external notification channel. Saved records are pruned when an acknowledgment is appended: the Host keeps the records whose acknowledgment time falls inside the configured `deliveryHistoryDays` window, measured back from the appended receipt's `deliveredAt`, and at most the newest `deliveryHistoryRecords` records. The latest receipt always survives, and a pruned window marks earlier records unavailable. The Host keeps the retained history in memory and rewrites the full task row for each acknowledgment. Pagination limits returned record count, not the retained history or instruction bytes. -Pause and a new Session for each run are not supported. Name, instruction, and run-time editing is available to the model through `schedule_update`, which changes the reminder in place and keeps its id and saved delivery records, and to the Automation tasks page against the selected task's binding; neither is a cross-Session relay workflow. Reminders recorded only in an older Session log are not scheduled automatically; recreate the ones you still need. Previously deleted task records are not reconstructed. +Name, instruction, timing, and target editing, pausing, and resuming are available to the model through `schedule_edit` and to the Automation tasks page for every reminder; neither is a cross-Session relay workflow. A change adds a notice to the next model request of each involved conversation whose Agent is loaded, except the conversation that made the change. Reminders recorded only in an older Session log are not scheduled automatically; recreate the ones you still need. Previously deleted task records are not reconstructed. ## Further Exploration -- [Schedule reference](../../../packages/schedule/schedule/README.md) documents exact timing selectors, persistence, and delivery limits. +- [Schedule reference](../../../packages/schedule/schedule/README.md) documents task fields, delivery targets, recurrence rules, persistence, and delivery limits. - [Automation tasks page reference](../../../packages/client/ui-schedule/README.md) describes the global page and conversation-header catalog. ## Dev Note diff --git a/docs/user/guide/schedule.zh.md b/docs/user/guide/schedule.zh.md index 73edfd2673..ebf7b24946 100644 --- a/docs/user/guide/schedule.zh.md +++ b/docs/user/guide/schedule.zh.md @@ -4,13 +4,13 @@ ## 概述 -在对话中创建提醒,再从自动化任务页面查看活动和未运行任务,并修改活动任务的名称、指令和运行时间。每日提醒遵循保存的本地时间与时区;固定速率提醒遵循经过的时间间隔。已投递的一次性任务会保留到显式删除为止。 +在对话中请模型创建、列出、查看、修改、暂停、恢复或删除提醒。每条提醒按其规则重复,并把指令投递到一个现有对话、一个新对话,或在每个发生时点投递到一个新对话。自动化任务页面列出宿主的所有提醒,并可创建、修改、运行、暂停、恢复和删除提醒。已投递的一次性任务会保留到显式删除为止。 ## 目录 - [创建提醒](#create-reminders) -- [查看和删除任务](#manage-tasks) -- [修改活动任务](#edit-timing) +- [查看、运行和删除任务](#manage-tasks) +- [修改任务](#edit-timing) - [时间与投递参考](#timing-and-delivery) - [延伸阅读](#further-exploration) @@ -19,59 +19,78 @@ 发布的 Web profile 自带宿主 Schedule 服务与自动化任务页面。在请求模型创建提醒前,先配置模型 provider。 -`standard`、`cordis` 和 `ptc` preset 声明四个提醒工具与把当前时间和浏览器时区交给模型的时钟上下文,因此这些 preset 提供 `schedule_create`、`schedule_list`、`schedule_update` 和 `schedule_delete`;`minimal` preset 两者都不声明。被委派的子 agent 看不到这四个工具,因为三个 preset 的委派行已将其 deny;即使某个调用仍能到达工具,也会被拒绝。 +`standard`、`cordis` 和 `ptc` preset 声明四个提醒工具与把当前时间和浏览器时区交给模型的时钟上下文,因此这些 preset 提供 `schedule_create`、`schedule_list`、`schedule_view` 和 `schedule_edit`;`minimal` preset 两者都不声明。被委派的 subagent 能看到这四个工具,但每个工具都会拒绝来自被委派 subagent 的调用,因此 subagent 无法读取或修改提醒。 -向模型提出创建、列出、修改或删除提醒的请求。模型使用 `schedule_create`、`schedule_list`、`schedule_update` 和 `schedule_delete`(更新原地修改一条提醒,保留其 id 与已保存的投递记录);「自动化任务」页面的「新建」操作则为创建打开一个新会话,其 composer 已写好该请求。支持正整数秒的一次性延迟、绝对日期时间、至少一分钟的固定间隔、带 IANA 时区的每日本地时间、带 IANA 时区和 ISO 星期(周一 1 至周日 7)的每周本地时间,以及带显式 IANA 时区的五字段 cron 表达式(表达式以规范化形式保存)。 +向模型提出创建、列出、查看、修改、暂停、恢复或删除提醒的请求。模型用 `schedule_create` 创建提醒,用 `schedule_list` 列出所有对话的提醒,用 `schedule_view` 读取一条提醒,用 `schedule_edit` 修改、暂停、恢复或删除一条提醒;修改保留提醒 id 与已保存的投递记录。模型创建的提醒有名称、指令、UTC 或某个 IANA 时区下的开始时间,以及一条 RFC 5545 重复规则,例如每个工作日 09:00 或仅一次。它投递到当前对话、首次投递时创建的一个新对话,或在每次投递时投递到一个新对话;新对话使用当前对话的工作目录与 preset。同一提醒的每次投递都在上一次投递的计划时间或上一次“立即执行”之后至少一分钟;每次投递都打开新对话的提醒改为等待宿主的最小运行间隔,默认为一分钟。延迟的投递(例如宿主重启之后)不会推迟下一次投递。 -例如,请求:“每天 Asia/Shanghai 时区 23:00 提醒我查看天气。”打开自动化任务页面并选择刚创建的提醒,检查频率显示的是每日规则和所需时区,而非仅一次。一次性提醒不会在投递后变成重复任务。 +投递创建的对话加入在其工作目录注册的 Workspace,并以提醒名称作为标题。对于每次投递都打开新对话的提醒,标题还写出该提醒规则所用时区下的启动时间,例如 `Weekday digest · 2026-10-12 09:00`。 + +例如,请求:“每天 Asia/Shanghai 时区 23:00 提醒我查看天气。”回复下方的卡片显示刚创建的提醒的名称和频率;“打开”在右侧栏显示其详情。检查频率是每天 23:00 重复,而非“仅一次”。一次性提醒不会在投递后变成重复任务。提醒删除后,卡片显示“已删除”,且不再打开该提醒。 + +不经模型创建提醒时,从侧栏打开自动化任务页面,打开“新建”旁的“选择创建方式”,再选择“手动创建”;尚无任务时,“新建自动化任务”打开同一编辑页。已有任务也使用此页面,填写“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”。初始运行时间为“仅一次”,时间为浏览器时区下的一小时后,初始执行位置为“新建对话并复用”。“执行位置”提供“新建对话并复用”和“每次新建对话”:前者在首次运行时创建一个对话并在之后沿用,后者在每次运行时创建独立对话,并显示宿主的最小运行间隔。“关联工作区”列出每个已注册的 Workspace 及其目录,并选择新对话使用其目录的 Workspace;初始值为“默认工作区”,未注册默认 Workspace 时为第一个 Workspace。尚无任何 Workspace 时,“关联工作区”显示“未分组”,并使用宿主项目目录。新对话使用默认 preset。“创建”创建该任务并在列表中选中它,“放弃”关闭编辑页而不创建任务。若宿主拒绝该任务,编辑页保留你的输入并说明问题,例如日期和时间必须在未来。 + +“新建”以及同一菜单中的“在对话中创建”会在当前或最近使用的 Workspace 中打开一个新对话;在其中请模型创建该任务。 -## 查看和删除任务 +## 查看、运行和删除任务 -从侧栏打开自动化任务页面,可跨 Session 查看提醒,而不激活相应对话。按任务已存储的名称、指令或任务所属的内部 Session id 搜索,并用唯一的“全部/已开启/未运行”状态筛选行过滤。Session 行在其 Session 有至少一个活动任务、自身空闲且未归档时显示时钟标识;归档行该格留空,其实时状态只在悬浮卡片中显示。悬停任一带活动任务的 Session 行时,最多列出其中两个任务及其频率,以及设备时区下的下次运行时间与相对时长。已打开 Session 的顶部在有活动提醒时显示仅图标时钟入口:只有一个任务时直接打开其详情,否则列出该 Session 的提醒。 +请模型列出提醒,可查看所有对话的提醒,活动提醒在前;也可请模型按 id 显示、暂停、恢复或删除一条提醒。 -选择任务打开“规则”,再选择“任务运行记录”加载最新的 20 条已保存记录。每条已保存记录为一行紧凑信息:时钟图标、任务保存时区下的发生时间(一次性或间隔任务则为浏览器时区),以及保存过的指令。没有保存指令的记录不会用当前指令顶替。“加载更早的记录”增加下一页。记录按保存顺序从新到旧排列,即使时钟回拨也不改变顺序;它们不描述模型执行结果。原会话入口位于详情页签条内,因此在“规则”视图滚动时都保持可见。不带修饰键的左右方向键和 Home/End 可切换已聚焦的页签;不会拦截与 Alt、Ctrl、Meta 或 Shift 的组合。刷新任务会保留当前页签。 +从侧栏打开自动化任务页面,可跨 Session 查看提醒,而不激活相应对话。按任务名称、指令或任务所属对话的 id 搜索,并用“任务状态”(“全部”“已开启”“已暂停”或“已结束”)过滤。各行按计划时间排列,最早的在前。每行显示任务名称和一行摘要:已暂停或已结束任务的状态、频率,以及已开启任务的“下次计划时间”与其本地时间和相对时间。 -记录空态表示查询成功且没有返回已保存记录。加载中、请求失败、任务不存在和较早记录游标无效分别显示不同提示。请求失败或返回任务不存在时,使用“重试加载发送记录”;游标无效时,使用“刷新发送记录”重新加载最新一页。请求失败时,此前加载的记录可能仍会显示,并附有警告。新的最近一次投递会刷新最新一页。离开任务或视图后才到达的响应不会替换当前视图。 +一个 Session 的任务包括投递到该 Session 的任务(对于每次运行都新建对话的任务,以其最近一次运行为准),以及该 Session 的 Agent(智能体)创建或修改过的任务。空闲、未归档且至少有一个活动任务的 Session 行显示时钟标识;归档行该格留空,其实时状态只在悬浮卡片中显示。长时间悬停在带活动任务的 Session 行上时,最多列出其中两个任务及其频率,以及设备时区下的下次运行时间与相对时长。已打开 Session 的顶部在该 Session 有活动任务时显示仅图标的提醒时钟:只有一个任务时,它在右侧栏打开该任务的详情;否则列出这些任务,每行可打开任务详情或删除任务。 -没有已保存历史的任务只能显示已有的最近一次回执,直到新投递增加记录;后续投递不会恢复缺失历史或清除相应提示。未保存的更早记录和指令快照无法恢复,不会用当前指令代替缺失的已保存指令。仅当宿主标记更早记录不可用时,才显示更早历史提示;尚未投递的新任务显示空态,不显示该提示。 +选择任务打开其详情。“规则”显示任务名称、“下次运行”及其本地时间和相对时间(已暂停或已结束的任务显示其状态)、指令、“重复”和“执行位置”;投递到现有对话的任务,“执行位置”显示“当前关联对话”。详情底部显示“关联会话”;对于每次运行都新建对话的任务,显示“最近运行对话”。其按钮在 Session 可用且未归档时打开该对话,否则禁用;首次运行创建对话之前,该条目显示“待创建”。对于投递到现有对话的任务,“规则”会说明该对话已归档、不可用或仍在加载。即使对话无法打开,任务详情与删除操作仍然可用。浏览任务不会取消 Session 归档。 -活动任务参与调度;未运行任务不会再次安排投递。一次性任务在提醒持久写入对话收件箱后变为未运行;选择所有任务或未运行即可找到它。对话顶部目录和模型 `schedule_list` 仅显示活动提醒,因此从这些视图消失并不表示保留的任务已被删除。 +选择“任务运行记录”加载最新的 20 条已保存记录。每条记录显示任务规则所用时区下的发生时间(规则未指定时区时为浏览器时区)、一个在接收该投递的对话可用时打开它的按钮,以及保存过的指令;“展开”完整显示较长的指令。没有保存指令的记录不会用当前指令顶替。“加载更多”增加下一页。记录按保存顺序从新到旧排列,即使时钟回拨也不改变顺序;它们不描述模型执行结果。左右方向键和 Home/End 可切换已聚焦的页签。 -详情页签条内的关联会话入口在元数据就绪、Session 可用且未归档时打开原对话;否则入口禁用并显示原因。即使原 Session 无法打开,任务详情与删除操作仍然可用。浏览任务不会取消 Session 归档。 +记录空态表示查询成功且没有返回已保存记录。加载中、请求失败、任务不存在和较早记录游标无效分别显示不同提示。请求失败或返回任务不存在时,使用“重试”;游标无效时,使用“刷新”重新加载最新一页。请求失败时,此前加载的记录可能仍会显示,并附有警告。新的最近一次投递会刷新最新一页。离开任务或视图后才到达的响应不会替换当前视图。 -选择删除任务并确认,可停止未来投递并将该任务从列表中移除,包括未运行任务。删除会移除该任务及其已保存的发送记录,因此该任务的已保存历史随之消失。确认删除会关闭发起删除的面板或页签,并在同一个应用级提示里报告结果——已删除,或失败(失败时任务保留、可重试);删除不会删除原对话,也不会撤回已进入队列的消息。该行会保留到成功查询确认剩余任务为止。查询失败时可通过重试重新加载目录;错误不会被视为查询成功的空结果。 +保留上限移除了更早的记录时,最后一页提示“更早的运行记录已清理”,“保留规则”说明每个任务保留的记录条数和天数。没有已保存历史的旧任务只显示其最近一次投递,且不含指令,直到新投递增加记录。未保存的更早记录和指令快照无法恢复。 + +活动任务参与调度;已暂停和已结束的任务不会再次安排投递。一次性任务在提醒持久写入对话收件箱后结束,重复任务在其规则的最后一个发生时点后结束;在“任务状态”中选择“全部”或“已结束”即可找到已结束的任务。Session 顶部的提醒时钟、Session 行的时钟标识和悬浮卡片只显示活动任务,因此从这些视图消失并不表示任务已被删除。 + +详情中的“暂停任务”停止活动任务之后的投递,“恢复任务”重新启动已暂停的任务。“自动化任务操作”菜单中的“立即执行”请宿主现在投递一次指令,并保留下次计划运行;已暂停或已结束的任务也可以这样运行。投递到现有对话或一个新对话的任务的一次投递已排队或正在运行时,字段、“保存修改”“暂停任务”“恢复任务”“立即执行”和“删除任务”均禁用,详情说明此任务已排队或执行中,请在会话中管理任务;详情底部的按钮打开该会话。每次运行都创建新对话的任务不会这样禁用;它的各次运行并行继续。一次投递之后,“立即执行”保持禁用,直到该任务的最小投递间隔结束;仅因间隔禁用时,将指针停在“立即执行”上或用键盘移到该项,即可查看它恢复可用的时间。若宿主因上述原因之一拒绝运行,详情会说明该任务已排队、执行中或刚执行过。任务投递到的对话已归档时,“立即执行”同样禁用。若在任务指令仍在对话中等待时停止该对话,指令会保持排队,直到你的下一条消息、该任务的下一次计划运行或“立即执行”使其开始。 + +从“自动化任务操作”菜单选择“删除任务”并确认,可停止未来投递并将该任务从列表中移除,包括已暂停或已结束的任务。删除会移除该任务及其已保存的发送记录,因此该任务的已保存历史随之消失。确认删除会在同一个应用级提示里报告结果——已删除(同时关闭详情),或失败(失败时任务保留、可重试);删除不会删除相关对话,也不会撤回已进入其队列的消息。该行会保留到成功查询确认剩余任务为止。查询失败时,“重试”重新加载目录;错误不会被视为查询成功的空结果。 -## 修改活动任务 +## 修改任务 -在自动化任务页面选择活动任务,打开“规则”,即可修改其名称、指令和运行时间。未运行任务保持只读,修改先保存在本地草稿中,直到选择“保存更改”。编辑保留任务 id、原对话、最近一次投递回执以及全部已保存的发送记录。 +请模型修改提醒的名称、指令、重复规则或投递目标,或暂停、恢复提醒;修改保留提醒 id 与已保存的投递记录。 -- Daily 和 Weekly:修改“时间”和“时区”;每周规则还可切换“星期”。时钟行显示整秒,未改动的行在提交时保留已存储的毫秒值,已存储的 IANA 时区保持不变。规则改变后,按下文的夏令时规则选择首个未来时点。 -- Every:选择“每 N 小时”“每 N 分钟”或“每 N 秒”,并按行内标出的单位填写数量;该单位下的最小间隔为 1 小时、1 分钟或 60 秒,提交的间隔为整秒。新间隔从宿主接受保存的时间起算,首个目标为一个新间隔之后。时区不影响这个经过时间间隔。 -- 一次性 After/At:分别修改“日期”“时间”两行以及“时区”。初始时区取记录已存储的时区;记录未保存时区时取本设备时区,初始钟表值在该时区下仍表示同一已存储瞬时。未保存时区的一次性规则会显示一条提示,说明输入的日期时间按所选时区解释。更改时区会保留这些钟表值并改变时点。目标改变后以相同任务 id 保存为 At,不将时区保留为重复规则元数据。 +在自动化任务页面选择任务,即可直接修改其“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”,包括已暂停或已结束的任务。修改先保存在本地草稿中,直到选择“保存修改”。编辑保留任务 id、最近一次投递回执以及全部已保存的发送记录。规则改变后,已结束的任务重新变为活动,已暂停的任务保持暂停。对于投递到现有对话的任务,“执行位置”显示“当前关联对话”;选择其他选项后,之后的运行会创建各自的对话,“关联工作区”也设为其初始值,与“手动创建”相同。Workspace 保持不变时,任务保留已存储的 preset;改换 Workspace 后使用默认 preset。 -各行只修改本地草稿。“保存更改”会以一次更新提交名称、指令和完整规则;草稿与已存储任务不同时显示保存栏,“取消”恢复已存储的值。“重复”菜单提供每周、周一至周五、每天、每 N 小时、每 N 分钟、每 N 秒、仅一次和自定义(cron),宿主接受其中任何一项,因此一次性 After 可保存为 At。规范化后等价的规则不写入或重设目标:相同的 Every 间隔不会重新起算,未变更的一次性目标保留 After 或 At。保存期间卡片各行禁用。离开卡片不会回滚宿主已开始的写入。 +- “仅一次”:“日期”打开月历,“时间”打开“时”“分”“秒”三列,“时区”决定如何解释它们。任务运行一次后结束。 +- “每 N 分钟”和“每 N 小时”:“重复间隔”设置分钟数或小时数,至少为 1。间隔从你保存任务时所在的分钟起算。 +- “每天”:“重复间隔”设置天数,“时间”打开“时”“分”两列。 +- “每周”和“周一至周五”:“重复间隔”设置周数,“星期”选择日子,“时间”打开“时”“分”“秒”三列。“周一至周五”一次选中这五天。 +- “每月”:“重复间隔”设置月数,“每月日期”选择 1 到 31 日中的一天,“时间”打开“时”“分”“秒”三列。某月没有所选日期时,任务在该月最后一天运行。 +- “自定义”:“自定义规则”包含规则文本。其他选项无法重现的规则以“自定义”打开。没有可编辑规则文本的已有任务显示其原频率,并保留该时间规则,直到你保存替代规则。 -刷新目录会保留你已修改的字段,其余字段取自已刷新的记录,因此其他字段的并发变化不会被未保存的修改覆盖。输入无效时显示错误并阻止保存。若投递或其他编辑改变了任务,冲突会阻止覆盖该变化;请重试以修改最新规则。更新被接受后刷新目录。更新被拒绝或无法确认与目录加载错误相互区分:应使用“重试”重新加载目录,而不是重复已确认的更新。若更新本身无法确认,应在重试前检查任务。关闭详情或切换任务后才到达的响应不会替换当前视图。 +“时区”先列出最近选择的时区,标出系统时区,并可按 UTC 偏移、IANA 标识或城市搜索。引导式选项和使用独立时区的“自定义”表达式显示此字段;其他“自定义”规则由文本指定时区。 + +各字段只修改本地草稿。若任务指向已有会话,执行位置仍提供“当前关联会话”,可撤销目标变更而保留其他修改。编辑期间,详情底部显示“有未保存的修改”以及“放弃”和“保存修改”;“保存修改”以一次更新只提交已修改的字段,“放弃”恢复已存储的值。只有时间规则改变时,保存才会提交新规则。只有实际修改且字段和时间规则有效时,才能“保存修改”。无效的自定义文本保留在草稿中,并显示纠正提示;宿主也会在保存时校验规则。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。保存进行期间,各字段禁用。离开详情不会回滚宿主已开始的写入。 + +切换任务或离开页面时保留未保存的草稿。刷新目录会更新未修改的表单;已修改的表单保留全部字段和原版本。若投递或其他编辑改变了任务,详情会在收到新版本后说明任务已在其他位置更新,并禁用“保存修改”。宿主也会在保存时检查版本。“保留修改并复核”保留你改过的名称、内容、时间和目标字段组,其余字段组载入最新值。保存前请复核整份表单;此操作本身不保存。若同一字段组在其他位置也有更改,表单优先保留你的修改。“放弃”用最新存储值替换整份草稿。保存因其他原因失败时,草稿保留,详情提示你重试;对于结果未知的更新,请在重试前检查任务。更新被接受后刷新目录。关闭详情或切换任务后才到达的响应不会替换当前视图。 ## 时间与投递参考 -Session 未打开时,提醒仍然保存。宿主运行期间,在提醒到期时恢复原 Session 并排入 follow-up,不中断当前工作。重启后检查存储的任务,投递逾期的一次性提醒,或每条重复任务最近错过的一次。关闭宿主后,调度停止,直到宿主再次启动。同一 Session 的到期重复任务可以共用一条消息。 +Session 未打开时,提醒仍然保存。宿主运行期间,在提醒到期时恢复或创建目标 Session 并排入 follow-up,不中断当前工作。重启后检查存储的任务,投递逾期的一次性提醒,或每条重复任务最近错过的一次。关闭宿主后,调度停止,直到宿主再次启动。同一 Session 的到期重复任务可以共用一条消息。 -固定速率提醒在间隔改变前与创建时间对齐;间隔改变后与接受保存的时间对齐。每日提醒则遵循保存的本地时间与 IANA 时区。不存在的每日本地时间或日期会被跳过;重叠时间选择当天较早的一次。绝对时间请求会拒绝不存在的本地时间,并在重叠时选择较早时刻。浏览器提供其时区来解释自然语言请求;显式指定时区可以避免歧义。任务详情在频率文案里保留钟表规则保存的时区,并把每个下一目标显示为设备时区的钟点;一次性任务仅存储 UTC 时点,因此其时间戳使用浏览器时区。 +IANA 时区下的重复规则遵循本地钟表时间:跳过不存在的本地时间,重复出现的本地时间取较早的时刻。已有任务在你保存新规则之前保留其时间规则:固定速率提醒保持与创建时间对齐,每日、每周或 cron 提醒遵循其 IANA 时区下保存的本地时间。浏览器提供其时区来解释自然语言请求;显式指定时区可以避免歧义。自动化任务页面把每个下次运行时间显示为浏览器时区的钟点;规则的时区与浏览器时区不同时,频率文本会标出该时区;未指定时区的规则使用浏览器时区。 -已保存的发送记录确认消息已持久化到对话收件箱,不表示模型完成了所请求的工作。收件箱持久化或任务写入失败时,不增加已保存记录。收件箱持久化后崩溃或任务写入失败,可能留下未记入发送记录的已投递消息,并重复投递;不保证恰好投递一次。这不是执行历史,也不是外部通知渠道。 +已保存的发送记录确认消息已持久化到对话收件箱,不表示模型完成了所请求的工作。收件箱持久化或任务写入失败时,不增加已保存记录。收件箱持久化后崩溃或任务写入失败,可能留下未记入发送记录的已投递消息,并重复投递;不保证恰好投递一次。关闭宿主会丢弃仍在对话收件箱中等待的每条消息:其已保存记录仍然保留,模型不会收到该消息,宿主也不会再次发送。这不是执行历史,也不是外部通知渠道。 已保存的记录在追加确认时裁剪:宿主保留确认时间落在配置的 `deliveryHistoryDays` 窗口内的记录(窗口以本次追加回执的 `deliveredAt` 向前计算),且最多保留最新的 `deliveryHistoryRecords` 条。最近一次回执始终保留,发生裁剪时标记更早记录不可用。宿主将保留的历史保存在内存中,每次确认均重写完整任务行。分页限制返回的记录数,不限制保留的历史或指令字节数。 -不支持暂停和每次运行新建 Session。名称、指令和运行时间的修改对模型开放:`schedule_update` 原地修改提醒并保留其 id 与已保存的投递记录;自动化任务页面也可按所选任务的绑定修改。两者都不是跨会话转交工作流。仅记录在旧 Session 日志中的提醒不会自动调度;请重新创建仍需要的提醒。此前已删除的任务记录不会被重建。 +模型可通过 `schedule_edit` 修改每条提醒的名称、指令、时间规则和目标,或暂停、恢复提醒;自动化任务页面也可对每条提醒这样做。两者都不是跨会话转交工作流。每次修改都会在每个 Agent 已加载的关联对话的下一次模型请求中加入一条通知,发起修改的对话除外。仅记录在旧 Session 日志中的提醒不会自动调度;请重新创建仍需要的提醒。此前已删除的任务记录不会被重建。 ## 延伸阅读 -- [Schedule 参考](../../../packages/schedule/schedule/README.zh.md) 说明精确的时间选择器、持久化与投递限制。 +- [Schedule 参考](../../../packages/schedule/schedule/README.zh.md) 说明任务字段、投递目标、重复规则、持久化与投递限制。 - [自动化任务页面参考](../../../packages/client/ui-schedule/README.zh.md) 说明全局页面与对话顶部目录。 ## 开发备注 diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 80b46c86fd..a86a64bdb9 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -15,8 +15,8 @@ en: ffc55792d6e922e1 zh: 83bd759638857e2d /packages/package-groups: - en: ef8a02bd7650ec1e - zh: 70195c5ca6525a32 + en: 45ded1c769f240ae + zh: 8c1b380d2b4290d4 /packages/release-expectations: en: 236081c1659b25ab zh: 809110adf003802e diff --git a/packages/README.md b/packages/README.md index e024e85e62..e14bb69398 100644 --- a/packages/README.md +++ b/packages/README.md @@ -49,10 +49,11 @@ Every package lives in exactly one group; new packages join existing groups, and | [`fs/`](fs/README.md) | Filesystem capability family: seam, local impl, model-facing file tools, discovery tools | | [`lsp/`](lsp/README.md) | LSP capability family: seam, generic stdio provider, and the `lsp` tool | | [`skill/`](skill/README.md) | Skill capability family: provider registry, local provider, model-facing catalog/loader | -| [`connector/`](connector/README.md) | Application plugins that connect third-party services through existing skills, Shell, and subprocesses | +| [`connector/`](connector/README.md) | Plugins connecting third-party services through skills and CLIs | | [`compaction/`](compaction/README.md) | Compaction capability family: Service Definition + basic provider + command Consumer | | [`context/`](context/README.md) | Model-visible request context: workspace instructions, time context, references | | [`subagent/`](subagent/README.md) | Subagent capability family: provider-registry contract and model-facing delegation tools | +| [`team/`](team/README.md) | Team coordination: shared task boards and model-facing task tools | | [`jobs/`](jobs/README.md) | Generic background-job runtime and model-facing job control tools | | [`experimental/`](experimental/README.md) | Capabilities under evaluation; [status and support policy](experimental/README.md#status) | | [`workflow/`](workflow/README.md) | Workflow seam, PTC process engine, and the model-facing `workflow` tool | diff --git a/packages/README.zh.md b/packages/README.zh.md index c88143fe27..b58d7bd937 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -49,10 +49,11 @@ harness 由 `packages/` 下的 npm 包组装而成,按能力系列分组:会 | [`fs/`](fs/README.zh.md) | 文件系统能力系列:seam、本地实现、面向模型的文件工具、发现工具 | | [`lsp/`](lsp/README.zh.md) | LSP 能力系列:seam、通用 stdio 提供方和 `lsp` 工具 | | [`skill/`](skill/README.zh.md) | skill(技能)能力系列:提供方注册表、本地提供方、面向模型的目录/loader | -| [`connector/`](connector/README.zh.md) | 通过现有 skill、Shell 与 subprocess 接入第三方服务的应用插件 | +| [`connector/`](connector/README.zh.md) | 通过 skill 和 CLI 接入第三方服务的插件 | | [`compaction/`](compaction/README.zh.md) | 压缩(compaction)能力系列:Service Definition + 基础提供方 + 命令 Consumer | | [`context/`](context/README.zh.md) | 模型可见请求上下文:workspace 指令、时间上下文、引用 | | [`subagent/`](subagent/README.zh.md) | subagent 能力系列:提供方注册表约定和面向模型的委托工具 | +| [`team/`](team/README.zh.md) | Team 协调:共享任务板与面向模型的任务工具 | | [`jobs/`](jobs/README.zh.md) | 通用后台任务运行时和面向模型的作业控制工具 | | [`experimental/`](experimental/README.zh.md) | 仍在评估中的能力;[状态与支持策略](experimental/README.zh.md#status) | | [`workflow/`](workflow/README.zh.md) | 工作流 seam、PTC 进程引擎、面向模型的 `workflow` 工具 | diff --git a/packages/acp/acp/src/session.ts b/packages/acp/acp/src/session.ts index 2af289b3a2..e1abf0b2f0 100644 --- a/packages/acp/acp/src/session.ts +++ b/packages/acp/acp/src/session.ts @@ -24,8 +24,8 @@ import { assistantUpdates, toolCallUpdate, toolResultUpdate } from './updates.ts interface SubagentLifecycle { /** Dispose subagent descendants below exact host-owned parents child-first. */ drainDescendants(parents: readonly Agent[]): Promise - /** Observe currently managed descendants without closing future admission. */ - waitForChildren(parent: Agent): Promise + /** Join progressing work in the root's subagent tree without closing future admission. */ + waitForTreeWork(root: Agent): Promise } /** Inputs shared by fresh and resumed ACP session construction. */ @@ -489,7 +489,7 @@ export class AcpSession { await Promise.race([this.agent.whenIdle(), cancelled]) if (isCancelled()) break const idleSeq = this.agent.session.seq - const children = await Promise.race([subagents?.waitForChildren(this.agent), cancelled]) + const children = await Promise.race([subagents?.waitForTreeWork(this.agent), cancelled]) if (isCancelled()) break if (children || !idleAt(idleSeq)) continue await this.outputTail diff --git a/packages/acp/acp/tests/turns.spec.ts b/packages/acp/acp/tests/turns.spec.ts index e85c2553d9..39eb9f784e 100644 --- a/packages/acp/acp/tests/turns.spec.ts +++ b/packages/acp/acp/tests/turns.spec.ts @@ -50,7 +50,7 @@ async function installDelegationTool(ctx: BridgeHarness['ctx']): Promise<() => b if (exec.agent === undefined) throw new Error('delegation fixture requires an Agent') const child = await ctx.subagents.startActivation({ provider: 'local-test', label: 'later child', delivery: 'caller', signal: exec.signal, - request: { parent: exec.agent, prompt: [{ type: 'text', text: 'later child task' }] }, + parent: exec.agent, prompt: [{ type: 'text', text: 'later child task' }], }) const result = await child.result delegated = result.stopReason === 'completed' @@ -215,7 +215,7 @@ describe('ACP prompt lifecycle', () => { const appendSpy = vi.spyOn(parent.session, 'append') const failures: number[] = [] harness.ctx.on('agent/error', ({ turn }) => { failures.push(turn) }) - const waitForChildren = vi.fn().mockImplementationOnce(() => { + const waitForTreeWork = vi.fn().mockImplementationOnce(() => { appendSpy.mockImplementation(((type: string, ...rest: never[]) => { if (type === failedEvent) throw new Error(`summary ${failedEvent} unavailable`) return (append as (...args: never[]) => unknown)(type as never, ...rest) @@ -223,7 +223,7 @@ describe('ACP prompt lifecycle', () => { parent.followup(createUserMessage({ content: [{ type: 'text', text: 'child result' }], source: { kind: 'test' } })) return Promise.resolve(true) }).mockResolvedValue(false) - harness.ctx.provide('subagents', { waitForChildren, drainDescendants: vi.fn() } as never) + harness.ctx.provide('subagents', { waitForTreeWork, drainDescendants: vi.fn() } as never) try { await expect(harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'delegate' }] })) .rejects.toThrow(`summary ${failedEvent} unavailable`) @@ -594,10 +594,10 @@ describe('ACP prompt lifecycle', () => { const parent = harness.ctx.agents.get(SessionId(sessionId))! const waiting = Promise.withResolvers() const children = Promise.withResolvers() - const waitForChildren = vi.fn() + const waitForTreeWork = vi.fn() .mockImplementationOnce(() => { waiting.resolve(undefined); return children.promise }) .mockResolvedValue(false) - harness.ctx.provide('subagents', { waitForChildren, drainDescendants: vi.fn() } as never) + harness.ctx.provide('subagents', { waitForTreeWork, drainDescendants: vi.fn() } as never) let settled = false const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'delegate' }] }) const observed = prompt.then(() => { settled = true }, () => { settled = true }) @@ -619,11 +619,11 @@ describe('ACP prompt lifecycle', () => { const sessionId = await newSession(harness) const waiting = Promise.withResolvers() const children = Promise.withResolvers() - const waitForChildren = vi.fn() + const waitForTreeWork = vi.fn() .mockImplementationOnce(() => { waiting.resolve(undefined); return children.promise }) .mockResolvedValue(false) const drainDescendants = vi.fn() - harness.ctx.provide('subagents', { waitForChildren, drainDescendants } as never) + harness.ctx.provide('subagents', { waitForTreeWork, drainDescendants } as never) const first = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'delegate' }] }) await waiting.promise await harness.client.cancel({ sessionId }) @@ -647,7 +647,7 @@ describe('ACP prompt lifecycle', () => { const parent = ctx.agents.get(SessionId(sessionId))! const waiting = Promise.withResolvers() const children = Promise.withResolvers() - vi.spyOn(ctx.subagents, 'waitForChildren').mockImplementationOnce(() => { + vi.spyOn(ctx.subagents, 'waitForTreeWork').mockImplementationOnce(() => { waiting.resolve(undefined) return children.promise }) @@ -873,11 +873,11 @@ describe('ACP prompt lifecycle', () => { await delivery.promise if (fail) throw new Error('summary image unavailable') } - const waitForChildren = vi.fn().mockImplementationOnce(() => { + const waitForTreeWork = vi.fn().mockImplementationOnce(() => { parent.followup(createUserMessage({ content: [{ type: 'text', text: 'child result' }], source: { kind: 'test' } })) return Promise.resolve(true) }).mockResolvedValue(false) - harness.ctx.provide('subagents', { waitForChildren, drainDescendants: vi.fn() } as never) + harness.ctx.provide('subagents', { waitForTreeWork, drainDescendants: vi.fn() } as never) let settled = false const prompt = harness.client.prompt({ sessionId, prompt: [{ type: 'text', text: 'delegate' }] }) const observed = prompt.then(() => { settled = true }, () => { settled = true }) @@ -910,7 +910,7 @@ describe('ACP prompt lifecycle', () => { const sessionId = await newSession(harness) const parent = ctx.agents.get(SessionId(sessionId))! const noChildren = Promise.withResolvers() - vi.spyOn(ctx.subagents, 'waitForChildren').mockImplementationOnce(() => { + vi.spyOn(ctx.subagents, 'waitForTreeWork').mockImplementationOnce(() => { noChildren.resolve(undefined) return Promise.resolve(false) }) diff --git a/packages/api/remotes/README.i18n.yaml b/packages/api/remotes/README.i18n.yaml index f3b9eab6fc..64b8496be6 100644 --- a/packages/api/remotes/README.i18n.yaml +++ b/packages/api/remotes/README.i18n.yaml @@ -15,8 +15,8 @@ en: a7a78c6d1aeebeb3 zh: 4bb69f32d8b05ba3 /deepseek-ai-dsh-api-remotes/use-this-package: - en: a80d44e0683768a5 - zh: 379833ac180e5418 + en: 6e3448339c646a7e + zh: 5dc00ff4cceaa88c /deepseek-ai-dsh-api-remotes/forwarded-host-events: en: 31bb9a2f50094b84 zh: 226c055739d5def7 diff --git a/packages/api/remotes/README.md b/packages/api/remotes/README.md index 8d49cb49a5..a05773a4af 100644 --- a/packages/api/remotes/README.md +++ b/packages/api/remotes/README.md @@ -29,7 +29,7 @@ Two-sided BFF for Host Remote capabilities selected by this application. The Hos [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.md) owns Agent and Session identity policy, including the Typert lookup resolvers used by other namespaces. This package selects and mounts that generated Session contribution without a direct runtime dependency on `@deepseek-ai/dsh-session`; activation policy stays with Session Controller. -The Client assembly mounts Office conversion, Commands, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. +The Client assembly mounts Office conversion, Commands, Agent Teams, credentials, settings, Goal, Schedule, dynamic Cordis, file and Session references, read-only Host plugin inventory, plugin-installation registry response comparison, message feedback, permission presets, Session Controller, subagents, and Workspace Controller contributions. The `permissionPresets` namespace returns the complete process-level catalog used by current-session controls. Cordis effect ownership withdraws every contribution when this assembly unloads, while `@deepseek-ai/dsh-api-gateway/client` owns descriptor validation, traced namespace Services, direct and scoped methods, invocation, streams, and cancellation. The Client entry consumes the shared `TypertClientRemote` interface through Cordis and does not import the concrete Gateway. It re-exports the Gateway Client face's declaration merges type-only, so a consumer reaching the forwarded-event vocabulary through this facade gains no runtime edge to the Gateway implementation. This facade is also the front door for the wire type vocabulary a Client package names. It re-exports, type-only, the Remote failure vocabulary (`RemoteResult`, `RemoteFailure`, `RemoteErrorCode`, `RemoteErrorDetailsMap`), the Host facts (`RemoteHostFacts`), and each selected domain's client-safe payload types, so a Client feature package imports one specifier instead of reaching into `dsh-typert-protocol`, the Gateway, or an owner's Host entry. Two kinds of package deliberately skip this door: the API-layer packages this assembly itself selects — importing it back would close a dependency cycle — and their tests, which take the failure vocabulary from `dsh-typert-protocol` directly. A UI package's tests instead take the `RemoteError` constructor from [`dsh-client-test-runtime`](../../test-support/client-runtime/README.md). diff --git a/packages/api/remotes/README.zh.md b/packages/api/remotes/README.zh.md index 4f9772403d..bc616b9588 100644 --- a/packages/api/remotes/README.zh.md +++ b/packages/api/remotes/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" [`@deepseek-ai/dsh-api-session-controller`](../session-controller/README.zh.md) 拥有 agent(智能体)与会话身份策略,包括供其他 namespace 使用的 Typert lookup 解析器。本包选择并挂载生成的会话 contribution,无需直接依赖 `@deepseek-ai/dsh-session` 的运行时;激活策略由会话控制器负责。 -Client 组合挂载 Office 转换、Commands、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 +Client 组合挂载 Office 转换、Commands、Agent Teams、凭据、settings、Goal、Schedule、动态 Cordis、文件与会话引用、只读 Host 插件清单、插件安装源响应比较、消息反馈、权限预设、会话控制器、subagents 和 Workspace 控制器 contribution。`permissionPresets` namespace 返回 current-session 控件使用的完整进程级目录。该组合卸载时,Cordis effect 的所有权机制会撤回所有贡献;`@deepseek-ai/dsh-api-gateway/client` 负责描述符校验、可追踪的 namespace 服务、直接与作用域方法、调用、流与取消。Client 入口通过 Cordis 消费共享的 `TypertClientRemote` 接口,不导入具体 Gateway;它只以 type-only 形式重新导出 Gateway Client face 的声明合并,因此消费端经由本外观取到转发事件词汇时,运行时不会多出一条通往 Gateway 实现的边。 本 facade 同时是 Client 包指称 wire 类型词汇的正门。它以 type-only 方式转出 Remote 失败词汇(`RemoteResult`、`RemoteFailure`、`RemoteErrorCode`、`RemoteErrorDetailsMap`)、Host 事实(`RemoteHostFacts`),以及各已选领域对 Client 安全的载荷类型,因此 Client 功能包只 import 一个 specifier,不必伸手进 `dsh-typert-protocol`、Gateway 或某个拥有方的 Host 入口。有两类包刻意不走这道门:本装配自己选中的 API 层包——反向 import 会形成依赖环——以及它们的测试,后者直接从 `dsh-typert-protocol` 取失败词汇。UI 包的测试则从 [`dsh-client-test-runtime`](../../test-support/client-runtime/README.zh.md) 取 `RemoteError` 构造器。 diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index 8735bc4339..1fe16a4a87 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -99,6 +99,7 @@ "@deepseek-ai/dsh-api-account-controller": "workspace:*", "@deepseek-ai/dsh-deepseek-account": "workspace:*", "@deepseek-ai/dsh-client-product-analytics": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-trajectory": "workspace:*" } } diff --git a/packages/api/remotes/src/client/index.ts b/packages/api/remotes/src/client/index.ts index 8a4b7dea8a..86112b7cc2 100644 --- a/packages/api/remotes/src/client/index.ts +++ b/packages/api/remotes/src/client/index.ts @@ -6,6 +6,8 @@ export type {} from '@deepseek-ai/dsh-client-product-analytics/remote' import agentPresetsRemote from '@deepseek-ai/dsh-agent-preset-registry/remote' import userQuestionsRemote from '@deepseek-ai/dsh-user-questions/remote' import commandsRemote from '@deepseek-ai/dsh-commands/remote' +import agentTeamsRemote from '@deepseek-ai/dsh-agent-team/remote' +export type {} from '@deepseek-ai/dsh-agent-team/remote' import accountRemote from '@deepseek-ai/dsh-api-account-controller/remote' import settingsControllerRemote from '@deepseek-ai/dsh-api-settings-controller/remote' import officeToPdfRemote from '@deepseek-ai/dsh-office-to-pdf/remote' @@ -189,7 +191,7 @@ export async function apply(ctx: Context): Promise<() => Promise> { const disposers: Array<() => Promise> = [] try { for (const contribution of [ - productAnalyticsRemote, agentPresetsRemote, commandsRemote, settingsControllerRemote, accountRemote, + productAnalyticsRemote, agentPresetsRemote, commandsRemote, agentTeamsRemote, settingsControllerRemote, accountRemote, goalsRemote, llmRemote, dynamicRemote, scheduleRemote, pluginInventoryRemote, pluginManagerRemote, pluginMarketRemote, pluginRegistryProbeRemote, toolResultsRemote, messageFeedbackRemote, sessionFeedbackRemote, diff --git a/packages/api/remotes/tsconfig.client.json b/packages/api/remotes/tsconfig.client.json index 70181b08c5..49b3180c43 100644 --- a/packages/api/remotes/tsconfig.client.json +++ b/packages/api/remotes/tsconfig.client.json @@ -11,6 +11,7 @@ "src/types.ts" ], "references": [ + { "path": "../../team/agent-team" }, { "path": "../../client/product-analytics/tsconfig.client.json" }, { "path": "../../../vendor/cordis" diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 010c41bf94..fb96bac533 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,11 +15,11 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: d3d53e899960d96e - zh: 16b2bc7fe74215d8 + en: 25c9c54037dc7971 + zh: 7fa87a380b046afb /session-controller/client-references: - en: 41bdda1ac32df558 - zh: aa5d0e325924066b + en: e8979a803ec3e194 + zh: c567efcd971728ba /session-controller/session-media-references: en: 954923654eebe2dc zh: 6bd9a7d2ea965aed diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 6fd7b24561..4ce2afd480 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -33,7 +33,7 @@ History pages and follow opening snapshots carry one `{ type: 'event', event: Se The Client journal validates current Session event envelopes before publishing follow snapshots, live entries, or history pages. It reuses the browser-safe Session validators for required surface markers, exact replacement endpoints, earlier unique source seqs, embedded Assistant provider metadata, request-header omissions, and tool-error consistency. Invalid records fail without field stripping or normalization; range membership and source existence remain durable-log checks on the Host. -Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and subagent ownership fence to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. +Each endpoint states its activation policy. List reads only stored headers and projection-cache rows: it never calls per-session stat or opens a cold Session body. A current-format cache identity may supply every list hint; a lifecycle-matching predecessor cache may supply only its version-compatible title as a stale display fact, never as an authoritative fold seed. Search, history pages, log following, skill discovery, and workspace-path opening can inspect persistence without activating an Agent; `canOpenWorkspacePath()` reports native-opening availability without addressing a Session. Cancellation requires live state; queue mutation, model, rename, prompt, and file-reference operations may resolve or resume an ordinary Session. Prompt rejects content with neither non-whitespace text nor an attachment before resolving the Agent or appending Session events; queue edits accept only non-empty text content. Prompt admission consumes opaque receipts from the injected [`fileUploads`](../../client/file-upload/README.md) Host service and resolves every same-Agent receipt before sending the complete ordered content list through `ctx.attachments`. A receipt names a staged file or a staged image, and an image receipt subjects the prompt to the same image-input check as an encoded image. Prompt retries whose `requestId` is already queued or logged return the original acceptance without inserting another message. Create and fork are the only operations that create a new Agent directly. The service applies one preset-aware resume policy and the subagent ownership fence determined by `origin: 'subagent'` to its own methods and to the Typert Agent and Session lookups used by other Remote namespaces. Queue mutation has one narrow exception: a live child whose current projected identity is continuable and comes from its own non-seed suffix accepts the ordinary Edit, Remove, and QueueDock Steer actions across both inbox destinations. One-shot, missing, unknown, corrupt, seed-only, or cold children remain rejected without resume. The skill catalog uses a live Agent's effective working directory and scoped registry when present. Cold listing uses the projected current directory, falling back to the recorded origin and then the configured directory default. It retains the preset standing scope without activating an Agent. The authenticated delivery routes use `workspaceDesktop()` for the serving Host name and file-manager behavior. `openWorkspacePath({ path, action: "reveal" })` delegates file-manager navigation to the native adapter; omitting `action` opens the file-type association, including HTML and SVG. Both operations require the composed filesystem to map the requested Host path to the same canonical process path; unmapped remote paths are refused before a native command runs. `session.projections` normally reads an exact baseline, including current-format cold logs, and returns `kind: sequenced`. Only a read requiring migration returns `kind: migration-required` hints without `asOfSeq`; missing keys remain absent. It returns null for a missing Session. Fork callers may set `allowMigration: false` to receive `session/migration-required` instead of starting source migration; omission retains automatic migration. The Client exposes shared values and explicit-read state through `projectionsBySession`; domains select their own keys. Session-list summaries carry `agentAvailable`, updated through existing summary and status events independently of durable projections. Sequenced reads and live projection frames use the same sequence ordering; cached reads fill hints without replacing sequenced values. Every Remote endpoint is access-controlled: a Peer whose principal is not the owner reaches an endpoint only when, on every resource the call touches, a binding of that principal kind's policy in [`dsh-api-remote-access`](../remote-access/README.md) grants a role listing the action ([Peer principals Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.md)). The controller injects `remoteAccess` and registers a default resolver for the `session` resource kind through `typert.resources`. It reads a named `sessionId` parameter, otherwise the first object argument's `sessionId` or `address`; unrelated string parameters name no Session. An object containing both `sessionId` and `address` is invalid, even when they name the same Session. `session/events`, the deprecated `session/page`, `session/observeEvent`, and `session/follow` use this resolver to read `address.sessionId` for an ordinary Session address and `address.childSessionId` for a subagent address; whether access to the parent Session covers its children is the policy's rule. `session/projections`, `session/observeProjections`, `session/state`, `session/observeState`, and `session/wait` read the Session resource from `request.sessionId`, so each call and subscription names only the Sessions it may read. `session/list`, `session/search`, and `session/control` read no resource, so their calls touch the `global` resource and need a `global` role; for a non-owner caller, `session/list` returns only the rows, `session/search` only the hits, and `session/control` only the baseline projections and projection frames, whose Session `ctx.remoteAccess.allows()` admits for the same action, so that action also belongs to a `session` role; owner results are unfiltered. `session/prompt` builds the durable `user-rpc` message source in its Remote method and records `principal` only for a non-owner caller, read through `principalOf(this.ctx.invocation)`; a source without `principal` belongs to the owner. @@ -76,14 +76,14 @@ Queue edits replace pending content with non-empty text only. `session.attachment` receives `{ sessionId, attachment: ImageAttachmentRef }` and passes the complete reference to `AttachmentStore.readImage()`, without reading or traversing Session history. The Client supplies the message's reference through `session.readAttachment(ref)`. Connection authentication and Gateway permission checks still apply; `sessionId` selects the Session resource for the endpoint's permission check. After authorization, the handler does not check whether that Session exists and does not return `session/not-found` merely because it is absent. An authorized caller may read any image in the same store, including an image referenced only by another Session or by no Session. The response preserves the supplied reference after verifying its ID, media type, byte length, width, and height against the stored bytes. Optional `name` and `originalDimensions` pass through as caller-supplied display information and are not verified against the file. Missing or invalid objects return a terminal attachment failure. The Client's historical-image cache retains one result and browser URL per Session and attachment ID. -The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads once the Agent registry, Session store, and Workspace registry exist and unwinds with the controller. Its `agent/pre-step` listener rejects a step proposed for an archived Session or for a subagent descendant of one — read from the Session header's lineage fields, never a fork — so a late waking delivery ends its turn as `blocked` without a model request; unarchiving lifts the gate for the whole lineage. The work an archived Session still runs is reported and stopped by its owners through the Workspace registry's archive admission ([seam](../../workspace/workspace/README.md)): the running turn by the [Agent registry](../../core/agent/README.md), owned jobs by the [job registry seam](../../jobs/jobs/README.md), subagent descendants by the [Subagent](../../subagent/subagent/README.md) runtime, reminders by the [Schedule](../../schedule/schedule/README.md) plugin; this controller reports nothing itself. +The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads once the Agent registry, Session store, and Workspace registry exist and unwinds with the controller. Its `agent/pre-step` listener rejects a step proposed for an archived Session or for a subagent descendant of one — read through available Session headers, never a fork — so a late waking delivery ends its turn as `blocked` without a model request; unarchiving lifts the gate for the whole lineage. The Subagent runtime separately checks retained creation ancestors, covering managed descendants whose intermediate creators are offline. The work an archived Session still runs is reported and stopped by its owners through the Workspace registry's archive admission ([seam](../../workspace/workspace/README.md)): the running turn by the [Agent registry](../../core/agent/README.md), owned jobs by the [job registry seam](../../jobs/jobs/README.md), subagent descendants by the [Subagent](../../subagent/subagent/README.md) runtime, reminders by the [Schedule](../../schedule/schedule/README.md) plugin; this controller reports nothing itself. ## Client references `sessions.retain(target, { source, signal? })` immediately acquires one exact Client generation and starts its shared initial history opening. The target is a known Session id or a durable direct-parent subagent address; the Host validates an explicit address when history opens. The returned reference supports idempotent `release()` and `Symbol.dispose`; its `ready` Promise follows the shared `Session.open()` result and resolves to the exact binding when that attempt settles, including when a Remote failure is represented by `openState: 'error'`. It rejects when `Session.open()` rejects, its waiter is cancelled, or the reference is released early. Cancelling one waiter does not cancel another owner's opening. `sessions.using(target, options, operation)` waits for that settlement, holds its reference until the callback settles, and propagates rejected readiness and callback failures. -References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent validation. Successful descriptor restoration determines the displayed mode; failures remain local to the child, and control requests still require a confirmed continuable identity. +References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 8729f555ba..0aecad0564 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -33,7 +33,7 @@ kind: "package-reference" Client journal 在发布 follow 快照、live entry 或历史页之前验证当前 Session 事件 envelope。它复用浏览器安全的 Session validator,检查必需的 surface marker、精确的 replacement endpoint、更早且唯一的 source seq、内嵌 Assistant 提供方元数据、request header 可选字段的省略规则以及工具错误一致性。无效 record 直接失败,不删除字段或归一化;范围成员与来源存在性仍由 Host 的持久日志检查。 -每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 +每个 endpoint 都声明自己的激活策略。列表只读取持久化 header 与 projection cache row,绝不调用逐 Session stat 或打开冷 Session body。当前格式 cache identity 可以提供全部列表 hint;生命周期匹配的 predecessor cache 只能提供版本兼容的 title,作为可能过时的展示事实,绝不能作为权威 fold seed。搜索、历史页、日志跟随、skill 发现和工作区路径打开可以在不激活 Agent 的情况下检查 persistence;`canOpenWorkspacePath()` 无需指定 Session 即可报告原生打开能力。取消要求 live 状态;queue 变更、模型、重命名、prompt 和文件引用操作可以解析或恢复普通 Session。提示词会在解析 Agent 或追加 Session 事件前,拒绝既没有非空白文本也没有附件的 content;queue edit 只接受非空文本 content。prompt 准入从注入的 [`fileUploads`](../../client/file-upload/README.zh.md) Host 服务取得不透明凭证,在把完整有序内容列表交给 `ctx.attachments` 前解析每个属于同一 Agent 的凭证。凭证指向一个暂存文件或一张暂存图片;图片凭证与编码图片一样要经过图片输入检查。`requestId` 已进入 queue 或日志时,prompt 重试直接返回原来的接受结果,不会重复插入消息。只有 create 与 fork 会直接创建新 Agent。该服务把同一套感知 preset 的恢复策略和由 `origin: 'subagent'` 确定的 subagent ownership fence 同时用于自身方法,以及其他 Remote namespace 使用的 Typert Agent 与 Session lookup。Queue 变更只有一个狭窄例外:当前 projection identity 为 continuable 且来自自身非 seed suffix 的在线 child,可以在两个 inbox 目标上使用普通 Edit、Remove 与 QueueDock Steer action。One-shot、缺失、未知、损坏、仅含 seed identity 或冷 child 继续被拒绝,且不会恢复。skill 目录优先使用已有 live Agent 的有效工作目录与限定范围内的注册表。冷态列表使用投影中的当前目录,依次回退到记录的起始目录与配置的默认目录。它保留 preset 常驻 scope,不会激活 Agent。经过鉴权的文件交付路由通过 `workspaceDesktop()` 获取提供服务的 Host 名称和文件管理器行为。`openWorkspacePath({ path, action: "reveal" })` 将文件管理器导航委托给原生适配器;省略 `action` 时按文件类型关联打开,包括 HTML 和 SVG。两种操作都要求当前文件系统将请求的 Host 路径映射到同一个规范进程路径;无法映射的远端路径会在执行原生命令之前被拒绝。 `session.projections` 正常读取准确基线,包括当前格式的冷日志,返回 `kind: sequenced`。只有需要迁移时才返回不带 `asOfSeq` 的 `kind: migration-required` 提示,缺少的键保持缺席。Session 不存在时返回 null。Fork 调用者可设置 `allowMigration: false`,在源历史需要迁移时收到 `session/migration-required`;省略则保持自动迁移。Client 通过 `projectionsBySession` 暴露共享值和显式读取状态,由领域选择自身的 key。Session 列表摘要携带 `agentAvailable`,通过已有摘要与状态事件更新,与持久化 projection 相互独立。有序读取与实时 projection 帧使用相同的序号排序规则;缓存读取只补充提示,不替换有序值。 每个 Remote 端点都受访问控制:principal 不是 owner 的 Peer 只有在本次调用访问的每个资源上,该 principal kind 在 [`dsh-api-remote-access`](../remote-access/README.zh.md) 中的 policy 都有某个 binding 授予列出该 action 的 role 时,才能调用该端点([Peer 身份属性 Agent Note](../../../.agents/notes/implemented/architecture/2026-10-12-peer-principal-and-remote-access.zh.md))。控制器注入 `remoteAccess`,并经 `typert.resources` 为 `session` 资源种类登记默认 resolver。它读取具名 `sessionId` 参数,否则读取第一个对象参数的 `sessionId` 或 `address`;无关字符串参数不指明 Session。对象同时包含 `sessionId` 和 `address` 时无效,即使两者指向同一 Session。`session/events`、已弃用的 `session/page`、`session/observeEvent` 与 `session/follow` 使用该 resolver:对普通 Session 地址读 `address.sessionId`,对 subagent 地址读 `address.childSessionId`;父会话的访问权是否覆盖其子会话由 policy 决定。`session/projections`、`session/observeProjections`、`session/state`、`session/observeState` 与 `session/wait` 从 `request.sessionId` 读取会话资源,因此每次调用与订阅都只点名它可读的会话。`session/list`、`session/search` 与 `session/control` 不读取资源,其调用访问 `global` 资源,需要 `global` role;对非 owner 调用方,`session/list` 只返回其 Session 被 `ctx.remoteAccess.allows()` 按同一 action 允许的行,`session/search` 只返回这类 Session 的命中,`session/control` 也只返回这类 Session 的 baseline projection 与 projection 帧,因此该 action 也要列在 `session` role 中;owner 的结果不过滤。`session/prompt` 在其 Remote 方法内构造持久的 `user-rpc` 消息 source,且只为非 owner 调用方记录经 `principalOf(this.ctx.invocation)` 读取的 `principal`;不带 `principal` 的 source 属于 owner。 @@ -76,14 +76,14 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 `session.attachment` 接收 `{ sessionId, attachment: ImageAttachmentRef }`,并把完整引用交给 `AttachmentStore.readImage()`,不读取或遍历 Session 历史。Client 通过 `session.readAttachment(ref)` 传入消息中的引用。连接身份认证和 Gateway 权限检查仍然适用;`sessionId` 为该接口的权限检查指定 Session 资源。授权通过后,处理函数不检查该 Session 是否存在,也不会仅因其不存在而返回 `session/not-found`。获准调用的身份可以读取同一存储中的任意图片,包括仅被其他 Session 引用或未被任何 Session 引用的图片。响应在把 ID、媒体类型、字节数、宽度和高度与存储字节校验后,保留传入的引用。可选的 `name` 和 `originalDimensions` 作为调用方提交的显示信息原样返回,不根据文件校验。对象缺失或无效时返回明确的附件失败。Client 的历史图片缓存按 Session 和附件 ID 保留一份结果与浏览器 URL。 -本控制器通过 `ctx.plugin` 组合 `ArchivedSessionGate`:在 Agent 注册表、Session store 与 Workspace 注册表就绪后加载,随控制器一起释放。它的 `agent/pre-step` 监听器会拒绝为已归档会话或其子代理子孙——从 Session header 的血缘字段读出,从不包括 fork——提出的步骤,因此迟到的唤醒投递会让该回合以 `blocked` 收口而不发出模型请求;取消归档即为整条血缘解除门禁。已归档会话仍在跑的工作由各自的 owner 通过 Workspace 注册表的归档准入([接缝](../../workspace/workspace/README.zh.md))报告与停止:运行中的回合由 [Agent 注册表](../../core/agent/README.zh.md)负责,所属任务由[任务注册表接缝](../../jobs/jobs/README.zh.md)负责,子代理子孙由 [Subagent](../../subagent/subagent/README.zh.md) runtime 负责,提醒由 [Schedule](../../schedule/schedule/README.zh.md) 插件负责;本控制器自己不报告任何内容。 +本控制器通过 `ctx.plugin` 组合 `ArchivedSessionGate`:在 Agent 注册表、Session store 与 Workspace 注册表就绪后加载,随控制器一起释放。它的 `agent/pre-step` 监听器会拒绝为已归档会话或其子代理子孙——沿可用的 Session header 读取,从不包括 fork——提出的步骤,因此迟到的唤醒投递会让该回合以 `blocked` 收口而不发出模型请求;取消归档即为整条血缘解除门禁。Subagent runtime 另行检查保留的创建祖先,覆盖中间创建者已离线的托管后代。已归档会话仍在跑的工作由各自的 owner 通过 Workspace 注册表的归档准入([接缝](../../workspace/workspace/README.zh.md))报告与停止:运行中的回合由 [Agent 注册表](../../core/agent/README.zh.md)负责,所属任务由[任务注册表接缝](../../jobs/jobs/README.zh.md)负责,子代理子孙由 [Subagent](../../subagent/subagent/README.zh.md) runtime 负责,提醒由 [Schedule](../../schedule/schedule/README.zh.md) 插件负责;本控制器自己不报告任何内容。 ## Client 引用 `sessions.retain(target, { source, signal? })` 立即获取一个精确 Client generation 的引用,并启动其共享的首次历史打开。目标是已知 Session id 或持久的直接父子 subagent 地址;Host 在打开历史时校验显式地址。返回引用支持幂等的 `release()` 和 `Symbol.dispose`;其 `ready` Promise 跟随共享的 `Session.open()` 结果,并在该次尝试结算时解析为确切 binding,包括 Remote failure 以 `openState: 'error'` 表示的情况。仅当 `Session.open()` 拒绝、等待方取消或引用提前释放时,`ready` 才拒绝。取消一个等待方不会取消其他 owner 的打开。`sessions.using(target, options, operation)` 等待该次结算,持有引用直到回调结束,并传播被拒绝的就绪与回调失败。 -引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级。成功恢复 descriptor 后确定展示模式;失败只影响该子会话,控制请求仍要求已确认的 continuable 身份。 +引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 ## 会话媒体引用 diff --git a/packages/api/session-controller/src/agent.ts b/packages/api/session-controller/src/agent.ts index d16e041773..343ad9ba5f 100644 --- a/packages/api/session-controller/src/agent.ts +++ b/packages/api/session-controller/src/agent.ts @@ -92,21 +92,11 @@ export type ApiSessionAgentResult = /** * Test whether generic Session routing must leave an identity to subagent routing. - * @param ctx - Host context carrying the Agent ownership registry. - * @param session - attached or live Session whose ownership is tested. - * @param agent - live Agent when one exists for the Session. + * @param session - Attached or live Session whose origin is tested. * @returns whether subagent routing owns the Session identity. */ -export function hasApiSessionSubagentOwner( - ctx: Context, - session: Pick, - agent: Agent | undefined, -): boolean { - if (session.header.origin === 'subagent') return true - const parentId = session.header.parentSession - if (parentId === undefined || agent === undefined) return false - const parent = ctx.agents.get(parentId) - return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent) +export function hasApiSessionSubagentOwner(session: Pick): boolean { + return session.header.origin === 'subagent' } /** @@ -178,7 +168,7 @@ export class ApiSessionAgentController { const live = this.liveAgent(sessionId) if (live !== undefined) return live const attached = this.ctx.sessions.get(sessionId) - if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) { + if (attached !== undefined && hasApiSessionSubagentOwner(attached)) { return { error: apiSessionSubagentOwnershipError(sessionId) } } @@ -203,7 +193,7 @@ export class ApiSessionAgentController { const raced = this.liveAgent(sessionId) if (raced !== undefined) return raced const racedSession = this.ctx.sessions.get(sessionId) - if (racedSession !== undefined && hasApiSessionSubagentOwner(this.ctx, racedSession, undefined)) { + if (racedSession !== undefined && hasApiSessionSubagentOwner(racedSession)) { return { error: apiSessionSubagentOwnershipError(sessionId) } } if (error instanceof Error && error.name === 'SessionAlreadyOwnedError') { @@ -286,7 +276,7 @@ export class ApiSessionAgentController { private liveAgent(sessionId: SessionId): ApiSessionAgentResult | undefined { const agent = this.ctx.agents.get(sessionId) if (agent === undefined) return undefined - return hasApiSessionSubagentOwner(this.ctx, agent.session, agent) + return hasApiSessionSubagentOwner(agent.session) ? { error: apiSessionSubagentOwnershipError(sessionId) } : { agent } } @@ -312,13 +302,12 @@ export class ApiSessionAgentController { if (observation.header.id !== sessionId || observation.header.cwd === undefined) { throw new ApiSessionNotFound(`session "${sessionId}" not found`) } - if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) { + if (hasApiSessionSubagentOwner({ header: observation.header })) { throw new ApiSessionSubagentOwnership(sessionId) } const composition = await this.composeAgent(this.presetForObservation(observation)) const published = this.ctx.sessions.get(sessionId) - const live = this.ctx.agents.get(sessionId) - if (published !== undefined && hasApiSessionSubagentOwner(this.ctx, published, live)) { + if (published !== undefined && hasApiSessionSubagentOwner(published)) { throw new ApiSessionSubagentOwnership(sessionId) } return (await this.ctx.agents.resume({ @@ -343,7 +332,7 @@ export class ApiSessionAgentController { private async claim(sessionId: SessionId, request: ApiSessionCreateRequest): Promise { const attached = this.ctx.sessions.get(sessionId) const live = this.ctx.agents.get(sessionId) - if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) { + if (attached !== undefined && hasApiSessionSubagentOwner(attached)) { throw new ApiSessionSubagentOwnership(sessionId) } if (live !== undefined) { @@ -363,7 +352,7 @@ export class ApiSessionAgentController { let reusable: boolean { using observed = observation - if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, undefined)) { + if (hasApiSessionSubagentOwner({ header: observed.header })) { throw new ApiSessionSubagentOwnership(sessionId) } if (observed.header.cwd !== request.cwd) { diff --git a/packages/api/session-controller/src/archived-session-gate.ts b/packages/api/session-controller/src/archived-session-gate.ts index 06c6ee5f02..b1f556b397 100644 --- a/packages/api/session-controller/src/archived-session-gate.ts +++ b/packages/api/session-controller/src/archived-session-gate.ts @@ -4,7 +4,9 @@ * it is restored. The work a Session still runs is reported and stopped by * its owners — the Agent registry (`turn`), the job registry seam (`job`), * the Subagent runtime (`subagent`), and the Schedule plugin (`schedule`) — - * through the Workspace registry's archive-admission events. + * through the Workspace registry's archive-admission events. The Subagent + * runtime also checks its retained ancestry before each step, so a released + * intermediate Session cannot hide an archived ancestor. */ import type { Context, Plugin } from '@deepseek-ai/cordis' @@ -33,9 +35,10 @@ export const ArchivedSessionGate: Plugin.Object = { /** * Whether the Agent's Session, or a Session above it in its subagent lineage, - * is archived. Lineage follows the durable header fields through + * is archived. This header-only check follows the durable fields through * subagent-origin Sessions only: a fork of an archived Session is an - * independent conversation. + * independent conversation. The Subagent runtime separately checks managed + * ancestry when an intermediate Session is unavailable here. * @param ctx - Host context. * @param agent - the Agent proposing a step. * @returns whether an archived Session owns the step. diff --git a/packages/api/session-controller/src/client/contract/snapshot.ts b/packages/api/session-controller/src/client/contract/snapshot.ts index 78e0c8c8a3..4912d19b16 100644 --- a/packages/api/session-controller/src/client/contract/snapshot.ts +++ b/packages/api/session-controller/src/client/contract/snapshot.ts @@ -73,8 +73,6 @@ export interface SessionSnapshot { readonly running: boolean readonly subagent: { readonly address: SubagentAddress - /** Absent until the direct-parent catalog resolves. */ - readonly parentAvailable?: boolean } | null readonly removed: boolean readonly openState: OpenState diff --git a/packages/api/session-controller/src/client/sessions/manager.ts b/packages/api/session-controller/src/client/sessions/manager.ts index 105930d1ef..e7450ca973 100644 --- a/packages/api/session-controller/src/client/sessions/manager.ts +++ b/packages/api/session-controller/src/client/sessions/manager.ts @@ -147,12 +147,7 @@ export class SessionManager { throw new Error(`sessions.retain: unknown session ${id}`) } if (address !== undefined) this.addresses.set(id, address) - this.sessions.get(id)?.configureSubagent( - address, - address === undefined - ? undefined - : this.agentAvailable(address.parentSessionId), - ) + this.sessions.get(id)?.configureSubagent(address) return id } @@ -276,14 +271,8 @@ export class SessionManager { private createSession(sessionId: SessionId): Session { const address = this.addresses.get(sessionId) - const parentAvailable = address === undefined - ? undefined - : this.agentAvailable(address.parentSessionId) return new Session(sessionId, this.remote, { - ...(address === undefined ? {} : { - address, - ...parentAvailable === undefined ? {} : { parentAvailable }, - }), + ...(address === undefined ? {} : { address }), // The sender's local first-send flip mirrors into the list row so the // session surfaces (lists filter on blank) before any host frame lands. onEngaged: (engaged) => { @@ -400,18 +389,6 @@ export class SessionManager { return operation } - private agentAvailable(sessionId: SessionId): boolean | undefined { - return this.summaries.find(summary => summary.sessionId === sessionId)?.agentAvailable - ?? (this.listPhase === 'ready' ? false : undefined) - } - - private updateParentAvailability(): void { - for (const [childId, address] of this.addresses) { - const available = this.agentAvailable(address.parentSessionId) - if (available !== undefined) this.sessions.get(childId)?.handleSubagentParentAvailable(available) - } - } - // ---- List API ---- /** Full refresh via session.list (single-flight within one Host generation). */ @@ -446,7 +423,7 @@ export class SessionManager { for (const sessionId of this.engagedSessions) this.pruneEngagement(sessionId, retained) this.listState = 'idle' this.listPhase = 'ready' - this.updateParentAvailability() + // Resident Sessions and list rows share one display blank, reconciled with the metadata projection. for (const s of this.summaries) { const session = this.sessions.get(s.sessionId) @@ -599,7 +576,6 @@ export class SessionManager { */ private mergeSummary(summary: SessionSummary): void { this.recordMutation({ kind: 'upsert', summary }) - this.updateParentAvailability() } /** Apply immediately and retain for replay when a list response is in flight. */ @@ -642,15 +618,17 @@ export class SessionManager { // ---- Live control and Host-event sinks ---- /** - * Apply a complete control baseline or one later replacement frame. - * @param frame - baseline or live control replacement from Session Controller. + * Apply a complete control baseline or one later per-event projection frame. + * @param frame - baseline or live per-event projection change from Session Controller. */ handleControlFrame(frame: SessionControlFrame): void { if (frame.type === 'baseline') { this.replaceControlBaseline(frame.value) return } - this.projectionStore(frame.sessionId).apply(frame.key, frame.value, SessionSeq(frame.seq)) + const store = this.projectionStore(frame.sessionId) + const seq = SessionSeq(frame.seq) + for (const change of frame.changes) store.apply(change.key, change.val, seq) this.notifier.markDirty() } @@ -719,11 +697,6 @@ export class SessionManager { this.projectionInflight.get(sessionId)?.controller.abort() this.projectionInflight.delete(sessionId) this.projectionLoads.delete(sessionId) - for (const [childId, address] of this.addresses) { - if (address.parentSessionId === sessionId) { - this.sessions.get(childId)?.handleSubagentParentAvailable(false) - } - } } /** @@ -734,7 +707,6 @@ export class SessionManager { handleSessionStatus(sessionId: SessionId, running: boolean): void { if (!this.disposed && running) this.engagedSessions.add(sessionId) this.recordMutation({ kind: 'status', sessionId, running, agentAvailable: true }) - this.updateParentAvailability() this.sessions.get(sessionId)?.handleRunning(running) } diff --git a/packages/api/session-controller/src/client/sessions/remotes.ts b/packages/api/session-controller/src/client/sessions/remotes.ts index 8e084384d4..bbe026bf4e 100644 --- a/packages/api/session-controller/src/client/sessions/remotes.ts +++ b/packages/api/session-controller/src/client/sessions/remotes.ts @@ -30,10 +30,8 @@ export interface SessionSubagentsRemote { request: SubagentPromptRequest, signal?: AbortSignal, ): Promise> - interruptByParent( + interruptByUser( childSessionId: SessionId, - parentSessionId: SessionId, - mode: 'continuable', ): Promise> } diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index 253da9c463..e74dd84422 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -71,8 +71,6 @@ interface PendingHistory { export interface SessionOptions { /** Catalog-discovered address selecting non-activating subagent transport. */ address?: SubagentAddress - /** Whether the exact direct parent Agent is available in Host summaries; absent until known. */ - parentAvailable?: boolean /** * Publish each accepted prompt to the Manager, including after this Session * object is replaced. Acceptance converts display state, but does not @@ -113,7 +111,6 @@ export class Session implements SessionFace { private readonly assistantStream = new ClientAssistantStream() private running = false private address: SubagentAddress | undefined - private parentAvailable: boolean | undefined /** * Sticky send marker, private input of the composerPhase derivation: set * when the Host accepts a prompt, never reset — the blank → engaging edge of @@ -193,7 +190,6 @@ export class Session implements SessionFace { ) { this.projections = options.projections ?? new ProjectionValueStore() this.address = options.address - this.parentAvailable = options.parentAvailable this.notifier = new Notifier(() => { this.snapshotCache = this.buildSnapshot() }) @@ -294,9 +290,7 @@ export class Session implements SessionFace { const routedContent = content as Exclude[] const routed = await this.remote.subagents.prompt({ requestId: requestId ?? randomUUID() as SessionRequestId, - parentSessionId: this.address.parentSessionId, childSessionId: this.address.childSessionId, - mode: 'continuable', delivery: mode, content: routedContent, clientTimeZone: resolvedClientTimeZone(), @@ -363,18 +357,14 @@ export class Session implements SessionFace { /** * Stop the active turn while the Host preserves pending inbox work; failures * land in promptError (same error-strip display slot). A subagent address - * routes through `subagents.interruptByParent`, whose durable parent-address - * authority works without a live parent Agent. + * routes through `subagents.interruptByUser`, authorized on the target Session + * without requiring a live parent Agent. * @returns the cancel result. */ async cancel(): Promise> { const address = this.address const result = address !== undefined - ? await this.remote.subagents.interruptByParent( - address.childSessionId, - address.parentSessionId, - 'continuable', - ) + ? await this.remote.subagents.interruptByUser(address.childSessionId) : await this.remote.session.cancel({ sessionId: this.sessionId }) if (!result.ok) { this.promptError = { op: 'stop', error: result.error } @@ -562,28 +552,16 @@ export class Session implements SessionFace { * Install or clear the catalog-discovered transport address. A changed * address rebuilds an already-open window through its new history route. * @param address - direct parent/child address, or undefined for ordinary transport. - * @param parentAvailable - latest exact-parent availability hint, or undefined before a catalog read. */ - configureSubagent(address: SubagentAddress | undefined, parentAvailable?: boolean): void { + configureSubagent(address: SubagentAddress | undefined): void { const same = this.address?.parentSessionId === address?.parentSessionId && this.address?.childSessionId === address?.childSessionId && this.address?.mode === address?.mode this.address = address - this.parentAvailable = parentAvailable if (!same && this.openState !== 'cold') void this.resync() else this.notifier.markDirty() } - /** - * Update only the parent availability hint from a catalog refresh. - * @param available - whether the exact direct parent is live. - */ - handleSubagentParentAvailable(available: boolean): void { - if (this.parentAvailable === available) return - this.parentAvailable = available - this.notifier.markDirty() - } - /** * Apply the Manager's effective display blank, further reconciled with the * current `sessionListMetadata` projection. Local send attempts and current @@ -934,7 +912,6 @@ export class Session implements SessionFace { address: this.address.mode === 'unknown' && identity != null ? { ...this.address, mode: identity.mode } : this.address, - ...(this.parentAvailable === undefined ? {} : { parentAvailable: this.parentAvailable }), }, removed: this.removed, openState: this.openState, diff --git a/packages/api/session-controller/src/commands.ts b/packages/api/session-controller/src/commands.ts index 5309872331..d306953c8c 100644 --- a/packages/api/session-controller/src/commands.ts +++ b/packages/api/session-controller/src/commands.ts @@ -409,7 +409,7 @@ export class SessionCommandController { } agent = found.agent } - if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) { + if (hasApiSessionSubagentOwner(agent.session)) { const identity = this.ctx.sessionProjections .snapshot(agent.session, ['subagent']) .values.subagent @@ -470,7 +470,7 @@ export class SessionCommandController { { sessionId: request.sessionId }, ) } - if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) { + if (hasApiSessionSubagentOwner(agent.session)) { throw apiSessionSubagentOwnershipError(request.sessionId) } agent.cancel({ kind: 'user' }, { keepInbox: true }) diff --git a/packages/api/session-controller/src/control.ts b/packages/api/session-controller/src/control.ts index 8d27396d29..7a9d04021e 100644 --- a/packages/api/session-controller/src/control.ts +++ b/packages/api/session-controller/src/control.ts @@ -5,11 +5,11 @@ import { Deque } from '@deepseek-ai/dsh-deque' import type { Session, SessionId, } from '@deepseek-ai/dsh-session' -import type { JsonValue } from '@deepseek-ai/dsh-util-values' import type { SessionControlBaseline, SessionControlFrame, SessionProjectionBaseline, + SessionProjectionUpdate, SessionProjectionValues, } from './types.ts' @@ -19,13 +19,13 @@ export class SessionControlController { /** @param ctx - Host context carrying live Agent and projection services. */ constructor(private readonly ctx: Context) { - ctx.sessionProjections.onChanged((session, key, value, seq) => { + ctx.sessionProjections.onEventChanged((session, changes, seq) => { this.broadcast({ type: 'projection', sessionId: session.id, - key, - value: value as JsonValue, seq, + // Every projection definition validates its value before change publication. + changes: changes as SessionProjectionUpdate['changes'], }) }) ctx.effect(() => () => { diff --git a/packages/api/session-controller/src/history/controller.ts b/packages/api/session-controller/src/history/controller.ts index d090f0a3f7..1899aff823 100644 --- a/packages/api/session-controller/src/history/controller.ts +++ b/packages/api/session-controller/src/history/controller.ts @@ -103,10 +103,10 @@ export class HistoryController { } /** - * Subscribe to sparse projection replacements without reading a baseline. + * Subscribe to projection changes without reading a baseline. * @param request - Session identity to subscribe without reading a baseline. * @param signal - stream cancellation. - * @returns readiness followed by sparse per-key replacement values. + * @returns readiness followed by one change frame per committed event, listing every key it changed. */ async *observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable { using listener = new ProjectionListener(this.ctx, request.sessionId, signal) diff --git a/packages/api/session-controller/src/history/listener.ts b/packages/api/session-controller/src/history/listener.ts index a272081620..cb41847dbf 100644 --- a/packages/api/session-controller/src/history/listener.ts +++ b/packages/api/session-controller/src/history/listener.ts @@ -5,7 +5,6 @@ import { Deque } from '@deepseek-ai/dsh-deque' import { SessionLogOffset } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent, SessionId } from '@deepseek-ai/dsh-session' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' -import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { entryFor } from '../history.ts' import type { SessionProjectionChange, SessionEventEntry } from '../types.ts' @@ -128,7 +127,7 @@ export function eventItem(item: EventItem, next?: number): { return { events, next } } -/** Sparse projection changes retain every key, including keys sharing a seq. */ +/** Projection changes of one Session, one change per committed event that changed a projection. */ export class ProjectionListener implements Disposable { private readonly buffer: ListenerBuffer<{ session: Session; change: SessionProjectionChange }> @@ -142,12 +141,12 @@ export class ProjectionListener implements Disposable { const input = this.buffer.createInput<{ session: Session; change: SessionProjectionChange }>(item => [item]) const target = sessionId try { - this.buffer.own(ctx.sessionProjections.onChanged((session, key, value, seq) => { + this.buffer.own(ctx.sessionProjections.onEventChanged((session, changes, seq) => { if (session.id !== target) return this.buffer.capture(() => { - input.append({ - session, change: { type: 'projection', key, value: value as JsonValue, seq } satisfies SessionProjectionChange, - }) + // Every projection definition validates its value before change publication. + const change: SessionProjectionChange = { type: 'projection', seq, changes: changes as SessionProjectionChange['changes'] } + input.append({ session, change }) }) })) } catch (error: unknown) { @@ -156,8 +155,8 @@ export class ProjectionListener implements Disposable { } } - /** Consume sparse per-key projection replacements. - * @returns validated replacement frames; projection seqs need not be contiguous. */ + /** Consume per-event projection changes. + * @returns validated change frames, one per committed event; projection seqs need not be contiguous. */ async *changes(): AsyncIterable { try { for await (const { change } of this.buffer.items()) { diff --git a/packages/api/session-controller/src/index.ts b/packages/api/session-controller/src/index.ts index 94d08c77e3..8e81986f0b 100644 --- a/packages/api/session-controller/src/index.ts +++ b/packages/api/session-controller/src/index.ts @@ -553,10 +553,10 @@ export class SessionController extends TypertRemoteService { } /** - * Subscribe to sparse Session projection changes. + * Subscribe to Session projection changes. * @param request - target Session. * @param signal - subscription cancellation. - * @returns readiness and sparse projection changes. + * @returns readiness followed by one projection change frame per committed event. */ @Remote({ mode: 'stream' }) observeProjections(request: SessionProjectionsRequest, signal: AbortSignal): AsyncIterable { diff --git a/packages/api/session-controller/src/types.ts b/packages/api/session-controller/src/types.ts index 9e399d8f3b..6c3c737cb6 100644 --- a/packages/api/session-controller/src/types.ts +++ b/packages/api/session-controller/src/types.ts @@ -569,12 +569,21 @@ export interface SessionControlBaseline { readonly projections: Readonly> } -/** One finished projection value and its durable watermark. */ +/** + * Projection changes caused by one committed Session event; the Host emits one + * update per event that changed at least one client-visible projection view. + */ export interface SessionProjectionUpdate { readonly sessionId: SessionId - readonly key: string - readonly value: JsonValue + /** Seq of the committed event that caused every listed change. */ readonly seq: number + /** + * One entry per client-visible key whose view the event changed, in + * registration order without duplicate keys, with the key's new value as + * `val`. A key absent from `changes` is unchanged; unlike a baseline, absence + * does not mean an absent capability. + */ + readonly changes: readonly { readonly key: string; readonly val: SessionProjectionValue }[] } /** Host-wide live state stream. Each generation starts with exactly one baseline. */ @@ -652,10 +661,10 @@ export type SessionEventFrame = | { readonly type: 'ready' } | SessionEventEntry -/** One sparse per-key replacement; different keys can share a seq. */ +/** Projection changes caused by one committed event of the observed Session. */ export type SessionProjectionChange = { readonly type: 'projection' } & Omit -/** Subscription readiness without a baseline, followed by per-key changes. */ +/** Subscription readiness without a baseline, followed by one change frame per committed event. */ export type SessionProjectionFrame = | { readonly type: 'ready' } | SessionProjectionChange diff --git a/packages/api/session-controller/tests/control-queue.host.spec.ts b/packages/api/session-controller/tests/control-queue.host.spec.ts index ad24ad94fb..fee05cb585 100644 --- a/packages/api/session-controller/tests/control-queue.host.spec.ts +++ b/packages/api/session-controller/tests/control-queue.host.spec.ts @@ -52,10 +52,15 @@ describe('Session control Inbox projection', () => { for (;;) { const next = await iterator.next() if (next.done) throw new Error('stream ended before an Inbox value') - if (next.value.type === 'projection' && next.value.key === 'inbox') return next.value + if (next.value.type === 'projection' && next.value.changes.some(change => change.key === 'inbox')) return next.value } } + /** The Inbox value one projection frame carries. */ + function inboxValue(frame: Extract): unknown { + return frame.changes.find(change => change.key === 'inbox')?.val + } + it('projects both pending lists in baselines and live replacement frames', async () => { const { control, inbox } = await harness() const queued = message('queued') @@ -82,10 +87,10 @@ describe('Session control Inbox projection', () => { const replacement = message('replacement') inbox.append('next-turn', replacement) const replaced = await nextInboxFrame(iterator) - expect(replaced.value).toMatchObject({ 'next-turn': [queued, replacement] }) + expect(inboxValue(replaced)).toMatchObject({ 'next-turn': [queued, replacement] }) inbox.remove(steering.id) const removed = await nextInboxFrame(iterator) - expect(removed.value).toMatchObject({ 'next-step': [context] }) + expect(inboxValue(removed)).toMatchObject({ 'next-step': [context] }) abort.abort() await iterator.next() @@ -109,8 +114,7 @@ describe('Session control Inbox projection', () => { await expect(iterator.next()).resolves.toMatchObject({ value: { type: 'projection', - key: 'inbox', - value: { 'next-turn': [{ id: pending.id }], 'next-step': [] }, + changes: [{ key: 'inbox', val: { 'next-turn': [{ id: pending.id }], 'next-step': [] } }], }, }) @@ -167,9 +171,9 @@ describe('Session control Inbox projection', () => { target: 'next-turn', start: 0, inserted: [pending], }) expect(ctx.agents.get(session.id)).toBeUndefined() - await expect(nextInboxFrame(iterator)).resolves.toMatchObject({ - sessionId: session.id, value: { 'next-turn': [pending], 'next-step': [] }, - }) + const frame = await nextInboxFrame(iterator) + expect(frame.sessionId).toBe(session.id) + expect(inboxValue(frame)).toMatchObject({ 'next-turn': [pending], 'next-step': [] }) abort.abort() await iterator.next() }) @@ -197,14 +201,14 @@ describe('Session control Inbox projection', () => { inbox.append('next-turn', first) inbox.append('next-turn', second) - const values: InboxState[] = [] + const values: unknown[] = [] ownedContexts.delete(ctx) await ctx.fiber.dispose() for (;;) { const next = await iterator.next() if (next.done) break - if (next.value.type === 'projection' && next.value.key === 'inbox') values.push(next.value.value as unknown as InboxState) + if (next.value.type === 'projection' && next.value.changes.some(change => change.key === 'inbox')) values.push(inboxValue(next.value)) } - expect(values.map(value => value['next-turn'].map(item => item.id))).toEqual([[first.id], [first.id, second.id]]) + expect(values).toMatchObject([{ 'next-turn': [{ id: first.id }] }, { 'next-turn': [{ id: first.id }, { id: second.id }] }]) }) }) diff --git a/packages/api/session-controller/tests/history-controller.host.spec.ts b/packages/api/session-controller/tests/history-controller.host.spec.ts index e3592ddbad..1f71f48e5e 100644 --- a/packages/api/session-controller/tests/history-controller.host.spec.ts +++ b/packages/api/session-controller/tests/history-controller.host.spec.ts @@ -40,19 +40,22 @@ describe('HistoryController passive reads', () => { expect(await stream.next()).toMatchObject({ done: true }) }) - it('subscribes to sparse projection changes without an Observation', async () => { + it('subscribes to per-event projection changes without an Observation', async () => { const f = await fixture() const observe = vi.spyOn(f.ctx.sessionQuery, 'observeSession') - let receive: Parameters[0] | undefined + let receive: Parameters[0] | undefined const dispose = vi.fn() - vi.spyOn(f.ctx.sessionProjections, 'onChanged').mockImplementation((callback) => { + vi.spyOn(f.ctx.sessionProjections, 'onEventChanged').mockImplementation((callback) => { receive = callback return dispose }) const stream = f.history.observeProjections({ sessionId: f.session.id }, f.abort.signal)[Symbol.asyncIterator]() expect(await stream.next()).toMatchObject({ value: { type: 'ready' } }) - receive?.(f.session, 'title', 'new title', SessionSeq(0)) - expect(await stream.next()).toMatchObject({ value: { type: 'projection', key: 'title', value: 'new title', seq: 0 } }) + receive?.(f.session, [{ key: 'title', val: 'new title' }, { key: 'goal', val: null }], SessionSeq(0)) + expect(await stream.next()).toEqual({ + done: false, + value: { type: 'projection', seq: 0, changes: [{ key: 'title', val: 'new title' }, { key: 'goal', val: null }] }, + }) expect(observe).not.toHaveBeenCalled() f.abort.abort() expect(await stream.next()).toMatchObject({ done: true }) diff --git a/packages/api/session-controller/tests/inbox-projection.client.spec.ts b/packages/api/session-controller/tests/inbox-projection.client.spec.ts index 0522c8db35..6e3c9b0bed 100644 --- a/packages/api/session-controller/tests/inbox-projection.client.spec.ts +++ b/packages/api/session-controller/tests/inbox-projection.client.spec.ts @@ -34,9 +34,8 @@ function inboxFrame(value: InboxState): Extract detachAgent, 'list-scheduling.agent') agents.set(id, agent) detach.set(id, () => { detachAgent(); detachSession() }) diff --git a/packages/api/session-controller/tests/listeners.host.spec.ts b/packages/api/session-controller/tests/listeners.host.spec.ts index 34207efb3c..d8f97b9244 100644 --- a/packages/api/session-controller/tests/listeners.host.spec.ts +++ b/packages/api/session-controller/tests/listeners.host.spec.ts @@ -178,17 +178,20 @@ describe('EventListener', () => { }) describe('ProjectionListener', () => { - it('emits sparse changes only for the selected Session', async () => { + it('emits one change per event only for the selected Session', async () => { const { ctx, session, abort } = await fixture() - let receive!: Parameters[0] + let receive!: Parameters[0] const dispose = vi.fn() - vi.spyOn(ctx.sessionProjections, 'onChanged').mockImplementation((listener) => { receive = listener; return dispose }) + vi.spyOn(ctx.sessionProjections, 'onEventChanged').mockImplementation((listener) => { receive = listener; return dispose }) using listener = new ProjectionListener(ctx, session.id, abort.signal) const other = ctx.sessions.create(SessionId('other')) - receive(other, 'subagent', null, SessionSeq(0)) - receive(session, 'subagent', null, SessionSeq(1)) + receive(other, [{ key: 'subagent', val: null }], SessionSeq(0)) + receive(session, [{ key: 'subagent', val: null }, { key: 'title', val: 'renamed' }], SessionSeq(1)) const changes = listener.changes()[Symbol.asyncIterator]() - expect(await changes.next()).toMatchObject({ value: { type: 'projection', key: 'subagent', value: null, seq: 1 } }) + expect(await changes.next()).toEqual({ + done: false, + value: { type: 'projection', seq: 1, changes: [{ key: 'subagent', val: null }, { key: 'title', val: 'renamed' }] }, + }) abort.abort() expect(await changes.next()).toMatchObject({ done: true }) expect(dispose).toHaveBeenCalledOnce() @@ -197,7 +200,7 @@ describe('ProjectionListener', () => { it('releases its buffer when projection subscription fails', async () => { const { ctx, session, abort } = await fixture() const remove = vi.spyOn(abort.signal, 'removeEventListener') - vi.spyOn(ctx.sessionProjections, 'onChanged').mockImplementation(() => { throw new Error('projection subscribe failed') }) + vi.spyOn(ctx.sessionProjections, 'onEventChanged').mockImplementation(() => { throw new Error('projection subscribe failed') }) expect(() => new ProjectionListener(ctx, session.id, abort.signal)).toThrow('projection subscribe failed') expect(remove).toHaveBeenCalled() }) diff --git a/packages/api/session-controller/tests/manager.client.spec.ts b/packages/api/session-controller/tests/manager.client.spec.ts index 9661f66a01..4e64470548 100644 --- a/packages/api/session-controller/tests/manager.client.spec.ts +++ b/packages/api/session-controller/tests/manager.client.spec.ts @@ -378,9 +378,9 @@ describe('SessionManager instances', () => { const stopObserving = manager.subscribe(() => { published.resolve(undefined) }) try { manager.handleControlFrame({ type: 'projection', sessionId: S1, - key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 1200 }, seq: 8 }) + changes: [{ key: 'sessionListMetadata', val: { blank: false, lastPromptAt: 1200 } }], seq: 8 }) manager.handleControlFrame({ type: 'projection', sessionId: S2, - key: 'sessionListMetadata', value: { blank: true, lastPromptAt: null }, seq: 2 }) + changes: [{ key: 'sessionListMetadata', val: { blank: true, lastPromptAt: null } }], seq: 2 }) // The initial notification must finish while neither Session is resident. await published.promise @@ -427,7 +427,7 @@ describe('SessionManager query lifetime', () => { const entries = [{ id: S2, createdAt: 1, mode: 'one-shot' as const }] try { if (warm) { - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 0, value: entries }) + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'subagentCatalog', val: entries }], seq: 0 }) } remote.session.projections.mockRejectedValueOnce(failure) await manager.refreshProjections(S1) @@ -446,9 +446,9 @@ describe('list lifecycle', () => { const manager = makeManager(mock, remote) try { manager.handleControlFrame({ type: 'projection', sessionId: S1, - key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 1200 }, seq: 8 }) + changes: [{ key: 'sessionListMetadata', val: { blank: false, lastPromptAt: 1200 } }], seq: 8 }) manager.handleControlFrame({ type: 'projection', sessionId: S2, - key: 'sessionListMetadata', value: { blank: true, lastPromptAt: null }, seq: 2 }) + changes: [{ key: 'sessionListMetadata', val: { blank: true, lastPromptAt: null } }], seq: 2 }) remote.session.list.mockResolvedValue(ok({ items: [ summary(S1, { blank: true }), summary(S2), ] as never[] })) @@ -457,7 +457,7 @@ describe('list lifecycle', () => { expect(manager.get(S1).getSnapshot().blank).toBe(false) expect(manager.get(S2).getSnapshot().blank).toBe(false) manager.handleControlFrame({ type: 'projection', sessionId: S1, - key: 'sessionListMetadata', value: { blank: true, lastPromptAt: null }, seq: 7 }) + changes: [{ key: 'sessionListMetadata', val: { blank: true, lastPromptAt: null } }], seq: 7 }) expect(manager.getListSnapshot().items[0]).toMatchObject({ blank: false, updatedAt: 1200 }) } finally { await manager.dispose() @@ -614,7 +614,7 @@ describe('list lifecycle', () => { it('retains title projections before list arrival, keeps last-wins by seq, and clears them on removal', async ({ mock, remote }) => { const manager = makeManager(mock, remote) const titleFrame = (title: string, seq: number) => { - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'title', value: title, seq }) + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'title', val: title }], seq }) } titleFrame('Newest', 4) titleFrame('Stale', 3) @@ -634,11 +634,34 @@ describe('list lifecycle', () => { expect(manager.getListSnapshot().items.find(item => item.sessionId === S1)?.title).toBeUndefined() }) + it('applies every key of one per-event frame with one list invalidation and per-key seq gating', async ({ mock, remote }) => { + remote.session.list.mockResolvedValue(ok({ items: [summary(S1, { blank: true })] as never[] })) + const manager = makeManager(mock, remote) + onTestFinished(() => manager.dispose()) + await manager.refreshList() + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'title', val: 'Newest' }], seq: 4 }) + await new Promise(resolve => setTimeout(resolve, 0)) + // Bracket access reaches the private list notifier; projection-store notifiers stay out of the count. + const markDirty = vi.spyOn(manager['notifier'], 'markDirty') + + manager.handleControlFrame({ + type: 'projection', sessionId: S1, seq: 3, changes: [ + { key: 'title', val: 'Stale' }, + { key: 'sessionListMetadata', val: { blank: false, lastPromptAt: 1200 } }, + ], + }) + expect(markDirty).toHaveBeenCalledOnce() + await new Promise(resolve => setTimeout(resolve, 0)) + + expect(manager.getListSnapshot().items[0]).toMatchObject({ sessionId: S1, title: 'Newest', blank: false }) + expect(manager.projectionValues(S1)).toMatchObject({ sessionListMetadata: { blank: false, lastPromptAt: 1200 } }) + }) + it('fills cold titles from the list rows\' projections block as cached values', async ({ mock, remote }) => { const manager = makeManager(mock, remote) // A push frame landed before the list: S2's title is a sequenced value. manager.handleControlFrame({ - type: 'projection', sessionId: S2, key: 'title', value: 'Pushed', seq: 9, + type: 'projection', sessionId: S2, changes: [{ key: 'title', val: 'Pushed' }], seq: 9, }) remote.session.list.mockResolvedValue(ok({ items: [ @@ -660,7 +683,7 @@ describe('list lifecycle', () => { const manager = makeManager(mock, remote) try { await manager.refreshList() - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'title', value: 'Unflushed', seq: 4 }) + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'title', val: 'Unflushed' }], seq: 4 }) manager.handleConnected() await manager.refreshList() @@ -738,7 +761,7 @@ describe('subagent catalogs', () => { const manager = makeManager(mock, remote) onTestFinished(() => manager.dispose()) const entries = [{ id: S2, createdAt: 1, mode: 'external' as const, label: 'external task' }] - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 0, value: entries }) + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'subagentCatalog', val: entries }], seq: 0 }) expect(manager.getListSnapshot().projectionsBySession[S1]?.values.subagentCatalog).toEqual(entries) expect(manager.subagentAddress(S2)).toBeUndefined() @@ -750,8 +773,9 @@ describe('subagent catalogs', () => { onTestFinished(() => manager.dispose()) manager.handleSessionAdded(summary(S2, { parentSessionId: S1, origin: 'subagent' })) manager.handleControlFrame({ - type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 0, - value: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }], + type: 'projection', sessionId: S1, seq: 0, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }] }, + ], }) expect(manager.subagentAddress(S2)).toEqual({ @@ -838,7 +862,6 @@ describe('subagent catalogs', () => { address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable', }, - parentAvailable: true, }) // Clicking the same child through an ordinary list-selection path must not // erase the catalog-derived address and fall back to session.* transport. @@ -850,7 +873,6 @@ describe('subagent catalogs', () => { address: { parentSessionId: S1, childSessionId: S2, mode: 'continuable', }, - parentAvailable: true, }) await manager.get(S2).open() await manager.get(S2).prompt([{ type: 'text', text: 'continue' }], 'queue') @@ -871,8 +893,7 @@ describe('subagent catalogs', () => { expect(remote.subagents.prompt.mock.calls.map(([request]) => request)).toEqual([ { requestId: expect.any(String) as unknown as string, - parentSessionId: S1, childSessionId: S2, - mode: 'continuable', + childSessionId: S2, delivery: 'queue', content: [{ type: 'text', text: 'continue' }], clientTimeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone, @@ -906,14 +927,17 @@ describe('subagent catalogs', () => { const client = await start() const manager = new SessionManager(client.ctx.remote) const entries = [{ id: S2, createdAt: 1, mode: 'unknown' as const }] - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 0, value: entries }) + manager.handleControlFrame({ type: 'projection', sessionId: S1, changes: [{ key: 'subagentCatalog', val: entries }], seq: 0 }) const address = manager.subagentAddress(S2)! expect(address).toEqual({ parentSessionId: S1, childSessionId: S2, mode: 'unknown' }) manager.resolveTarget(address) const child = manager.get(S2) expect(child.getSnapshot().subagent?.address.mode).toBe('unknown') - manager.handleControlFrame({ type: 'projection', sessionId: S2, key: 'subagent', seq: 0, - value: { seq: SessionSeq(0), mode: 'continuable', label: 'repaired child' } }) + manager.handleControlFrame({ + type: 'projection', sessionId: S2, seq: 0, changes: [ + { key: 'subagent', val: { seq: SessionSeq(0), mode: 'continuable', label: 'repaired child' } }, + ], + }) await child.open() expect(child.getSnapshot().subagent?.address).toEqual({ ...address, mode: 'continuable' }) expect(manager.getListSnapshot().projectionsBySession[S1]?.values.subagentCatalog).toEqual(entries) @@ -924,8 +948,9 @@ describe('subagent catalogs', () => { const manager = makeManager(mock, remote) manager.handleSessionAdded(summary(S2, { origin: 'subagent', parentSessionId: S1, running: true })) manager.handleControlFrame({ - type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 4, - value: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }], + type: 'projection', sessionId: S1, seq: 4, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }] }, + ], }) expect(manager.getListSnapshot().projectionsBySession[S1]?.values.subagentCatalog).toEqual([ { id: S2, createdAt: 1, mode: 'continuable', label: 'worker' }, @@ -1008,8 +1033,9 @@ describe('subagent catalogs', () => { const manager = makeManager(mock, remote) const read = manager.refreshProjections(S1) manager.handleControlFrame({ - type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 5, - value: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'pushed' }], + type: 'projection', sessionId: S1, seq: 5, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'continuable', label: 'pushed' }] }, + ], }) response.resolve(ok({ kind: 'sequenced', asOfSeq: 3, values: { subagentCatalog: [] } })) await read @@ -1032,43 +1058,16 @@ describe('subagent catalogs', () => { expect(remote.session.projections).toHaveBeenCalledTimes(2) }) - it.for([false, true])('keeps live parent availability when an earlier initial read settles (failure: %s)', async (failure, { mock, remote }) => { - const response = Promise.withResolvers>>() - remote.session.projections.mockImplementation(() => response.promise) - const manager = makeManager(mock, remote) - manager.resolveTarget({ parentSessionId: S1, childSessionId: S2, mode: 'continuable' }) - const child = manager.get(S2) - const read = manager.refreshProjections(S1) - manager.handleSessionAdded(summary(S1)) - manager.handleSessionStatus(S1, false) - response.resolve(failure - ? err(new RemoteError('gateway/internal', 'offline', {})) - : ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [] } })) - await read - expect(child.getSnapshot().subagent?.parentAvailable).toBe(true) - expect(remote.session.projections.mock.calls.map(([request]) => request)).toHaveLength(1) - }) - - it('keeps parent availability unknown after list failure and accepts a later Host summary', async ({ mock, remote }) => { - const manager = makeManager(mock, remote) - manager.resolveTarget({ parentSessionId: S1, childSessionId: S2, mode: 'continuable' }) - const child = manager.get(S2) - remote.session.list.mockResolvedValue(err(new RemoteError('gateway/internal', 'offline', {}))) - await manager.refreshList() - expect(manager.getListSnapshot().state).toBe('error') - expect(child.getSnapshot().subagent?.parentAvailable).toBeUndefined() - manager.handleSessionAdded(summary(S1)) - expect(child.getSnapshot().subagent?.parentAvailable).toBe(true) - await manager.dispose() - }) - it('keeps a pushed catalog when an earlier initial read reports the parent missing', async ({ mock, remote }) => { const response = Promise.withResolvers>>() remote.session.projections.mockImplementation(() => response.promise) const manager = makeManager(mock, remote) const read = manager.refreshProjections(S1) - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 1, - value: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }) + manager.handleControlFrame({ + type: 'projection', sessionId: S1, seq: 1, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }, + ], + }) response.resolve(ok(null)) await read expect(manager.getListSnapshot().projectionsBySession[S1]?.values.subagentCatalog).toEqual([ @@ -1117,9 +1116,12 @@ describe('subagent catalogs', () => { it('keeps completed unselected child metadata with its durable catalog row', ({ mock, remote }) => { const manager = makeManager(mock, remote) manager.handleSessionAdded(summary(S2, { origin: 'subagent', parentSessionId: S1, running: true })) - manager.handleControlFrame({ type: 'projection', sessionId: S2, key: 'title', value: 'finished child', seq: 2 }) - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 1, - value: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }) + manager.handleControlFrame({ type: 'projection', sessionId: S2, changes: [{ key: 'title', val: 'finished child' }], seq: 2 }) + manager.handleControlFrame({ + type: 'projection', sessionId: S1, seq: 1, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }, + ], + }) manager.handleSessionRemoved(S2) expect(manager.getListSnapshot().items[0]).toMatchObject({ title: 'finished child', running: false }) expect(manager.getListSnapshot().items.find(item => item.sessionId === S2)?.running).toBe(false) @@ -1134,8 +1136,11 @@ describe('subagent catalogs', () => { it('retries a failed initial read without discarding pushed entries', async ({ mock, remote }) => { remote.session.projections.mockImplementation(() => Promise.resolve(err(new RemoteError('gateway/internal', 'offline', {})))) const manager = makeManager(mock, remote) - manager.handleControlFrame({ type: 'projection', sessionId: S1, key: 'subagentCatalog', seq: 2, - value: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }) + manager.handleControlFrame({ + type: 'projection', sessionId: S1, seq: 2, changes: [ + { key: 'subagentCatalog', val: [{ id: S2, createdAt: 1, mode: 'one-shot' }] }, + ], + }) await manager.refreshProjections(S1) expect(manager.getListSnapshot().projectionsBySession[S1]).toMatchObject({ state: 'error', values: { subagentCatalog: [{ id: S2 }] } }) remote.session.projections.mockImplementation(() => Promise.resolve(ok({ kind: 'sequenced', asOfSeq: 2, values: { subagentCatalog: [] } }))) @@ -1222,23 +1227,6 @@ describe('remaining branches', () => { await manager.dispose() }) - it('preserves Host availability when a local create echo follows Agent disposal', async ({ mock, remote }) => { - const response = Promise.withResolvers>>() - remote.session.create.mockImplementation(() => response.promise) - const manager = makeManager(mock, remote) - manager.resolveTarget({ - parentSessionId: S1, childSessionId: S2, mode: 'continuable', - }) - const child = manager.get(S2) - const request = manager.create() - manager.handleSessionAdded(summary(S1, { agentAvailable: false })) - response.resolve(ok({ sessionId: S1 })) - await request - manager.resolveTarget(S2) - expect(child.getSnapshot().subagent?.parentAvailable).toBe(false) - await manager.dispose() - }) - it('publishes a real Ungrouped summary from workspace-attach-failed', async ({ mock, remote }) => { remote.session.create.mockResolvedValue(err(new RemoteError('session/workspace-attach-failed', 'published but unattached', { sessionId: S1, workspaceId: 'w1', @@ -1593,7 +1581,6 @@ describe('connected generation', () => { }) expect(manager.get(S2).getSnapshot().subagent).toEqual({ address, - parentAvailable: true, }) expect(manager.subagentAddress(S2)).toEqual(address) }) diff --git a/packages/api/session-controller/tests/projection-store.client.spec.ts b/packages/api/session-controller/tests/projection-store.client.spec.ts index ab1e185744..3c0d196c80 100644 --- a/packages/api/session-controller/tests/projection-store.client.spec.ts +++ b/packages/api/session-controller/tests/projection-store.client.spec.ts @@ -228,13 +228,13 @@ describe('manager frame routing', () => { it('lands projection frames before instantiation and the Session adopts the same store', ({ mock, remote }) => { const manager = makeManager(mock, remote) manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['early'] }, seq: 7, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'test/marks', val: { marks: ['early'] } }], seq: 7, }) const session = manager.get(sid('s1')) expect(session.projections.get('test/marks')).toEqual({ marks: ['early'] }) // Frames after instantiation land in the same store. manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'test/marks', value: { marks: ['later'] }, seq: 9, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'test/marks', val: { marks: ['later'] } }], seq: 9, }) expect(session.projections.get('test/marks')).toEqual({ marks: ['later'] }) }) @@ -246,7 +246,7 @@ describe('manager frame routing', () => { })) await manager.refreshList() manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Projected title', seq: 4, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'title', val: 'Projected title' }], seq: 4, }) await Promise.resolve() expect(manager.getListSnapshot().items[0]?.title).toBe('Projected title') @@ -318,7 +318,7 @@ describe('manager frame routing', () => { // A frame past the block's watermark still advances it. manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Frame title', seq: 41, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'title', val: 'Frame title' }], seq: 41, }) await Promise.resolve() expect(manager.getListSnapshot().items[0]?.title).toBe('Frame title') @@ -342,8 +342,8 @@ describe('manager frame routing', () => { expect(manager.getListSnapshot().items[0]?.projectionValues).toBe(baseline) manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'test/marks', - value: { marks: ['live'] }, seq: 3, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'test/marks', val: { marks: ['live'] } }], + seq: 3, }) await Promise.resolve() expect(manager.getListSnapshot().items[0]?.projectionValues) @@ -358,10 +358,12 @@ describe('manager frame routing', () => { })) await manager.refreshList() manager.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Doomed', seq: 4, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'title', val: 'Doomed' }], seq: 4, }) if (catalog !== undefined) { - manager.handleControlFrame({ type: 'projection', sessionId: sid('s1'), key: 'subagentCatalog', value: catalog, seq: 4 }) + manager.handleControlFrame({ + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'subagentCatalog', val: catalog }], seq: 4, + }) } manager.handleSessionRemoved(sid('s1')) expect(manager.getListSnapshot().projectionsBySession[sid('s1')]).toBeUndefined() diff --git a/packages/api/session-controller/tests/remote-access.host.spec.ts b/packages/api/session-controller/tests/remote-access.host.spec.ts index 8be0dac78e..a11b157b1b 100644 --- a/packages/api/session-controller/tests/remote-access.host.spec.ts +++ b/packages/api/session-controller/tests/remote-access.host.spec.ts @@ -239,7 +239,7 @@ describe('Session Controller access', () => { for (;;) { const next = await iterator.next() if (next.done === true) throw new Error('control stream ended') - if (next.value.type === 'projection' && next.value.key === 'inbox') return next.value.sessionId + if (next.value.type === 'projection' && next.value.changes.some(change => change.key === 'inbox')) return next.value.sessionId } } // The owner sees the private Session's frame first; the guest's first Inbox frame is the shared one. diff --git a/packages/api/session-controller/tests/remote/bench.client.ts b/packages/api/session-controller/tests/remote/bench.client.ts index 6e0f10d569..a696fd0c28 100644 --- a/packages/api/session-controller/tests/remote/bench.client.ts +++ b/packages/api/session-controller/tests/remote/bench.client.ts @@ -11,7 +11,7 @@ import { sessionWorld } from './session.client.ts' * @param mock - this case's Remote responses. * @param start - the fixture's lazy client startup. * @param sessionId - Session identity. - * @param options - addressed child and parent availability, when applicable. + * @param options - addressed child and other Session options, when applicable. * @returns the Session, disposed at the end of the case. */ export async function sessionBench( diff --git a/packages/api/session-controller/tests/remote/session.client.ts b/packages/api/session-controller/tests/remote/session.client.ts index f920d1592e..c4d8049177 100644 --- a/packages/api/session-controller/tests/remote/session.client.ts +++ b/packages/api/session-controller/tests/remote/session.client.ts @@ -147,7 +147,7 @@ export const sessionWorld: RemoteTable = { 'session/page': pageRule(ok({ cursor: -1, records: [], hasMore: false })), 'session/projections': ok({ kind: 'sequenced', asOfSeq: -1, values: { subagentCatalog: [] } }), 'subagents/prompt': ok({ messageId: 'fake-message' }), - 'subagents/interruptByParent': ok({ accepted: true }), + 'subagents/interruptByUser': ok({ accepted: true }), }, stream: { 'session/follow': followScript(ok({ cursor: -1, records: [], hasMore: false })), diff --git a/packages/api/session-controller/tests/session-cold.host.spec.ts b/packages/api/session-controller/tests/session-cold.host.spec.ts index 560c05514f..e5f721d37d 100644 --- a/packages/api/session-controller/tests/session-cold.host.spec.ts +++ b/packages/api/session-controller/tests/session-cold.host.spec.ts @@ -672,10 +672,10 @@ describe('subagent ownership fence', () => { await ctx.agents.register(originChild) const startingSession = ctx.sessions.create(sid('session-starting-child'), { - meta: { cwd: '/proj', parentSession: parent.id }, + meta: { cwd: '/proj', parentSession: parent.id, origin: 'subagent' }, }) const startingChild = { id: startingSession.id, session: startingSession, status: 'idle', ctx } as Agent - ctx.agents.enter(startingChild, parent) + ctx.agents.enter(startingChild) const remote = await createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'p', model: 'm' }), cwd: '/tmp' }) const stopped = await remote.cancel(request({ sessionId: originChild.id })) diff --git a/packages/api/session-controller/tests/session-projections.host.spec.ts b/packages/api/session-controller/tests/session-projections.host.spec.ts index db37e8bcb8..89dc6d6963 100644 --- a/packages/api/session-controller/tests/session-projections.host.spec.ts +++ b/packages/api/session-controller/tests/session-projections.host.spec.ts @@ -360,7 +360,7 @@ describe('session.history projections block', () => { await new Promise(resolve => setTimeout(resolve, 0)) await expect(next).resolves.toMatchObject({ done: false, - value: { type: 'projection', key: 'sessionListMetadata' }, + value: { type: 'projection', changes: [{ key: 'sessionListMetadata' }] }, }) const extra = iterator.next() const quiet = Symbol('quiet') @@ -418,7 +418,7 @@ describe('session.history projections block', () => { const changed = await iterator.next() expect(changed).toMatchObject({ done: false, - value: { type: 'projection', key: 'sessionListMetadata' }, + value: { type: 'projection', changes: [{ key: 'sessionListMetadata' }] }, }) abort.abort() await iterator.return?.() @@ -752,16 +752,16 @@ describe('Session control projection frames', () => { return frames } - it('broadcasts changed view references with the causing seq and skips same-reference applies', async () => { + it('broadcasts one frame per event listing changed views in registration order and skips same-reference applies', async () => { const { ctx, session } = await harness(true) await ctx.sessionProjections.register(lastUserUnit()) const proxy = await remote(ctx) - // The controller's onChanged subscription lives in an inject child whose + // The controller's onEventChanged subscription lives in an inject child whose // fiber activates asynchronously; yield until it lands before appending. await new Promise(resolve => setTimeout(resolve, 0)) const abort = new AbortController() const stream = proxy.control(abort.signal) - const collected = collect(stream, 5, abort) + const collected = collect(stream, 3, abort) const now = vi.spyOn(Date, 'now').mockReturnValue(100) seedMessages(session, 1) @@ -773,24 +773,56 @@ describe('Session control projection frames', () => { now.mockRestore() const frames = await collected - const pushes = frames.filter( - (f): f is Extract => - f.type === 'projection' && f.key === 'test/last-user', - ) + const pushes = frames.filter((f): f is Extract => f.type === 'projection') expect(pushes).toEqual([ - { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 0 }, - { type: 'projection', sessionId: session.id, key: 'test/last-user', value: { text: 'm0' }, seq: 2 }, - ]) - expect(frames.filter( - (f): f is Extract => - f.type === 'projection' && f.key === 'sessionListMetadata', - )).toEqual([ - { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: true, lastPromptAt: 100 }, seq: 0 }, - { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 100 }, seq: 1 }, - { type: 'projection', sessionId: session.id, key: 'sessionListMetadata', value: { blank: false, lastPromptAt: 300 }, seq: 2 }, + { + type: 'projection', sessionId: session.id, seq: 0, changes: [ + { key: 'test/last-user', val: { text: 'm0' } }, + { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + ], + }, + { + type: 'projection', sessionId: session.id, seq: 1, changes: [ + { key: 'sessionListMetadata', val: { blank: false, lastPromptAt: 100 } }, + ], + }, + { + type: 'projection', sessionId: session.id, seq: 2, changes: [ + { key: 'test/last-user', val: { text: 'm0' } }, + { key: 'sessionListMetadata', val: { blank: false, lastPromptAt: 300 } }, + ], + }, ]) // Frame seq aligns with the tail block's asOfSeq vocabulary (higher-seq-wins compatible). const tail = await opening(proxy, session.id) expect(tail.projections.asOfSeq).toBe(pushes.at(-1)?.seq) }) + + it('streams one observeProjections change per event for the observed Session only', async () => { + const { ctx, session } = await harness(true) + await ctx.sessionProjections.register(lastUserUnit()) + const proxy = await remote(ctx) + await new Promise(resolve => setTimeout(resolve, 0)) + const other = ctx.sessions.create(undefined, { meta: { cwd: '/workspace' } }) + const abort = new AbortController() + const changes = proxy.observeProjections({ sessionId: session.id }, abort.signal)[Symbol.asyncIterator]() + expect(await changes.next()).toEqual({ done: false, value: { type: 'ready' } }) + + const now = vi.spyOn(Date, 'now').mockReturnValue(100) + seedMessages(other, 1) + seedMessages(session, 1) + now.mockRestore() + + expect(await changes.next()).toEqual({ + done: false, + value: { + type: 'projection', seq: 0, changes: [ + { key: 'test/last-user', val: { text: 'm0' } }, + { key: 'sessionListMetadata', val: { blank: true, lastPromptAt: 100 } }, + ], + }, + }) + abort.abort() + expect(await changes.next()).toEqual({ done: true, value: undefined }) + }) }) diff --git a/packages/api/session-controller/tests/session-remote-rejection.client.spec.ts b/packages/api/session-controller/tests/session-remote-rejection.client.spec.ts index a6e7a274aa..2fb870f910 100644 --- a/packages/api/session-controller/tests/session-remote-rejection.client.spec.ts +++ b/packages/api/session-controller/tests/session-remote-rejection.client.spec.ts @@ -7,21 +7,28 @@ */ import { describe, expect, it } from 'vitest' import type { SessionId } from '@deepseek-ai/dsh-api-remotes/client' +import { RemoteMock } from '@deepseek-ai/dsh-remote-mock' import { Session } from '../src/client/sessions/session.ts' import type { SessionRemotes } from '../src/client/sessions/remotes.ts' const SID = 'fk-s1' as SessionId const PARENT = 'fk-parent' as SessionId -/** Every command rejects with `message`; nothing else on the face is reachable from prompt or cancel. */ +/** Calls used by Session prompt and cancel reject with `message`. */ function rejecting(message: string): SessionRemotes { const reject = (): Promise => Promise.reject(new Error(message)) + const { remote } = RemoteMock.create() + remote.commands.execute.mockImplementation(reject) + remote.session.prompt.mockImplementation(reject) + remote.session.cancel.mockImplementation(reject) + remote.subagents.prompt.mockImplementation(reject) + remote.subagents.interruptByUser.mockImplementation(reject) return { $stream: () => { throw new Error('unused') }, - commands: { execute: reject }, - session: { prompt: reject, cancel: reject }, - subagents: { list: reject, prompt: reject, interruptByParent: reject }, - } as unknown as SessionRemotes + commands: remote.commands, + session: remote.session, + subagents: remote.subagents, + } } describe('Session over a rejecting Remote face', () => { @@ -35,7 +42,6 @@ describe('Session over a rejecting Remote face', () => { it('propagates the rejection from a subagent continuation prompt and interrupt', async () => { const session = new Session(SID, rejecting('assembly fault'), { address: { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' }, - parentAvailable: true, }) await expect(session.prompt([{ type: 'text', text: 'x' }], 'queue')).rejects.toThrow('assembly fault') await expect(session.cancel()).rejects.toThrow('assembly fault') diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index 70c69ca033..e118ef29e5 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -474,7 +474,7 @@ describe('prompt and cancel errors', () => { const CHILD = { parentSessionId: PARENT, childSessionId: SID, mode: 'continuable' } as const it('routes an addressed child through non-activating history, continuation prompt, and interrupt only', async ({ mock, start }) => { - const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) + const session = await sessionBench(mock, start, SID, { address: CHILD }) await session.open() const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue') const steered = await session.prompt([{ type: 'text', text: '现在处理' }], 'steer') @@ -491,34 +491,34 @@ describe('prompt and cancel errors', () => { expect(mock.log.requests('subagents/prompt')).toEqual([ { requestId: expect.any(String) as unknown as string, - ...CHILD, + childSessionId: SID, delivery: 'queue', content: [{ type: 'text', text: '继续' }], clientTimeZone: TIME_ZONE, }, { requestId: expect.any(String) as unknown as string, - ...CHILD, + childSessionId: SID, delivery: 'steer', content: [{ type: 'text', text: '现在处理' }], clientTimeZone: TIME_ZONE, }, ]) // Positional parameters cross the wire as positional args. - expect(mock.log.calls('subagents/interruptByParent').map(call => call.args)).toEqual([[SID, PARENT, 'continuable']]) + expect(mock.log.calls('subagents/interruptByUser').map(call => call.args)).toEqual([[SID]]) expect(mock.log.requests('session/prompt')).toEqual([]) expect(mock.log.requests('session/cancel')).toEqual([]) // A successful interrupt leaves no stop error behind. expect(session.getSnapshot().promptError).toBeNull() - expect(session.getSnapshot().subagent).toEqual({ address: CHILD, parentAvailable: true }) + expect(session.getSnapshot().subagent).toEqual({ address: CHILD }) }) it('sends an addressed child continuation under its echo request id and retires a refused echo', async ({ mock, start }) => { - const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) + const session = await sessionBench(mock, start, SID, { address: CHILD }) await session.open() const accepted = session.beginSubmission({ mode: 'queue', text: '继续', attachments: [] }) await session.prompt([{ type: 'text', text: '继续' }], 'queue', undefined, accepted.requestId) - expect(mock.log.requests('subagents/prompt')).toMatchObject([{ requestId: accepted.requestId, ...CHILD }]) + expect(mock.log.requests('subagents/prompt')).toMatchObject([{ requestId: accepted.requestId, childSessionId: SID }]) expect(session.getSnapshot().pendingSubmissions.map(echo => echo.requestId)).toEqual([accepted.requestId]) const refused = session.beginSubmission({ mode: 'queue', text: '附件', attachments: [] }) @@ -527,7 +527,7 @@ describe('prompt and cancel errors', () => { }) it('forwards continuation image parts to the subagent prompt Remote unstripped', async ({ mock, start }) => { - const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) + const session = await sessionBench(mock, start, SID, { address: CHILD }) await session.open() const content = [ { type: 'text' as const, text: '看这张图' }, @@ -539,7 +539,7 @@ describe('prompt and cancel errors', () => { expect(mock.log.requests('subagents/prompt')).toEqual([ { requestId: expect.any(String) as unknown as string, - ...CHILD, + childSessionId: SID, delivery: 'queue', content, clientTimeZone: TIME_ZONE, @@ -549,18 +549,18 @@ describe('prompt and cancel errors', () => { }) it('lands an interrupt business failure in promptError with op=stop', async ({ mock, start }) => { - const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) - mock.remote.subagents.interruptByParent.mockResolvedValue(err(new RemoteError('subagent/unauthorized', 'nope', { childSessionId: SID }))) + const session = await sessionBench(mock, start, SID, { address: CHILD }) + mock.remote.subagents.interruptByUser.mockResolvedValue(err(new RemoteError('remote-access/denied', 'nope', { action: 'subagents/interruptByUser', reason: 'no-allow' }))) await session.open() const cancelled = await session.cancel() - expect(cancelled).toMatchObject({ ok: false, error: { code: 'subagent/unauthorized' } }) + expect(cancelled).toMatchObject({ ok: false, error: { code: 'remote-access/denied' } }) expect(session.getSnapshot().promptError).toMatchObject({ - op: 'stop', error: { code: 'subagent/unauthorized' }, + op: 'stop', error: { code: 'remote-access/denied' }, }) }) it('rejects staged files instead of dropping them from subagent continuations', async ({ mock, start }) => { - const session = await sessionBench(mock, start, SID, { address: CHILD, parentAvailable: true }) + const session = await sessionBench(mock, start, SID, { address: CHILD }) await session.open() const prompted = await session.prompt([ @@ -578,7 +578,7 @@ describe('prompt and cancel errors', () => { expect(mock.log.requests('subagents/prompt')).toEqual([]) }) - it('sends a one-shot address to the Host under the continuable marker', async ({ mock, start }) => { + it('lets the Host validate the target continuation state', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID, { address: { ...CHILD, mode: 'one-shot' } }) mock.remote.subagents.prompt.mockResolvedValue(err(new RemoteError( 'subagent/not-resumable', 'subagent cannot be resumed', { childSessionId: SID }, @@ -587,11 +587,10 @@ describe('prompt and cancel errors', () => { const prompted = await session.prompt([{ type: 'text', text: '继续' }], 'queue') const cancelled = await session.cancel() - // The Host reads the durable descriptor; the wire marker stays 'continuable'. expect(prompted).toMatchObject({ ok: false, error: { code: 'subagent/not-resumable' } }) expect(cancelled).toEqual({ ok: true, value: { accepted: true } }) - expect(mock.log.requests('subagents/prompt')).toMatchObject([CHILD]) - expect(mock.log.calls('subagents/interruptByParent').map(call => call.args)).toEqual([[SID, PARENT, 'continuable']]) + expect(mock.log.requests('subagents/prompt')).toMatchObject([{ childSessionId: SID }]) + expect(mock.log.calls('subagents/interruptByUser').map(call => call.args)).toEqual([[SID]]) expect(mock.log.requests(FOLLOW)).toEqual([ { address: { kind: 'subagent', ...CHILD, mode: 'one-shot' }, activate: true, assistantStream: true, maxMessages: 500, turnWindow: { minMessages: 50, minTurns: 2 } }, ]) diff --git a/packages/api/session-controller/tests/sessions-service.client.spec.ts b/packages/api/session-controller/tests/sessions-service.client.spec.ts index 212320fdf6..4301be69d6 100644 --- a/packages/api/session-controller/tests/sessions-service.client.spec.ts +++ b/packages/api/session-controller/tests/sessions-service.client.spec.ts @@ -107,7 +107,7 @@ describe('list store projection', () => { it('projects durable titles separately from cwd/id display fallbacks and parent links', async ({ bench }) => { const b = bench() b.svc.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'title', value: 'Durable title', seq: 2, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'title', val: 'Durable title' }], seq: 2, }) await feedList(b, [ { id: 's1', cwd: '/home/u/proj-a/' }, @@ -128,7 +128,7 @@ describe('list store projection', () => { expect(b.svc.list.getSnapshot().byId[sid('s1')]?.projectionValues?.agentPreset).toBe('standard') b.svc.handleControlFrame({ - type: 'projection', sessionId: sid('s1'), key: 'agentPreset', value: 'minimal', seq: 1, + type: 'projection', sessionId: sid('s1'), changes: [{ key: 'agentPreset', val: 'minimal' }], seq: 1, }) await Promise.resolve() @@ -784,7 +784,7 @@ describe('catalog-addressed navigation', () => { it(`loads an unretained one-shot child with projected title ${String(title)}`, async ({ bench }) => { const b = bench() if (title !== undefined) b.svc.handleControlFrame({ - type: 'projection', sessionId: sid('one-shot'), key: 'title', value: title, seq: 2, + type: 'projection', sessionId: sid('one-shot'), changes: [{ key: 'title', val: title }], seq: 2, }) b.mock.remote.session.projections.mockResolvedValue(ok({ kind: 'sequenced', asOfSeq: 0, values: { subagentCatalog: [{ id: sid('one-shot'), createdAt: 1, mode: 'one-shot' }] }, @@ -984,7 +984,7 @@ describe('fork', () => { ] as const)('increments the durable title %j after the child is published', async ([sourceTitle, childTitle], { bench }) => { const b = bench() b.svc.handleControlFrame({ - type: 'projection', sessionId: sid('source'), key: 'title', value: sourceTitle, seq: 2, + type: 'projection', sessionId: sid('source'), changes: [{ key: 'title', val: sourceTitle }], seq: 2, }) await feedList(b, [{ id: 'source', cwd: '/work' }]) b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') })) @@ -1035,7 +1035,7 @@ describe('fork', () => { it('rejects child rename failure while preserving its catalog row without retaining the child', async ({ bench }) => { const b = bench() b.svc.handleControlFrame({ - type: 'projection', sessionId: sid('source'), key: 'title', value: 'Roadmap', seq: 2, + type: 'projection', sessionId: sid('source'), changes: [{ key: 'title', val: 'Roadmap' }], seq: 2, }) await feedList(b, [{ id: 'source' }]) b.mock.remote.session.fork.mockResolvedValue(ok({ sessionId: sid('child') })) diff --git a/packages/api/session-controller/tests/subagent-access.host.spec.ts b/packages/api/session-controller/tests/subagent-access.host.spec.ts new file mode 100644 index 0000000000..ad077c695b --- /dev/null +++ b/packages/api/session-controller/tests/subagent-access.host.spec.ts @@ -0,0 +1,128 @@ +/** Target Session permissions are enforced before subagent input or cancellation is admitted. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import TypertGatewayService from '@deepseek-ai/dsh-api-gateway' +import type { RemoteAccessBinding } from '@deepseek-ai/dsh-api-remote-access' +import { SessionId } from '@deepseek-ai/dsh-session' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import SubagentRuntime from '@deepseek-ai/dsh-subagent' +import type { PeerId, PeerScope, Principal } from '@deepseek-ai/dsh-typert-protocol' +import TypertRegistry from '@deepseek-ai/dsh-typert-registry' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { MockAdapter } from '../../../core/agent-loop/tests/mock-adapter.ts' +import { mountWorkingDirectoryFixture } from '../../../subagent/subagent/tests/working-directory-fixture.ts' +import { createSessionTestController } from './test-remote.ts' + +declare module '@deepseek-ai/dsh-typert-protocol' { + interface PrincipalMap { + /** Test-only non-owner caller shared by the access specs. */ + 'test-guest': { readonly kind: 'test-guest'; readonly guest: string } + } +} + +const GUEST: Principal = { kind: 'test-guest', guest: 'subagent-controls' } +const ACTIONS = ['subagents/prompt', 'subagents/interruptByUser'] as const +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + for (const cleanup of cleanups.splice(0).reverse()) await cleanup() +}) + +async function harness() { + const root = await mkdtemp(join(tmpdir(), 'dsh-subagent-access-')) + const ctx = new Context() + cleanups.push(async () => { + try { await ctx.fiber.dispose() } finally { await rm(root, { recursive: true, force: true }) } + }) + await ctx.plugin(TypertRegistry) + await mountAgentLoopTestDependencies(ctx) + await ctx.plugin(JsonlSessionPersistence, { root }) + await ctx.plugin(AgentLoop, { agents: [] }) + await mountWorkingDirectoryFixture(ctx) + await createSessionTestController(ctx, { defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: root }) + await ctx.plugin(SubagentRuntime) + ctx.subagents.registerProvider({ + name: 'test', inheritsParentContext: false, + capabilities: { agentOptions: true, agentPreset: false, outputSchema: false, depthLimit: false }, + prepareContinuable: async () => ({}), + }) + const adapter = new MockAdapter(['hang']) + ctx.llm.registerAdapter(['mock'], adapter) + const parent = await ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' }) + const run = await ctx.subagents.startActivation({ + provider: 'test', label: 'access target', delivery: 'caller', + parent, prompt: [{ type: 'text', text: 'hold' }], + signal: new AbortController().signal, + }) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + const child = ctx.agents.get(run.childId)! + await ctx.plugin(TypertGatewayService) + const bindings: RemoteAccessBinding[] = [] + ctx.remoteAccess.registerPolicy('test-guest', { bindings: () => bindings }) + const call = (method: 'prompt' | 'interruptByUser', principal: Principal = GUEST, image = false) => { + const peer: PeerScope = { + id: 'subagent-access-peer' as PeerId, ctx, principal, interactions: 'answer', + signal: new AbortController().signal, dispose: async () => {}, + } + return ctx.typertGateway.invoke({ + peer, namespace: 'subagents', method, + args: method === 'prompt' ? { request: { + requestId: 'access-follow-up', childSessionId: child.id, delivery: 'queue', + content: image ? [{ type: 'image', mediaType: 'image/png', data: 'aGk=' }] : [{ type: 'text', text: 'follow-up' }], + } } : { childSessionId: child.id }, + }) + } + return { ctx, parent, child, bindings, call } +} + +describe('subagent target Session access', () => { + it.each(['prompt', 'interruptByUser'] as const)('requires the target permission for %s', async (method) => { + const { ctx, parent, child, bindings, call } = await harness() + const attachments = vi.spyOn(ctx.attachments, 'admitPromptContent') + const observe = vi.spyOn(ctx.sessionQuery, 'observeSession') + const cancel = vi.spyOn(child, 'cancel') + const grants: RemoteAccessBinding[][] = [ + [], + [{ role: { name: 'global controls', resource: 'global', actions: ACTIONS }, resource: { kind: 'global' } }], + [{ role: { name: 'parent controls', resource: 'session', actions: ACTIONS }, resource: { kind: 'session', id: parent.id } }], + [{ role: { name: 'other control', resource: 'session', actions: [method === 'prompt' ? ACTIONS[1] : ACTIONS[0]] }, resource: { kind: 'session', id: child.id } }], + ] + for (const grant of grants) { + bindings.splice(0, bindings.length, ...grant) + await expect(call(method, GUEST, true)).rejects.toMatchObject({ + code: 'remote-access/denied', details: { action: `subagents/${method}`, reason: 'no-allow' }, + }) + } + expect(attachments).not.toHaveBeenCalled() + expect(observe).not.toHaveBeenCalled() + expect(cancel).not.toHaveBeenCalled() + expect(child.inbox.nextTurn).toHaveLength(0) + + bindings.splice(0, bindings.length, { + role: { name: 'target control', resource: 'session', actions: [`subagents/${method}`] }, + resource: { kind: 'session', id: child.id }, + }) + const accepted = await call(method) + if (method === 'prompt') { + expect(child.inbox.nextTurn).toHaveLength(1) + expect(accepted).toEqual({ messageId: child.inbox.nextTurn[0]?.id }) + expect(child.inbox.nextTurn[0]?.source).toMatchObject({ kind: 'user', principal: GUEST }) + } else { + expect(accepted).toEqual({ accepted: true }) + expect(cancel).toHaveBeenCalledWith({ kind: 'user' }, { keepInbox: true }) + await child.whenIdle() + } + }) + + it('allows the owner without target bindings', async () => { + const { child, call } = await harness() + const accepted = await call('prompt', { kind: 'owner' }) + expect(child.inbox.nextTurn).toHaveLength(1) + expect(accepted).toEqual({ messageId: child.inbox.nextTurn[0]?.id }) + await expect(call('interruptByUser', { kind: 'owner' })).resolves.toEqual({ accepted: true }) + await child.whenIdle() + }) +}) diff --git a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts index 36216a1f1c..0f834506d9 100644 --- a/packages/api/session-controller/tests/subagent-catalog.host.spec.ts +++ b/packages/api/session-controller/tests/subagent-catalog.host.spec.ts @@ -77,12 +77,15 @@ describe('SessionController subagent catalog', () => { version: 0, childId: CHILD, childCreatedAt: 8, mode: 'continuable', label: 'worker', }) let frame = await stream.next() - while (!frame.done && !(frame.value.type === 'projection' && frame.value.key === 'subagentCatalog' - && Array.isArray(frame.value.value) && frame.value.value.length === 1)) { + let catalog = frame.done || frame.value.type !== 'projection' + ? undefined : frame.value.changes.find(change => change.key === 'subagentCatalog')?.val + while (!frame.done && !(Array.isArray(catalog) && catalog.length === 1)) { frame = await stream.next() + catalog = frame.done || frame.value.type !== 'projection' + ? undefined : frame.value.changes.find(change => change.key === 'subagentCatalog')?.val } - expect(frame.value).toMatchObject({ type: 'projection', sessionId: PARENT, key: 'subagentCatalog', - value: [{ id: CHILD, createdAt: 8, mode: 'continuable', label: 'worker' }] }) + expect(frame.value).toMatchObject({ type: 'projection', sessionId: PARENT }) + expect(catalog).toMatchObject([{ id: CHILD, createdAt: 8, mode: 'continuable', label: 'worker' }]) } finally { signal.abort() await stream.return?.() diff --git a/packages/api/session-controller/tests/test-remote.ts b/packages/api/session-controller/tests/test-remote.ts index 145b48f5c3..04ed6788cf 100644 --- a/packages/api/session-controller/tests/test-remote.ts +++ b/packages/api/session-controller/tests/test-remote.ts @@ -62,6 +62,7 @@ import type { SessionSelectModelRequest, SessionSelectModelValue, SessionProjectionsRequest, + SessionProjectionFrame, SessionUpdateQueueRequest, SessionUpdateQueueValue, } from '../src/types.ts' @@ -90,6 +91,7 @@ export interface TestSessionRemote { page(request: SessionPageRequest, signal?: AbortSignal): Promise> projections(request: SessionProjectionsRequest, signal?: AbortSignal): Promise> follow(request: SessionFollowRequest, signal?: AbortSignal): AsyncIterable + observeProjections(request: SessionProjectionsRequest, signal?: AbortSignal): AsyncIterable control(signal?: AbortSignal): AsyncIterable } @@ -397,6 +399,7 @@ export async function createSessionTestRemote( signal, ), follow: (request, signal = new AbortController().signal) => direct.follow(request, signal), + observeProjections: (request, signal = new AbortController().signal) => direct.observeProjections(request, signal), control: (signal = new AbortController().signal) => direct.control(signal), } } diff --git a/packages/api/session-controller/tests/transport.client.spec.ts b/packages/api/session-controller/tests/transport.client.spec.ts index 2c60701f80..db0857e5b7 100644 --- a/packages/api/session-controller/tests/transport.client.spec.ts +++ b/packages/api/session-controller/tests/transport.client.spec.ts @@ -83,7 +83,7 @@ function sessionClient(remote: SessionTransportRemote): SessionRemotes { commands: { execute: () => Promise.reject(new Error('stream tests never run commands')) }, subagents: { prompt: () => Promise.reject(new Error('stream tests never prompt a subagent')), - interruptByParent: () => Promise.reject(new Error('stream tests never interrupt a subagent')), + interruptByUser: () => Promise.reject(new Error('stream tests never interrupt a subagent')), }, } } @@ -669,7 +669,7 @@ describe('Session Client stream adapters', () => { value: { projections: {} }, } const update: SessionControlFrame = { - type: 'projection', sessionId: 'session-1' as never, key: 'title', value: 'updated', seq: 1, + type: 'projection', sessionId: 'session-1' as never, changes: [{ key: 'title', val: 'updated' }], seq: 1, } const remote = new ScriptedSessionRemote([], [], [baseline, update]) const accept = vi.fn<(frame: SessionControlFrame) => void>() diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index 9ce0beae8e..98cb511540 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-app-boot/use-this-package: - en: f6fa378225009c8f - zh: 324c0e4640bb1358 + en: 8e42ac55d685e0f1 + zh: e9e8804af1b2df2b /deepseek-ai-dsh-app-boot/use-this-package/when-to-use-it: en: 2fdfe02f2ed4a258 zh: d748228ece579c4a diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 4d30457f81..46fc9be865 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -27,6 +27,8 @@ English | [中文](README.zh.md) Starting an app with this package is a small, explicit entry point: you give it a config file and it runs the whole boot. This section covers what you can do and what you get; the helper calls behind each outcome are documented in the folded implementation section. +Profile loading removes retired installation-bundle selections from `dsh.profile.bundles` and rewrites the manifest only when needed, preserving other fields. [Team migration](../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.md) describes the default composition and retained row overrides. + ### When to use it Use it when implementing the shared `dsh` launcher or embedding its lower-level boot helpers. Product features belong in profile bundles instead of new application bins; code that only adds plugins to an already-running app mounts those plugins directly. diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index a4d8554ca5..1bc7234f55 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -27,6 +27,8 @@ kind: "package-library" 用此包启动应用是一个小而显式的入口:你给它一个配置文件,它运行整个启动过程。本节说明你能做什么、能得到什么;每个结果背后的 helper 调用记录在下方可折叠的实现章节中。 +profile 加载时会从 `dsh.profile.bundles` 移除已停用的安装方 bundle 选项,仅在需要时重写 manifest,保留其他字段。[Team 迁移](../../../docs/upgrade-guide/v0.2.1-rc.2/session-team-mode/guide.zh.md)说明默认组合与保留的行覆盖。 + ### 何时使用 在实现共享 `dsh` launcher 或嵌入其低层启动 helper 时使用它。产品功能应放入 profile 组合包,而不是新增应用 bin;只向已运行应用添加插件的代码直接挂载插件即可。 diff --git a/packages/boot/app-boot/tests/profile.spec.ts b/packages/boot/app-boot/tests/profile.spec.ts index 0a67d476e1..238f316dc9 100644 --- a/packages/boot/app-boot/tests/profile.spec.ts +++ b/packages/boot/app-boot/tests/profile.spec.ts @@ -394,13 +394,13 @@ describe('loadProfile', () => { ]) }) - it('removes a retired bundle from an application-owned profile and keeps the rest of the manifest', () => { + it.each(['@deepseek-ai/dsh-experimental-schedule-bundle', '@deepseek-ai/dsh-experimental-agent-team-profile'])('removes retired %s and keeps the rest of an application-owned manifest', (retired) => { const anchor = stageInstallation({ '@deepseek-ai/dsh-base': { patch: '[]\n' }, 'custom-bundle': { patch: '[]\n' }, }) const dir = join(tmp(), 'app-profile') - initProfile(dir, ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-experimental-schedule-bundle', 'custom-bundle']) + initProfile(dir, ['@deepseek-ai/dsh-base', retired, 'custom-bundle']) writeProfileManifest(dir, { ...readProfileManifest('t', dir), dependencies: { 'custom-bundle': '^1.0.0' } }) const profile = loadProfileDirectory('t', dir, anchor) expect(profile.skippedBundles).toEqual([]) diff --git a/packages/boot/plugin-market/tests/repository-cache.spec.ts b/packages/boot/plugin-market/tests/repository-cache.spec.ts index bb57767bc3..9b9e77803c 100644 --- a/packages/boot/plugin-market/tests/repository-cache.spec.ts +++ b/packages/boot/plugin-market/tests/repository-cache.spec.ts @@ -1,4 +1,4 @@ -/** Partial clones of real local repositories: reads, README lookup, limits, eviction, and Git failures. */ +/** Partial clones of real local repositories: reads, README lookup, limits, eviction, and Git failures, including a stalled Git fixture. */ import { execFileSync } from 'node:child_process' import { createHash, randomBytes } from 'node:crypto' import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs' @@ -17,6 +17,7 @@ async function expectRejection(promise: Promise, fields: object, messag let root: string +const caches: RepositoryCache[] = [] const lifetime = new AbortController() const signal = new AbortController().signal const text = (bytes: Uint8Array | undefined): string => new TextDecoder().decode(bytes) @@ -28,16 +29,20 @@ beforeEach(() => { vi.stubEnv('HOME', join(root, 'home')) vi.stubEnv('XDG_CONFIG_HOME', join(root, 'home')) }) -afterEach(() => { +afterEach(async () => { + await Promise.all(caches.splice(0).map(repositories => repositories.settled())) vi.unstubAllEnvs() vi.unstubAllGlobals() rmSync(root, { recursive: true, force: true }) }) function git(cwd: string, ...args: string[]): string { - // Fixture repositories ignore inherited Git overrides, such as a hook's `GIT_DIR`, and every user or system configuration. + // Fixture Git ignores inherited overrides and user configuration. Background maintenance stays disabled. const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith('GIT_'))) - return execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', '-c', 'commit.gpgsign=false', ...args], { + return execFileSync('git', [ + '-c', 'user.name=t', '-c', 'user.email=t@example.com', '-c', 'commit.gpgsign=false', + '-c', 'gc.auto=0', '-c', 'maintenance.auto=false', ...args, + ], { cwd, encoding: 'utf8', env: { ...env, HOME: join(root, 'home'), XDG_CONFIG_HOME: join(root, 'home'), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, }).trim() @@ -73,10 +78,12 @@ function repository(name: string, files: Record): { } function cache(options: Partial = {}): RepositoryCache { - return new RepositoryCache({ + const repositories = new RepositoryCache({ dir: join(root, 'cache'), maxRepositoryBytes: 10 * 1024 * 1024, maxCacheBytes: 100 * 1024 * 1024, timeoutMs: 30_000, ttlMs: 60_000, transports: ['file', 'ssh'], lifetime: lifetime.signal, sizePollMs: 1, ...options, }) + caches.push(repositories) + return repositories } it('reads files at a pinned commit and the default branch, fetching contents only when read', async () => { @@ -132,7 +139,7 @@ it('asks the smart HTTP endpoint without credentials whether a repository is pub expect(fetch).toHaveBeenCalledTimes(5) }) -it('reports an unreachable host as a network failure, a failed local command as a plain error, and a Git that cannot run', async () => { +it('reports an unreachable host as a network failure, a failed local command as a plain error, and a missing Git', async () => { vi.stubEnv('GIT_SSH_COMMAND', 'ssh -F /dev/null -o BatchMode=yes -o ConnectTimeout=5') await expectRejection(cache().read('ssh://127.0.0.1:1/owner/repo.git', undefined, 'README.md', 100, signal), { reason: 'network' }, 'git fetch') const source = repository('t', { 'README.md': 'x' }) @@ -149,15 +156,31 @@ it('reports an unreachable host as a network failure, a failed local command as await expect(broken).rejects.toThrow('git update-ref') await expect(broken).rejects.not.toBeInstanceOf(DetailFailure) expect(readdirSync(join(root, 'cache'))).toEqual([]) - // Git that cannot answer `git --version` within the deadline cannot run. const other = repository('t2', { 'README.md': 'x' }) - await expectRejection(cache({ timeoutMs: 1 }).read(other.url, other.commit, 'README.md', 100, signal), { reason: 'git-unavailable' }, 'timed out') vi.stubEnv('PATH', join(root, 'no-git')) const missing = cache().read(other.url, other.commit, 'README.md', 100, signal) await expectRejection(missing, { reason: 'git-unavailable' }, 'git --version') expect(readdirSync(join(root, 'cache'))).toEqual([]) }) +it('reports a stalled Git version check as unavailable before initializing a clone', async () => { + const bin = join(root, 'stalled-git') + const script = join(bin, 'stall.cjs') + mkdirSync(bin) + writeFileSync(script, 'setInterval(() => {}, 1000)\n') + vi.stubEnv('PLUGIN_MARKET_TEST_NODE', process.execPath) + vi.stubEnv('PLUGIN_MARKET_TEST_GIT_SCRIPT', script) + writeFileSync(join(bin, process.platform === 'win32' ? 'git.cmd' : 'git'), process.platform === 'win32' + ? '@"%PLUGIN_MARKET_TEST_NODE%" "%PLUGIN_MARKET_TEST_GIT_SCRIPT%"\r\n' + : '#!/bin/sh\nexec "$PLUGIN_MARKET_TEST_NODE" "$PLUGIN_MARKET_TEST_GIT_SCRIPT"\n', { mode: 0o755 }) + vi.stubEnv('PATH', bin) + const repositories = cache({ timeoutMs: 100 }) + const stalled = repositories.read('https://git.example/stalled.git', undefined, 'README.md', 100, signal) + await expectRejection(stalled, { reason: 'git-unavailable' }, 'timed out') + await expect(stalled).rejects.toThrow('git --version') + expect(readdirSync(join(root, 'cache'))).toEqual([]) +}) + it('reports a repository Git cannot fetch as denied', async () => { const repositories = cache() const missing = pathToFileURL(join(root, 'missing')).href diff --git a/packages/bundle/base/README.i18n.yaml b/packages/bundle/base/README.i18n.yaml index c6f661f22d..8c6ebd500c 100644 --- a/packages/bundle/base/README.i18n.yaml +++ b/packages/bundle/base/README.i18n.yaml @@ -21,8 +21,8 @@ en: 0f971f7ac7c09139 zh: ceb866da681c709c /deepseek-ai-dsh-base/use-this-package/what-you-get: - en: 2ef2653d55107eec - zh: 4936c0fff94b1984 + en: 94430c891006526d + zh: 94ba771960ec6f71 /deepseek-ai-dsh-base/use-this-package/shell-tools-per-platform: en: 2dce12f82d6ee955 zh: d4599eb899a3cd88 diff --git a/packages/bundle/base/README.md b/packages/bundle/base/README.md index f928d433d6..db77c345ec 100644 --- a/packages/bundle/base/README.md +++ b/packages/bundle/base/README.md @@ -51,6 +51,8 @@ Out of the box, every profile built on this core provides: a DeepSeek model conn Both `subagent` and `subagent_fork` create managed children and return a child id immediately. Use `send_message` to steer active children or continue their conversations after completion. [Delegation-tool behavior](../../subagent/tool-subagent/README.md) describes result delivery and backend capabilities. +The bundle also mounts [Agent Teams](../../team/agent-team/README.md) and its task tools. Team mode defaults off per root Session; the root conversation’s **Use Agent Teams** menu switch enables collaboration for that tree without changing the profile. + The built-in `working_directory` tool changes the directory for subsequent operations while existing processes and write permissions remain independent. Current directory information appears in user context. Default file editing uses `read`, `write`, and `edit`. The `str_replace_editor` tool remains available as an explicit opt-in. To add it to a base-backed profile, put this entry in the profile, home, or invocation patch: ```yaml diff --git a/packages/bundle/base/README.zh.md b/packages/bundle/base/README.zh.md index 132a40bab3..53c04f4b52 100644 --- a/packages/bundle/base/README.zh.md +++ b/packages/bundle/base/README.zh.md @@ -51,6 +51,8 @@ kind: "package-bundle" `subagent` 与 `subagent_fork` 都创建受管理的子任务,并立即返回 child id。使用 `send_message` 可引导活跃子任务,或在完成后继续其对话。[委派工具行为](../../subagent/tool-subagent/README.zh.md)说明了结果交付和后端能力。 +此 bundle 还挂载 [Agent Teams](../../team/agent-team/README.zh.md) 及其任务工具。每个根 Session 的 Team 模式默认关闭;根会话菜单中的**使用智能体团队**开关为当前树开启协作,无需修改 profile。 + 内置 `working_directory` 工具改变后续操作使用的目录,已有进程与写权限保持独立。当前目录信息出现在用户上下文中。默认文件编辑使用 `read`、`write` 和 `edit`。`str_replace_editor` 工具仍可显式启用。要将它加入基于 base 的 profile,请在 profile、home 或逐次调用 patch 中添加以下条目: ```yaml diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 863d194bf5..6740234ade 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -291,9 +291,13 @@ - id: fs-observation-policy name: '@deepseek-ai/dsh-fs-observation-policy' + disabled: true - id: tool-fs name: '@deepseek-ai/dsh-tool-fs' + config: + # Set false to drop the apply_patch tool beside edit. + applyPatch: true - id: tool-fs-search name: '@deepseek-ai/dsh-tool-fs-search' @@ -359,6 +363,14 @@ - id: subagent name: '@deepseek-ai/dsh-subagent' + - id: agent-team + name: '@deepseek-ai/dsh-agent-team' + config: + maxTasks: 256 + + - id: tool-agent-team + name: '@deepseek-ai/dsh-tool-agent-team' + - id: subagent-spawn-in-process name: '@deepseek-ai/dsh-subagent-spawn-in-process' config: diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index 6c6e508732..68a395af92 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -34,13 +34,16 @@ } }, "dependencies": { - "@deepseek-ai/dsh-hmr": "workspace:*", "@deepseek-ai/cordis-plugin-timer": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-agent-default-model": "workspace:*", + "@deepseek-ai/dsh-agent-instructions": "workspace:*", "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*", + "@deepseek-ai/dsh-api-gateway": "workspace:*", + "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-attachment-local": "workspace:*", - "@deepseek-ai/dsh-shell-env": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", "@deepseek-ai/dsh-bash-sandbox": "workspace:*", "@deepseek-ai/dsh-command-compact": "workspace:*", "@deepseek-ai/dsh-command-feedback": "workspace:*", @@ -49,24 +52,29 @@ "@deepseek-ai/dsh-compaction-basic": "workspace:*", "@deepseek-ai/dsh-compaction-image-offload": "workspace:*", "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", + "@deepseek-ai/dsh-config-editor": "workspace:*", "@deepseek-ai/dsh-credentials-local": "workspace:*", + "@deepseek-ai/dsh-deepseek-account-platform": "workspace:*", "@deepseek-ai/dsh-deepseek-llm-api-extensions": "workspace:*", - "@deepseek-ai/dsh-plugin-package-inventory-deepseek": "workspace:*", "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", "@deepseek-ai/dsh-fs-sandbox": "workspace:*", "@deepseek-ai/dsh-goal": "workspace:*", "@deepseek-ai/dsh-goal-round-driver": "workspace:*", - "@deepseek-ai/dsh-api-gateway": "workspace:*", - "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@deepseek-ai/dsh-hmr": "workspace:*", + "@deepseek-ai/dsh-jobs-local": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", "@deepseek-ai/dsh-llm-deepseek-account": "workspace:*", + "@deepseek-ai/dsh-llm-deepseek-api-key": "workspace:*", "@deepseek-ai/dsh-llm-pi-ai": "workspace:*", "@deepseek-ai/dsh-llm-retry": "workspace:*", "@deepseek-ai/dsh-mcp-resources": "workspace:*", + "@deepseek-ai/dsh-otel": "workspace:*", "@deepseek-ai/dsh-permission-presets": "workspace:*", "@deepseek-ai/dsh-plan-mode": "workspace:*", + "@deepseek-ai/dsh-plugin-manager": "workspace:*", + "@deepseek-ai/dsh-plugin-package-inventory-deepseek": "workspace:*", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", "@deepseek-ai/dsh-pwsh-sandbox": "workspace:*", "@deepseek-ai/dsh-repeat-tool-reminder": "workspace:*", "@deepseek-ai/dsh-sandbox-local": "workspace:*", @@ -81,6 +89,8 @@ "@deepseek-ai/dsh-session-telemetry-otel": "workspace:*", "@deepseek-ai/dsh-session-title": "workspace:*", "@deepseek-ai/dsh-session-title-first-prompt-llm": "workspace:*", + "@deepseek-ai/dsh-settings": "workspace:*", + "@deepseek-ai/dsh-shell-env": "workspace:*", "@deepseek-ai/dsh-skill": "workspace:*", "@deepseek-ai/dsh-skill-filesystem": "workspace:*", "@deepseek-ai/dsh-spill-local": "workspace:*", @@ -93,44 +103,36 @@ "@deepseek-ai/dsh-subagent-spawn-in-process": "workspace:*", "@deepseek-ai/dsh-subprocess-local": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/dsh-jobs-local": "workspace:*", - "@deepseek-ai/dsh-tool-call-timeout-policy": "workspace:*", "@deepseek-ai/dsh-token-meter": "workspace:*", + "@deepseek-ai/dsh-tool-agent-team": "workspace:*", "@deepseek-ai/dsh-tool-bash": "workspace:*", - "@deepseek-ai/dsh-tool-present": "workspace:*", + "@deepseek-ai/dsh-tool-call-timeout-policy": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-executor-ptc": "workspace:*", "@deepseek-ai/dsh-tool-fs": "workspace:*", "@deepseek-ai/dsh-tool-fs-search": "workspace:*", "@deepseek-ai/dsh-tool-goal": "workspace:*", + "@deepseek-ai/dsh-tool-jobs": "workspace:*", + "@deepseek-ai/dsh-tool-present": "workspace:*", "@deepseek-ai/dsh-tool-pwsh": "workspace:*", "@deepseek-ai/dsh-tool-skill": "workspace:*", "@deepseek-ai/dsh-tool-subagent": "workspace:*", "@deepseek-ai/dsh-tool-subagent-control": "workspace:*", - "@deepseek-ai/dsh-tool-jobs": "workspace:*", "@deepseek-ai/dsh-tool-todo": "workspace:*", "@deepseek-ai/dsh-tool-web": "workspace:*", "@deepseek-ai/dsh-tool-workflow": "workspace:*", + "@deepseek-ai/dsh-tool-working-directory": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", "@deepseek-ai/dsh-typert-loader": "workspace:*", "@deepseek-ai/dsh-typert-registry": "workspace:*", "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/dsh-user-questions": "workspace:*", "@deepseek-ai/dsh-web": "workspace:*", + "@deepseek-ai/dsh-web-deepseek-api": "workspace:*", "@deepseek-ai/dsh-web-fetch-http": "workspace:*", "@deepseek-ai/dsh-web-search-deepseek": "workspace:*", "@deepseek-ai/dsh-workflow-ptc": "workspace:*", - "@deepseek-ai/dsh-agent-instructions": "workspace:*", - "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", - "@deepseek-ai/dsh-plugin-manager": "workspace:*", - "@deepseek-ai/dsh-authorization": "workspace:*", - "@deepseek-ai/dsh-deepseek-account-platform": "workspace:*", - "@deepseek-ai/dsh-config-editor": "workspace:*", - "@deepseek-ai/dsh-settings": "workspace:*", - "@deepseek-ai/dsh-otel": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-tool-working-directory": "workspace:*", - "@deepseek-ai/dsh-web-deepseek-api": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" diff --git a/packages/bundle/headless/src/index.ts b/packages/bundle/headless/src/index.ts index d02729c097..bc98d7ae6b 100644 --- a/packages/bundle/headless/src/index.ts +++ b/packages/bundle/headless/src/index.ts @@ -426,7 +426,7 @@ async function run(ctx: Context, config: Config, io: HeadlessIo): Promise await agent.whenIdle() const idleSeq = agent.session.seq // Child settlement can wake the parent before the child wait observes it. - if (!await subagents?.waitForChildren(agent) + if (!await subagents?.waitForTreeWork(agent) && agent.status === 'idle' && agent.session.seq === idleSeq) break } } finally { diff --git a/packages/bundle/headless/tests/fixtures/provider-cwd.ts b/packages/bundle/headless/tests/fixtures/provider-cwd.ts index 9675fb9961..34a4d740b6 100644 --- a/packages/bundle/headless/tests/fixtures/provider-cwd.ts +++ b/packages/bundle/headless/tests/fixtures/provider-cwd.ts @@ -9,6 +9,10 @@ interface Config { root: string } /** Empty provider-owned workspace; no operation accesses the host filesystem. */ export default class ProviderCwdFileSystem extends FileSystem { + override async patchText(): Promise { throw new FsError('patch unsupported by test provider', 'FS_IO_ERROR') } + override async deleteFile(): Promise { throw new FsError('delete unsupported by test provider', 'FS_IO_ERROR') } + override async moveFile(): Promise { throw new FsError('move unsupported by test provider', 'FS_IO_ERROR') } + override watch(): never { throw new Error('Fixture does not support watching') } static inject = ['sandboxPolicy'] static Config: schema = schema.object({ root: schema.string().required() }) diff --git a/packages/bundle/headless/tests/headless.spec.ts b/packages/bundle/headless/tests/headless.spec.ts index 0d00029409..7a76b0b3e5 100644 --- a/packages/bundle/headless/tests/headless.spec.ts +++ b/packages/bundle/headless/tests/headless.spec.ts @@ -381,7 +381,7 @@ describe('headless runner', () => { if (turns === 1) { await test.ctx.subagents.startActivation({ provider: 'external', label: 'work', delivery: 'parent', signal: new AbortController().signal, - request: { parent, prompt: [] }, + parent, prompt: [], }) await cleaning.promise appendTurn(session, 1, message, 'waiting for child', true) @@ -429,7 +429,7 @@ describe('headless runner', () => { }, }) test.ctx.provide('subagents', { - async waitForChildren(parent: Agent) { + async waitForTreeWork(parent: Agent) { expect(test.ctx.agents.get(parent.id)).toBe(parent) const batch = checks++ if (batch === 2) return false @@ -467,7 +467,7 @@ describe('headless runner', () => { }, }) test.ctx.provide('subagents', { - async waitForChildren(parent: Agent) { + async waitForTreeWork(parent: Agent) { const check = checks++ if (check === 2) return false parent.followup(createUserMessage({ content: [{ type: 'text', text: 'batch complete' }], source: { kind: 'user' } })) diff --git a/packages/bundle/headless/tests/terminal-failures.spec.ts b/packages/bundle/headless/tests/terminal-failures.spec.ts index 5c20881ea9..c92f095334 100644 --- a/packages/bundle/headless/tests/terminal-failures.spec.ts +++ b/packages/bundle/headless/tests/terminal-failures.spec.ts @@ -60,7 +60,7 @@ describe('headless terminal failures', () => { const test = await harness() const failures: unknown[] = [] test.ctx.on('agent/error', ({ error }) => { failures.push(error) }) - const waitForChildren = vi.fn().mockImplementationOnce((parent: Agent) => { + const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => { const append = parent.session.append.bind(parent.session) const failAppend: typeof parent.session.append = (type, data, ...intent) => { if (type === failedEvent) throw new Error(`summary ${failedEvent} unavailable`) @@ -70,7 +70,7 @@ describe('headless terminal failures', () => { followup(parent) return Promise.resolve(true) }).mockResolvedValue(false) - test.ctx.provide('subagents', { waitForChildren } as never) + test.ctx.provide('subagents', { waitForTreeWork } as never) const result = await test.run(json) expect(failures).toHaveLength(1) @@ -87,7 +87,7 @@ describe('headless terminal failures', () => { it.each([false, true])('uses the durable outcome after a summary hook fails (recover=%s)', async (recover) => { const test = await harness() - const waitForChildren = vi.fn().mockImplementationOnce((parent: Agent) => { + const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => { const stop = test.ctx.on('agent/pre-step', () => { stop() throw new Error('summary hook failed') @@ -98,7 +98,7 @@ describe('headless terminal failures', () => { if (recover) followup(parent) return Promise.resolve(recover) }).mockResolvedValue(false) - test.ctx.provide('subagents', { waitForChildren } as never) + test.ctx.provide('subagents', { waitForTreeWork } as never) await expect(test.run()).resolves.toEqual(recover ? { code: 0, out: 'summary\n', err: '' } @@ -107,7 +107,7 @@ describe('headless terminal failures', () => { it.each(['turn/start', 'turn/end'] as const)('accepts a recovered summary after a missing %s', async (failedEvent) => { const test = await harness() - const waitForChildren = vi.fn().mockImplementationOnce((parent: Agent) => { + const waitForTreeWork = vi.fn().mockImplementationOnce((parent: Agent) => { const append = parent.session.append.bind(parent.session) let failed = false const failAppend: typeof parent.session.append = (type, data, ...intent) => { @@ -124,7 +124,7 @@ describe('headless terminal failures', () => { followup(parent) return Promise.resolve(true) }).mockResolvedValue(false) - test.ctx.provide('subagents', { waitForChildren } as never) + test.ctx.provide('subagents', { waitForTreeWork } as never) await expect(test.run()).resolves.toEqual({ code: 0, @@ -142,12 +142,12 @@ describe('headless terminal failures', () => { if (agent === other) throw new Error('another Agent failed') return next() }) - const waitForChildren = vi.fn().mockImplementationOnce(async () => { + const waitForTreeWork = vi.fn().mockImplementationOnce(async () => { followup(other) await other.whenIdle() return false }).mockResolvedValue(false) - test.ctx.provide('subagents', { waitForChildren } as never) + test.ctx.provide('subagents', { waitForTreeWork } as never) await expect(test.run()).resolves.toEqual({ code: 0, out: 'waiting\n', err: '' }) }) diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index ac78994ab7..adb17d9e6d 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-web-app/use-this-package: - en: 3bd37b85139d2fa7 - zh: ba86c807eb83866e + en: 1f69a4c52a27e7e5 + zh: e4431a252fb86f7c /deepseek-ai-dsh-web-app/use-this-package/starting-the-web-gui: en: e3cac911f080d8ef zh: 60749e9f5c39c1bc diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index cb974443e5..b621d1e8c2 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -31,6 +31,8 @@ Run `dsh --profile web` for browser chat, model and settings management, and ses Start the GUI, open your browser, and start talking to the agent. The flags fine-tune the invocation. +[Agent Teams UI](../../client/ui-agent-team/README.md) loads with this bundle. Enable it per Session in the model and reasoning menu; shared tasks open below the member tree from the Subagent control. + ### Starting the Web GUI ```sh diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 88bbae54a5..9df9111bf3 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -31,6 +31,8 @@ kind: "package-bundle" 启动 GUI、打开浏览器,然后开始与 agent(智能体)对话。flag 用于微调本次调用。 +[Agent Teams UI](../../client/ui-agent-team/README.zh.md) 随本 bundle 加载。在模型与推理等级菜单中按 Session 开启;通过 Subagent 控件打开成员树,下方显示共享任务。 + ### 启动 Web GUI ```sh diff --git a/packages/bundle/web-app/cordis.patch.yml b/packages/bundle/web-app/cordis.patch.yml index 20987aeabc..8c425e4b7e 100644 --- a/packages/bundle/web-app/cordis.patch.yml +++ b/packages/bundle/web-app/cordis.patch.yml @@ -129,7 +129,7 @@ name: '@deepseek-ai/dsh-api-workspace-files' # The Schedule service owns the task store and delivers each due occurrence - # as a follow-up in its original Session. The clock reading and the four + # as a follow-up to the task's target Session. The clock reading and the four # reminder tools belong to the `standard`, `cordis`, and `ptc` presets, # which declare them in their own scope. - id: schedule @@ -314,8 +314,9 @@ - id: ui-plugin-manager name: '@deepseek-ai/dsh-client-ui-plugin-manager' - # Account section, title tag, activation prompt, and notices that CLI app - # plugins register on the Plugins page over their own account Remotes. + # CLI app plugins register their accounts with the `cliAccounts` registry; + # the Plugins page shows each account's section, title tag, activation + # prompt, and notices through the `cliAccounts` Remote. - id: ui-cli-account name: '@deepseek-ai/dsh-client-ui-cli-account' @@ -387,6 +388,9 @@ - id: ui-skill name: '@deepseek-ai/dsh-client-ui-skill' + - id: ui-agent-team + name: '@deepseek-ai/dsh-client-ui-agent-team' + - id: ui-subagent name: '@deepseek-ai/dsh-client-ui-subagent' @@ -557,12 +561,9 @@ - id: tool-result-pruner disabled: true -# The subagent registry and its backends STAY in the host plane. `subagents` is -# a process singleton with a cross-session query surface (`listChildren`, -# `followup`) that the host api-proxy serves to the browser, and a provider -# registers under a globally unique name, so a per-session copy would both -# starve that host row and collide on the second session. What a preset -# chooses is which delegation TOOLS its agent sees, below. +# The subagent registry and its backends belong in the host composition: browser +# prompt and interrupt requests share its runtime, and provider names are unique +# within the registry. Presets select the delegation tools visible to each Agent. - id: tool-subagent-control disabled: true diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index e6e1a26909..ecf3339f38 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -58,6 +58,7 @@ "@deepseek-ai/dsh-agent-instructions": "workspace:*", "@deepseek-ai/dsh-agent-preset": "workspace:*", "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", + "@deepseek-ai/dsh-agent-tool-presentation": "workspace:*", "@deepseek-ai/dsh-api-job-controller": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", @@ -71,8 +72,11 @@ "@deepseek-ai/dsh-client-hmr": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-modules": "workspace:*", + "@deepseek-ai/dsh-client-product-analytics": "workspace:*", "@deepseek-ai/dsh-client-resources": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-ui-agent-preset": "workspace:*", + "@deepseek-ai/dsh-client-ui-agent-team": "workspace:*", "@deepseek-ai/dsh-client-ui-approval": "workspace:*", "@deepseek-ai/dsh-client-ui-attachment": "workspace:*", "@deepseek-ai/dsh-client-ui-brand-official": "workspace:*", @@ -98,18 +102,21 @@ "@deepseek-ai/dsh-client-ui-plugin-manager": "workspace:*", "@deepseek-ai/dsh-client-ui-reference": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", + "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", "@deepseek-ai/dsh-client-ui-secret-mask": "workspace:*", "@deepseek-ai/dsh-client-ui-session": "workspace:*", - "@deepseek-ai/dsh-client-ui-schedule": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-agent-loop": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-general": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-models": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-plugin-inventory": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-plugins": "workspace:*", + "@deepseek-ai/dsh-client-ui-settings-session-log": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-shell": "workspace:*", - "@deepseek-ai/dsh-client-ui-settings-agent-loop": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-subagent": "workspace:*", "@deepseek-ai/dsh-client-ui-settings-web-search": "workspace:*", + "@deepseek-ai/dsh-client-ui-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-browser": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-documentpreview": "workspace:*", @@ -131,14 +138,17 @@ "@deepseek-ai/dsh-compaction-tool-result-pruner": "workspace:*", "@deepseek-ai/dsh-cordis-client-runner": "workspace:*", "@deepseek-ai/dsh-cordis-host-runner": "workspace:*", + "@deepseek-ai/dsh-deliverable-file-references": "workspace:*", "@deepseek-ai/dsh-file-reference": "workspace:*", "@deepseek-ai/dsh-file-reference-local": "workspace:*", + "@deepseek-ai/dsh-harness-dev-context": "workspace:*", "@deepseek-ai/dsh-host-directory-picker-auto": "workspace:*", "@deepseek-ai/dsh-host-directory-picker-browse": "workspace:*", "@deepseek-ai/dsh-host-directory-picker-native": "workspace:*", "@deepseek-ai/dsh-host-frontend-static": "workspace:*", "@deepseek-ai/dsh-host-open-in-app": "workspace:*", "@deepseek-ai/dsh-host-plugin-inventory": "workspace:*", + "@deepseek-ai/dsh-host-product-telemetry-otel": "workspace:*", "@deepseek-ai/dsh-host-webserver": "workspace:*", "@deepseek-ai/dsh-launch-environment": "workspace:*", "@deepseek-ai/dsh-message-feedback": "workspace:*", diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index 51bbd00ef9..4494bb1530 100644 --- a/packages/bundle/web-app/presets/cordis.patch.yml +++ b/packages/bundle/web-app/presets/cordis.patch.yml @@ -29,6 +29,9 @@ disabled: !!js process.platform !== 'win32' - id: tool-fs name: '@deepseek-ai/dsh-tool-fs' + config: + # Set true to add the apply_patch tool beside edit. + applyPatch: false - id: tool-fs-search name: '@deepseek-ai/dsh-tool-fs-search' config: diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 034a2a6457..678692075c 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -26,6 +26,9 @@ disabled: !!js process.platform !== 'win32' - id: tool-fs name: '@deepseek-ai/dsh-tool-fs' + config: + # Set true to add the apply_patch tool beside edit. + applyPatch: false - id: tool-fs-search name: '@deepseek-ai/dsh-tool-fs-search' config: diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index e702c4b39d..a1aff022b0 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -26,6 +26,9 @@ disabled: !!js process.platform !== 'win32' - id: tool-fs name: '@deepseek-ai/dsh-tool-fs' + config: + # Set false to drop the apply_patch tool beside edit. + applyPatch: true - id: tool-fs-search name: '@deepseek-ai/dsh-tool-fs-search' config: diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml index 9e1e8a0ca7..3ec228ab0e 100644 --- a/packages/client/README.i18n.yaml +++ b/packages/client/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /client-web-gui-browser-half/packages: - en: 45f2781bd178f00a - zh: ed9c01b1be743b63 + en: 1ee961ced57fb164 + zh: 8ff78f2070f50cce /client-web-gui-browser-half/related-documentation: en: d1d506e68fab7333 zh: 1a90fe6f3f8f24a9 diff --git a/packages/client/README.md b/packages/client/README.md index 5aa8d02c63..3edf11de86 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -64,9 +64,10 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-skill/`](ui-skill/README.md) | Adds skill references to inline suggestions | — | | [`ui-reference/`](ui-reference/README.md) | Unified Web `@file` / `@session` reference source | — | | [`ui-secret-mask/`](ui-secret-mask/README.md) | Masks recognized credentials in sent user text | — | +| [`ui-agent-team/`](ui-agent-team/README.md) | Session Team switch and shared tasks below the Subagent tree | — | | [`ui-subagent/`](ui-subagent/README.md) | Provides subagent navigation, child transcript states, and inline references | — | | [`ui-jobs/`](ui-jobs/README.md) | Lists this session's background jobs with on-demand streaming record panels | — | -| [`ui-schedule/`](ui-schedule/README.md) | Lists the current Session's active reminders in a read-only header catalog | — | +| [`ui-schedule/`](ui-schedule/README.md) | Provides the sidebar Automation tasks page and right Sidebar task tab, which create, edit, run, pause, resume, and delete Host scheduled tasks, plus the Session header clock and row mark | — | | [`ui-model-selection/`](ui-model-selection/README.md) | Provides model selection in conversation surfaces | — | | [`ui-permission-presets/`](ui-permission-presets/README.md) | Configures default permissions and switches the current session's access | — | | [`ui-plan/`](ui-plan/README.md) | Presents active plan-mode status and its exit control | — | @@ -81,7 +82,7 @@ The kernel packages boot and serve the page; the UI feature packages present it. | [`ui-settings-session-log/`](ui-settings-session-log/README.md) | Controls API Session-log upload in General settings | — | | [`ui-settings-subagent/`](ui-settings-subagent/README.md) | Provides the Subagent settings page on the Plugins page | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.md) | Provides the web-search settings page on the Plugins page | — | -| [`ui-cli-account/`](ui-cli-account/README.md) | Shows the account section, tag, activation prompt, confirmations, and notices that CLI app plugins register on the Plugins page | `ctx.cliAccounts` | +| [`ui-cli-account/`](ui-cli-account/README.md) | Holds the accounts CLI app plugins register on the Host and shows each one's section, tag, activation prompt, confirmations, and notices on the Plugins page | `ctx.cliAccounts` | | [`ui-plugin-manager/`](ui-plugin-manager/README.md) | Contributes the sidebar Plugins panel: install, enable, disable, retry, and compose installed packages | — | | [`ui-entry-customization/`](ui-entry-customization/README.md) | Adds region-local More menus that pin or unpin plugin launchers and start a plugin draft | — | | [`ui-plugin-market/`](ui-plugin-market/README.md) | Contributes the Discover tab to the Plugins page: browse market indexes and install their bundles | — | diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md index 4675839f6a..5de11c4fdb 100644 --- a/packages/client/README.zh.md +++ b/packages/client/README.zh.md @@ -64,9 +64,10 @@ kind: "package-group" | [`ui-skill/`](ui-skill/README.zh.md) | 向内联建议添加 skill(技能)引用 | — | | [`ui-reference/`](ui-reference/README.zh.md) | 统一的 Web `@file` / `@session` 引用 source | — | | [`ui-secret-mask/`](ui-secret-mask/README.zh.md) | 遮挡已发送用户文本中可识别的凭据 | — | +| [`ui-agent-team/`](ui-agent-team/README.zh.md) | Session Team 开关与 Subagent 树下方的共享任务 | — | | [`ui-subagent/`](ui-subagent/README.zh.md) | 提供 subagent 导航、子级 transcript(文本记录)状态与内联引用 | — | | [`ui-jobs/`](ui-jobs/README.zh.md) | 列出本会话的后台任务,并提供按需展开的流式输出面板 | — | -| [`ui-schedule/`](ui-schedule/README.zh.md) | 在只读标题栏目录中列出当前会话中生效的提醒 | — | +| [`ui-schedule/`](ui-schedule/README.zh.md) | 提供侧栏“自动化任务”页面与右侧栏任务页签,用于创建、编辑、立即运行、暂停、恢复和删除宿主的计划任务,并提供 Session 顶部时钟与行标记 | — | | [`ui-model-selection/`](ui-model-selection/README.zh.md) | 在对话界面中提供模型选择 | — | | [`ui-permission-presets/`](ui-permission-presets/README.zh.md) | 配置默认权限并切换当前会话的访问模式 | — | | [`ui-plan/`](ui-plan/README.zh.md) | 展示生效中的 plan mode 状态及其退出控件 | — | @@ -81,7 +82,7 @@ kind: "package-group" | [`ui-settings-session-log/`](ui-settings-session-log/README.zh.md) | 在通用设置中控制随 API 上传会话日志 | — | | [`ui-settings-subagent/`](ui-settings-subagent/README.zh.md) | 在插件页提供子智能体设置页 | — | | [`ui-settings-web-search/`](ui-settings-web-search/README.zh.md) | 在插件页提供网页搜索设置页 | — | -| [`ui-cli-account/`](ui-cli-account/README.zh.md) | 显示 CLI 应用插件在插件页注册的账号区块、标签、开启引导、确认和提示 | `ctx.cliAccounts` | +| [`ui-cli-account/`](ui-cli-account/README.zh.md) | 保存 CLI 应用插件在 Host 上注册的账号,并在插件页显示每个账号的区块、标签、开启引导、确认和提示 | `ctx.cliAccounts` | | [`ui-plugin-manager/`](ui-plugin-manager/README.zh.md) | 贡献侧栏的“插件”面板:安装、启用、停用、重试与组合已安装的包 | — | | [`ui-entry-customization/`](ui-entry-customization/README.zh.md) | 添加分区域的“更多”菜单,固定或收起插件入口,并开始创建插件的草稿 | — | | [`ui-plugin-market/`](ui-plugin-market/README.zh.md) | 为“插件”页面贡献“发现”标签页:浏览市场索引并安装其中的组合包 | — | diff --git a/packages/client/locale/src/locales/de.ts b/packages/client/locale/src/locales/de.ts index dd88cf6fc4..cb0bb45579 100644 --- a/packages/client/locale/src/locales/de.ts +++ b/packages/client/locale/src/locales/de.ts @@ -33,6 +33,8 @@ export const de = { 'more': 'Mehr', 'collapse': 'Einklappen', 'expand': 'Ausklappen', + 'subtitle.expand': 'Beschreibung für {name} ausklappen', + 'subtitle.collapse': 'Beschreibung für {name} einklappen', 'back': 'Zurück', 'brand.localBuild': 'Lokaler DSH-Build', 'workspace.defaultName': 'Standardarbeitsbereich', diff --git a/packages/client/locale/src/locales/en.ts b/packages/client/locale/src/locales/en.ts index b649bbc3dc..47a03d69ef 100644 --- a/packages/client/locale/src/locales/en.ts +++ b/packages/client/locale/src/locales/en.ts @@ -32,6 +32,8 @@ export const en = { 'more': 'More', 'collapse': 'Collapse', 'expand': 'Expand', + 'subtitle.expand': 'Expand description for {name}', + 'subtitle.collapse': 'Collapse description for {name}', 'back': 'Back', 'brand.localBuild': 'DSH Local Build', 'workspace.defaultName': 'Default workspace', diff --git a/packages/client/locale/src/locales/es.ts b/packages/client/locale/src/locales/es.ts index 7eb95374e1..4fba984885 100644 --- a/packages/client/locale/src/locales/es.ts +++ b/packages/client/locale/src/locales/es.ts @@ -33,6 +33,8 @@ export const es = { 'more': 'Más', 'collapse': 'Contraer', 'expand': 'Expandir', + 'subtitle.expand': 'Expandir la descripción de {name}', + 'subtitle.collapse': 'Contraer la descripción de {name}', 'back': 'Atrás', 'brand.localBuild': 'Compilación local de DSH', 'workspace.defaultName': 'Espacio de trabajo predeterminado', diff --git a/packages/client/locale/src/locales/fr.ts b/packages/client/locale/src/locales/fr.ts index c57f1a3b11..f0e5030f41 100644 --- a/packages/client/locale/src/locales/fr.ts +++ b/packages/client/locale/src/locales/fr.ts @@ -33,6 +33,8 @@ export const fr = { 'more': 'Plus', 'collapse': 'Réduire', 'expand': 'Développer', + 'subtitle.expand': 'Développer la description de {name}', + 'subtitle.collapse': 'Réduire la description de {name}', 'back': 'Retour', 'brand.localBuild': 'Version locale de DSH', 'workspace.defaultName': 'Espace de travail par défaut', diff --git a/packages/client/locale/src/locales/ja.ts b/packages/client/locale/src/locales/ja.ts index 1186838c31..2b70cbb156 100644 --- a/packages/client/locale/src/locales/ja.ts +++ b/packages/client/locale/src/locales/ja.ts @@ -33,6 +33,8 @@ export const ja = { 'more': 'その他', 'collapse': '折りたたむ', 'expand': '展開', + 'subtitle.expand': '{name} の説明を展開', + 'subtitle.collapse': '{name} の説明を折りたたむ', 'back': '戻る', 'brand.localBuild': 'DSHローカルビルド', 'workspace.defaultName': 'デフォルトワークスペース', diff --git a/packages/client/locale/src/locales/pt.ts b/packages/client/locale/src/locales/pt.ts index 75cdb19c29..adf711152d 100644 --- a/packages/client/locale/src/locales/pt.ts +++ b/packages/client/locale/src/locales/pt.ts @@ -33,6 +33,8 @@ export const pt = { 'more': 'Mais', 'collapse': 'Recolher', 'expand': 'Expandir', + 'subtitle.expand': 'Expandir descrição de {name}', + 'subtitle.collapse': 'Recolher descrição de {name}', 'back': 'Voltar', 'brand.localBuild': 'Versão local do DSH', 'workspace.defaultName': 'Espaço de trabalho padrão', diff --git a/packages/client/locale/src/locales/ru.ts b/packages/client/locale/src/locales/ru.ts index a8a6d829da..e75620fe21 100644 --- a/packages/client/locale/src/locales/ru.ts +++ b/packages/client/locale/src/locales/ru.ts @@ -33,6 +33,8 @@ export const ru = { 'more': 'Ещё', 'collapse': 'Свернуть', 'expand': 'Развернуть', + 'subtitle.expand': 'Развернуть описание {name}', + 'subtitle.collapse': 'Свернуть описание {name}', 'back': 'Назад', 'brand.localBuild': 'Локальная сборка DSH', 'workspace.defaultName': 'Рабочая область по умолчанию', diff --git a/packages/client/locale/src/locales/zh.ts b/packages/client/locale/src/locales/zh.ts index 11ff789b8a..6350caae3c 100644 --- a/packages/client/locale/src/locales/zh.ts +++ b/packages/client/locale/src/locales/zh.ts @@ -30,6 +30,8 @@ export const zh = { 'more': '更多', 'collapse': '收起', 'expand': '展开', + 'subtitle.expand': '展开{name}的描述', + 'subtitle.collapse': '收起{name}的描述', 'back': '返回', 'brand.localBuild': 'DSH 本地构建', 'workspace.defaultName': '默认工作区', diff --git a/packages/client/store/README.i18n.yaml b/packages/client/store/README.i18n.yaml index 5da729b805..50903fc78f 100644 --- a/packages/client/store/README.i18n.yaml +++ b/packages/client/store/README.i18n.yaml @@ -21,8 +21,8 @@ en: ed7581186c5b5a33 zh: a0efffb2631c1eec /deepseek-ai-dsh-client-store/known-limitations-and-deferred-work: - en: 3190cd5b744025fe - zh: f559c3316b6a7da4 + en: 313598f4a7a9911e + zh: c183d275b1207d5b /deepseek-ai-dsh-client-store/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/store/README.md b/packages/client/store/README.md index a83f5aa420..9cb22744e0 100644 --- a/packages/client/store/README.md +++ b/packages/client/store/README.md @@ -32,7 +32,7 @@ None; the stores neither assemble nor send model requests. - **Persistence is browser-local** — persisted stores use JSON in `localStorage`; non-browser runtimes disable persistence, and the package provides no cross-device synchronization. -- **Web-shell build input** — the static ESM retains third-party imports for Vite; independent consumers supply its development dependencies ([dependency rules](../AGENTS.md#dependency-declaration)). +- **Web-shell build input** — the static ESM retains third-party imports for Vite; independent consumers supply its development dependencies ([dependency rules](../AGENTS.md#dependency-declaration)). The build defaults to production; `NODE_ENV=development` enables development checks. Wholesale `set()` freezes snapshots only outside production; `update()` retains Immer's automatic freezing. diff --git a/packages/client/store/README.zh.md b/packages/client/store/README.zh.md index 15a62b4bae..c64411a82f 100644 --- a/packages/client/store/README.zh.md +++ b/packages/client/store/README.zh.md @@ -32,7 +32,7 @@ kind: "package-library" - **持久化仅限浏览器本地**——持久化存储使用 `localStorage` 中的 JSON;非浏览器运行时会禁用持久化,本包也不提供跨设备同步。 -- **Web 壳构建输入**——静态 ESM 为 Vite 保留第三方导入;独立消费方自行提供开发依赖([依赖规则](../AGENTS.md#dependency-declaration))。 +- **Web 壳构建输入**——静态 ESM 为 Vite 保留第三方导入;独立消费方自行提供开发依赖([依赖规则](../AGENTS.md#dependency-declaration))。构建默认为生产模式;`NODE_ENV=development` 启用开发检查。整份替换的 `set()` 仅在非生产模式冻结快照;`update()` 保留 Immer 的自动冻结。 diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 5f1cbd355e..5eaf0b2a35 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below @@ -310,6 +310,8 @@ function staticLinkedConfig(id: string, entry: string, outputName = basename(ent format: ['esm'], platform: 'browser', target: 'es2024', + // Resolve the mode before this intermediate bundle removes conditional branches. + define: { 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV ?? 'production') }, fixedExtension: false, dts: false, clean: false, diff --git a/packages/client/ui-agent-preset/src/client/AgentPresetLabel.module.css b/packages/client/ui-agent-preset/src/client/AgentPresetLabel.module.css index f828de9af1..50a1b2b181 100644 --- a/packages/client/ui-agent-preset/src/client/AgentPresetLabel.module.css +++ b/packages/client/ui-agent-preset/src/client/AgentPresetLabel.module.css @@ -19,7 +19,6 @@ .icon { flex: none; - opacity: 0.7; } /* First sacrifice when the title row (the enclosing inline-size container) diff --git a/packages/client/ui-agent-team/README.i18n.yaml b/packages/client/ui-agent-team/README.i18n.yaml new file mode 100644 index 0000000000..dfab72bf26 --- /dev/null +++ b/packages/client/ui-agent-team/README.i18n.yaml @@ -0,0 +1,40 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/client/ui-agent-team/README.md +/: + en: cecfe90c9079279f + zh: 58062db454093088 +/deepseek-ai-dsh-client-ui-agent-team: + en: 39c47e6e926425bf + zh: 0fd155c454355e3a +/deepseek-ai-dsh-client-ui-agent-team/summary: + en: 88103cec4c91d755 + zh: 6536e4307a5ce122 +/deepseek-ai-dsh-client-ui-agent-team/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-client-ui-agent-team/use-this-package: + en: d502ab38773eef34 + zh: e1f9c4edbc74c38f +/deepseek-ai-dsh-client-ui-agent-team/use-this-package/inspect-the-task-board: + en: 7e88fb00a3abd230 + zh: 08efcf80afecb0c0 +/deepseek-ai-dsh-client-ui-agent-team/understand-the-implementation: + en: 9b0b6a8505a9ebbf + zh: beb5d89f80463b3e +/deepseek-ai-dsh-client-ui-agent-team/further-exploration: + en: 4d9214370681b02e + zh: 4acb21b9ecf25e85 +/deepseek-ai-dsh-client-ui-agent-team/model-experience: + en: 47ebeba07d72759d + zh: 8fe8133f6dd845a9 +/deepseek-ai-dsh-client-ui-agent-team/model-experience/kv-cache-effect: + en: b51b320f5e4dacfc + zh: 6695947c3f9fed28 +/deepseek-ai-dsh-client-ui-agent-team/known-limitations-and-deferred-work: + en: 8be0a045f2f42e9e + zh: 36f98d5cc1189f7a +/deepseek-ai-dsh-client-ui-agent-team/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-agent-team/README.md b/packages/client/ui-agent-team/README.md new file mode 100644 index 0000000000..d156e7b7cb --- /dev/null +++ b/packages/client/ui-agent-team/README.md @@ -0,0 +1,100 @@ +--- +description: "Inspect the shared task board from the Web conversation header." +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-agent-team + +English | [中文](README.zh.md) + +## Summary + +This package displays shared tasks below the Subagent tree in one header panel. Host projection frames keep task state current without a refresh control. Ordinary subagent navigation owns the member list and teammate conversations. The Web bundle loads this package; it adds no model-facing input. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +In the root conversation’s model and reasoning menu, turn on **Enable agent teamwork**. New Sessions default to off. While enabled, open the root conversation’s Subagent control to see members above shared tasks. Child conversations keep subagent navigation without a task board or Team switch, including before their subagent address is discovered. The entry is hidden when both the subagent catalog and shared tasks are empty; catalog and task-record errors remain accessible. Section headers appear only when Team mode is enabled, at least one nondeleted shared task exists, and the task footer is available. In that case, the noncollapsible Subagents section remains above shared tasks even when its catalog is empty. Otherwise, the menu shows only subagent navigation, without section headers, a shared-task module, empty-state copy, or a divider. Turning it off retains tasks and subagents. The entire Team row highlights on hover and toggles the selection when clicked, except for its independent information button. The switch calls `remote.agentTeams.setEnabled`, waits for the saved projection and reports failures through the menu host; the row cannot toggle while locked or saving. The adjacent information button explains shared-task coordination and additional token use on hover, keyboard focus, or click/tap without changing the selection. Escape or an outside press dismisses the explanation. + +Turning off the menu switch requires confirmation after the Session records a model request; a model choice alone does not require it. The switch waits while request history is unavailable. The dialog explains the tool, coordination, and possible cache effects without deleting task records. Cancel, Escape, or closing the dialog leaves Team mode unchanged. Dismissing the dialog returns focus to the model selector. Confirmation targets the originating Session, waits for the save, and keeps failures visible for retry; it does not depend on the model menu remaining open. Team mode has no slash command; menu changes create no `command/run` or `command/done` records. + +Chat hides historical `/team on` and `/team off` receipts with pending or successful outcomes. Failures remain visible with a Users icon, a localized “Agent teamwork” title, and a localized failure prefix followed by the first nonempty line of the recorded reason without translation. Expanding the receipt shows the full original error. Unknown or missing arguments retain a visible receipt. + +The [Web bundle](../../bundle/web-app/README.md) loads this package by default. The Web Client loader mounts the `/client` export; the root Host export is inert, and the package has no user configuration fields. + +### Inspect the task board + +Ready pending tasks use idle, blocked pending tasks use warning, in-progress tasks use ongoing, and completed tasks use done. + +The noncollapsible Shared tasks header uses a Checklist icon and completed, in-progress, and pending counts, with zero counts omitted and wording and separators matching the input task list. Compact read-only rows show the subject, status, and a chevron, with 13px primary titles and hover geometry aligned to subagent rows; expanded details use 12px text. Task rows use 7px vertical padding, 6px horizontal padding, and 7px gaps to align their clickable content with subagent rows. All task details start closed; opening one closes the previous task. Details show only the full description when present, followed by a single-line owner label and Session id in the same color with a 4px gap. Long owner ids are ellipsized and reveal their full text in a tooltip only when clipped. Task-text and owner tooltips appear after 500ms of hover. Every owner is identified by its Session id. The shared menu is 360px wide with 6px outer padding, constrained to fit the viewport. Shared tasks have a 4px top margin rather than a divider. Both section headers keep a 7px icon/title gap and an additional 4px before their counts. Only the menu scrolls; task lists and details have no nested scrolling. Agents mutate tasks through tools; the panel provides no mutation controls. A projection failure appears separately above any retained tasks and remains visible when no tasks exist. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The Client export registers its locale dictionaries and subagent-catalog and model-menu slots through Cordis effects; it mounts no Remote namespace. Disposing the plugin fiber removes its registrations. + +The Subagent catalog owns the shared panel, scrolling, hover, keyboard, and dismissal interactions. This package contributes the task section only below the root conversation’s tree. The board reads the current Session’s mode and tasks through `useProjection('agentTeam')`. An available, enabled projection supplies the task section only when it contains nondeleted tasks; a projection failure can render independently without a task section. Task IDs, dependencies, readiness, write scopes, and write scope warnings remain in task data but are not displayed as detail fields; blocked pending tasks still use the warning glyph. + +The [Chat visibility policy](../ui-chat/src/client/contract/chat-visibility.ts) hides only historical commands named `team` whose trimmed recorded arguments are exactly `on` or `off` and whose outcome is pending or successful. The remaining receipts use a localized running summary or preserve raw successful output, with a localized completed fallback when that text is empty. Rendering neither reads the current Team projection nor parses English outcome text. Filtering and localization affect only Chat presentation: command records, logs, trajectory, and raw errors remain unchanged. + +| File | Role | +|---|---| +| [`src/client/mount.ts`](src/client/mount.ts) | Locale, catalog-section, and model-menu registrations | +| [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | Projection-derived task section | +| [`src/client/locales.ts`](src/client/locales.ts) | Panel and command copy in eight languages | +| [`src/index.ts`](src/index.ts) | Inert Host entry | + +
+ +----- + + +## Further Exploration + +- [Web bundle](../../bundle/web-app/README.md) — mounts the Client plugin by default. +- [Agent Teams service](../../team/agent-team/README.md) — authoritative task and projection behavior. +- [Conversation UI](../ui-conversation/README.md) — the stable header slot and addressed-subagent navigation surface. + +----- + + +## Model Experience + +None, as this browser projection registers no model-facing input. + +#### KV Cache effect + +No direct effect; the Team tools and ordinary conversation submission own any later model-visible use. + +## Known Limitations and Deferred Work + + + +- **No mailbox timeline** — the panel displays tasks, not messages. +- **No lifecycle or workspace controls** — the panel cannot spawn, rename, delete, or interrupt teammates, and write scopes remain advisory metadata. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/client/ui-agent-team/README.zh.md b/packages/client/ui-agent-team/README.zh.md new file mode 100644 index 0000000000..6a370c6eeb --- /dev/null +++ b/packages/client/ui-agent-team/README.zh.md @@ -0,0 +1,100 @@ +--- +description: "从 Web 对话标题栏查看共享任务板。" +kind: "package-reference" +--- + +# @deepseek-ai/dsh-client-ui-agent-team + +[English](README.md) | 中文 + +## 概述 + +此包在同一个页头面板中,将共享任务显示在 Subagent 树下方。Host 投影帧持续更新任务状态,无需刷新控件。普通 subagent(子智能体)导航负责成员列表和队友对话。Web bundle 默认加载此包;它不添加模型可见输入。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +在根会话的模型与推理等级菜单中打开**启用智能体团队协作**。新 Session 默认关闭。开启后,通过根会话的 Subagent 入口同时查看上方的成员树和下方的共享任务。子会话保留子智能体导航,不显示任务板或 Team 开关,包括尚未发现子代理地址时。子智能体目录和共享任务都为空时隐藏入口;目录或任务记录错误仍保留查看入口。仅当 Team 模式已开启、存在至少一个未删除的共享任务且任务 footer 可用时,才显示区域标题。此时即使目录为空,共享任务上方仍保留不可折叠的“子智能体”区域。其他情况下,菜单仅显示 subagent 导航,不显示区域标题、共享任务模块、空状态文案或分隔线。关闭后保留任务和子代理。团队设置整行在悬停时高亮,点击可切换状态,但独立的信息按钮除外。开关调用 `remote.agentTeams.setEnabled`,等待保存后的投影更新,失败由菜单宿主提示;锁定或保存中不能通过整行切换。旁边的信息按钮可通过悬停、键盘聚焦或点击/轻触查看共享任务协作与额外 token 消耗的说明,不改变开关状态。按 Escape 或点击外部可关闭说明。 + +会话记录过模型请求后,从菜单开关停用团队需要确认;仅选择模型不会触发确认。请求历史尚未加载时,开关暂不可操作。弹窗说明工具、协作与可能的缓存影响,不会删除任务记录。取消、按 Escape 或关闭弹窗都保持团队状态不变。弹窗关闭后,焦点回到模型选择按钮。确认操作绑定到最初的会话,等待保存完成,失败时保留错误供重试,不依赖模型菜单保持打开。Team 模式没有斜杠命令;菜单切换不会生成 `command/run` 或 `command/done` 记录。 + +Chat 隐藏历史 `/team on` 和 `/team off` 记录中尚未完成或执行成功的回执。失败回执仍显示 Users 图标、本地化的“智能体团队协作”标题,以及本地化的失败前缀和已记录原因的首个非空行,不翻译原因原文。展开回执可查看完整原始错误。参数无法识别或缺失时仍显示回执。 + +[Web bundle](../../bundle/web-app/README.zh.md) 默认加载本包。Web Client loader 挂载 `/client` export;root Host export 不执行行为,本包也没有用户配置字段。 + +### 查看任务板 + +可开始的 pending 任务使用 idle 灰点,被依赖阻塞的 pending 任务使用 warning 橙点,in-progress 任务使用 ongoing loading,completed 任务使用 done 绿点。 + +不可折叠的“共享任务”标题使用 Checklist 图标,并显示已完成、进行中和待处理数量;省略零值,文案和分隔符与输入区任务列表一致。紧凑只读行显示主题、状态和展开箭头,13px 主标题与悬停区域对齐子智能体行;展开详情使用 12px 文字。任务行使用 7px 垂直内边距、6px 水平内边距和 7px 间距,使可点击内容与 subagent 行对齐。所有任务详情初始关闭,打开一项会关闭上一项。详情仅显示完整描述(如有),下方以单行显示负责人标签和 Session id,两者使用相同颜色,间距为 4px。过长的负责人 id以省略号截断,仅在被截断时通过工具提示显示完整内容。任务文字和负责人的工具提示在悬停 500ms 后显示。每个负责人均通过其 Session id 标识。共享菜单宽度为 360px,外层内边距为 6px,并受视口可用宽度约束。共享任务上方保留 4px 外边距,不显示分隔线。两个区域标题均保留 7px 图标与文字间距,并在统计数量前额外留出 4px。仅菜单本身滚动,任务列表与详情不单独滚动。Agent 通过工具修改任务;面板不提供修改控件。投影失败以独立警告显示在保留的任务上方,即使没有任务也保持可见。 + +----- + + +## 理解实现 + +
+实现细节——点击展开 + +Client export 通过 Cordis effect 注册语言字典、子代理目录与模型菜单 slot;它不挂载 Remote namespace。销毁插件 fiber 会移除这些注册。 + +Subagent 目录负责共享面板的滚动、悬停、键盘和关闭交互。本包仅在根会话的树下方提供任务区。任务板通过 `useProjection('agentTeam')` 读取当前 Session 的模式与任务;仅当投影可用、已开启且含有未删除的任务时才显示任务区;投影错误可独立显示,不需要任务区。任务 ID、依赖、准备状态、写入范围及其提示仍保留在任务数据中,但不作为详情字段显示;被依赖阻塞的 pending 任务仍使用 warning 图标。 + +[Chat 可见性策略](../ui-chat/src/client/contract/chat-visibility.ts) 仅隐藏名称为 `team`、已记录参数去除首尾空白后恰为 `on` 或 `off`,且尚未完成或执行成功的历史命令。其余回执在执行中显示本地化摘要,成功时保留原始结果文本,文本为空则使用本地化的完成提示。渲染既不读取当前 Team 投影,也不解析英文结果文案。过滤与本地化仅影响 Chat 展示:命令记录、日志、轨迹和原始错误均保持不变。 + +| 文件 | 职责 | +|---|---| +| [`src/client/mount.ts`](src/client/mount.ts) | 语言字典、目录任务区和模型菜单注册 | +| [`src/client/TeamBoard.tsx`](src/client/TeamBoard.tsx) | 从投影派生的任务区 | +| [`src/client/locales.ts`](src/client/locales.ts) | 八种语言的面板与命令文案 | +| [`src/index.ts`](src/index.ts) | 不执行行为的 Host entry | + +
+ +----- + + +## 进一步探索 + +- [Web bundle](../../bundle/web-app/README.zh.md)——默认挂载本 Client plugin。 +- [Agent Teams 服务](../../team/agent-team/README.zh.md) — 任务和投影行为的权威来源。 +- [会话 UI](../ui-conversation/README.zh.md)——稳定 header slot 与 addressed-subagent 导航表层。 + +----- + + +## 模型体验 + +无直接影响,因为该浏览器 projection 不注册面向模型的输入。 + +#### KV Cache 影响 + +无直接影响;Team 工具与普通会话提交负责后续任何模型可见用途。 + +## 已知限制与延期工作 + + + +- **无邮箱时间线** — 面板显示任务,不显示消息。 +- **没有 lifecycle 或 workspace control**——panel 不能 spawn、rename、delete 或 interrupt teammate,write scope 仍只是提示性 metadata。 + + +### 开发备注 + +
+维护者的工作上下文——点击展开 + +无。 + +
diff --git a/packages/experimental/client-ui-agent-team/locale/de.json b/packages/client/ui-agent-team/locale/de.json similarity index 100% rename from packages/experimental/client-ui-agent-team/locale/de.json rename to packages/client/ui-agent-team/locale/de.json diff --git a/packages/client/ui-agent-team/locale/en.json b/packages/client/ui-agent-team/locale/en.json new file mode 100644 index 0000000000..c6667a6afb --- /dev/null +++ b/packages/client/ui-agent-team/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Task board", + "description": "View shared tasks for the subagent tree." + } +} diff --git a/packages/experimental/client-ui-agent-team/locale/es.json b/packages/client/ui-agent-team/locale/es.json similarity index 100% rename from packages/experimental/client-ui-agent-team/locale/es.json rename to packages/client/ui-agent-team/locale/es.json diff --git a/packages/experimental/client-ui-agent-team/locale/fr.json b/packages/client/ui-agent-team/locale/fr.json similarity index 100% rename from packages/experimental/client-ui-agent-team/locale/fr.json rename to packages/client/ui-agent-team/locale/fr.json diff --git a/packages/client/ui-agent-team/locale/ja.json b/packages/client/ui-agent-team/locale/ja.json new file mode 100644 index 0000000000..ae63e83f31 --- /dev/null +++ b/packages/client/ui-agent-team/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "タスクボード", + "description": "サブエージェントツリーの共有タスクを表示します。" + } +} diff --git a/packages/experimental/client-ui-agent-team/locale/pt.json b/packages/client/ui-agent-team/locale/pt.json similarity index 100% rename from packages/experimental/client-ui-agent-team/locale/pt.json rename to packages/client/ui-agent-team/locale/pt.json diff --git a/packages/experimental/client-ui-agent-team/locale/ru.json b/packages/client/ui-agent-team/locale/ru.json similarity index 100% rename from packages/experimental/client-ui-agent-team/locale/ru.json rename to packages/client/ui-agent-team/locale/ru.json diff --git a/packages/client/ui-agent-team/locale/zh.json b/packages/client/ui-agent-team/locale/zh.json new file mode 100644 index 0000000000..9d06145f0f --- /dev/null +++ b/packages/client/ui-agent-team/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "任务板", + "description": "查看子智能体树的共享任务。" + } +} diff --git a/packages/experimental/client-ui-agent-team/package.json b/packages/client/ui-agent-team/package.json similarity index 71% rename from packages/experimental/client-ui-agent-team/package.json rename to packages/client/ui-agent-team/package.json index 17963f6de8..271137193a 100644 --- a/packages/experimental/client-ui-agent-team/package.json +++ b/packages/client/ui-agent-team/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-experimental-client-ui-agent-team", - "description": "Web Agent Teams roster, task board, and teammate navigation", + "name": "@deepseek-ai/dsh-client-ui-agent-team", + "description": "Web shared task board for a subagent tree", "version": "0.2.2-alpha.2", "publishConfig": { "access": "public" @@ -8,7 +8,7 @@ "repository": { "type": "git", "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/experimental/client-ui-agent-team" + "directory": "packages/client/ui-agent-team" }, "type": "module", "main": "lib/index.js", @@ -32,8 +32,9 @@ "@deepseek-ai/dsh-api-session-controller", "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-conversation", - "@deepseek-ai/dsh-client-ui-primitives", - "@deepseek-ai/dsh-client-ui-workspace" + "@deepseek-ai/dsh-client-ui-chat", + "@deepseek-ai/dsh-client-ui-layout", + "@deepseek-ai/dsh-client-ui-primitives" ], "platform": "web" } @@ -51,18 +52,23 @@ "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-commands": "workspace:*", "@deepseek-ai/dsh-client-ui-conversation": "workspace:*", + "@deepseek-ai/dsh-client-ui-chat": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", - "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", - "@deepseek-ai/dsh-experimental-agent-team": "workspace:*", + "@deepseek-ai/dsh-agent-team": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@testing-library/react": "^16.3.3", "@deepseek-ai/cordis": "workspace:~", "react": "^18.2.0", "react-dom": "^18.2.0", + "@deepseek-ai/dsh-client-ui-model-selection": "workspace:*", + "@deepseek-ai/dsh-client-ui-layout": "workspace:*", + "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-client-ui-subagent": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*" }, "files": [ diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.module.css b/packages/client/ui-agent-team/src/client/TeamBoard.module.css new file mode 100644 index 0000000000..3d10436a16 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamBoard.module.css @@ -0,0 +1,165 @@ +.board { + min-width: 0; + padding: 8px 7px; +} + +.board[data-with-members='true'] { + margin-top: 4px; +} + +.header { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 4px 7px; + margin: 0 0 4px; + padding: 0; +} + +.lead, +.glyph, +.chevron { + display: grid; + flex: none; + place-items: center; + color: var(--dsw-alias-label-tertiary); +} + +.title { + flex: none; + color: var(--dsw-alias-label-primary); + font-size: 13px; + font-weight: 500; + line-height: 24px; +} + +.progress { + margin-inline-start: 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 13px; + font-weight: 400; + font-variant-numeric: tabular-nums; + line-height: 20px; + overflow-wrap: anywhere; +} + +.tasks { + display: flex; + flex-direction: column; + margin: 0; + padding: 0; + list-style: none; +} + +.task { + min-width: 0; +} + +.taskRow { + box-sizing: border-box; + display: flex; + align-items: center; + gap: 7px; + width: calc(100% + 12px); + min-width: 0; + margin: 0 -6px; + padding: 7px 6px; + border: 0; + border-radius: var(--dsw-radius-md); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + font-size: 13px; + line-height: 17px; + text-align: left; + cursor: pointer; +} + +.taskRow:focus-visible { + outline: none; + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .taskRow:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.glyph { + width: 14px; + height: 17px; +} + +.subject { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.task[data-expanded='true'] .taskRow { + align-items: flex-start; +} + +.task[data-expanded='true'] .subject { + overflow: visible; + overflow-wrap: anywhere; + white-space: pre-wrap; +} + +.task[data-expanded='true'] .chevron { + transform: rotate(180deg); +} + +.chevron { + width: 28px; + height: 17px; +} + +.details { + padding: 0 0 8px 21px; + color: var(--dsw-alias-label-secondary); + font-size: 12px; + line-height: 18px; + overflow-wrap: anywhere; +} + +.description { + margin: 0; + white-space: pre-wrap; +} + +.owner { + display: flex; + gap: 4px; + min-width: 0; + margin: 0; + white-space: nowrap; +} + +.description + .owner { + margin-top: 6px; +} + +.ownerLabel { + flex: none; +} + +.ownerValue { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.error { + display: flex; + align-items: flex-start; + gap: 7px; + padding: 8px 0; + color: var(--dsw-alias-state-error-primary); + font-size: 12px; + line-height: 18px; + overflow-wrap: anywhere; +} diff --git a/packages/client/ui-agent-team/src/client/TeamBoard.tsx b/packages/client/ui-agent-team/src/client/TeamBoard.tsx new file mode 100644 index 0000000000..dbc554d33c --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamBoard.tsx @@ -0,0 +1,112 @@ +import { useState } from 'react' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { TeamTaskView, TeamTaskId } from '@deepseek-ai/dsh-agent-team/client' +import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { + IconChecklistOutlineRegular, IconChevronDownOutlineRegular, + StateDot, Tooltip, type StateDotState, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-subagent/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import { NS, type TeamKey } from './locales.ts' +import css from './TeamBoard.module.css' + +/** Full props of the task board below the shared subagent catalog. */ +export type TeamBoardProps = + PropsRuntime<'conversation.session.header.actions.subagent.footer'> & PropsLocale + +type VisibleTask = TeamTaskView & { status: Exclude } + +const statusKeys = { + pending: 'status.pending', in_progress: 'status.in_progress', completed: 'status.completed', +} satisfies Record + +const dotStates = { + pending: 'idle', in_progress: 'ongoing', completed: 'done', +} satisfies Record + +function progressLabel(tasks: readonly VisibleTask[], t: TeamBoardProps['t']): string { + const completed = tasks.filter(task => task.status === 'completed').length + const active = tasks.filter(task => task.status === 'in_progress').length + const pending = tasks.length - completed - active + return [ + ...completed > 0 ? [t('progress.completed', { count: completed })] : [], + ...active > 0 ? [t('progress.active', { count: active })] : [], + ...pending > 0 ? [t('progress.pending', { count: pending })] : [], + ].join('\u2002·\u2002') +} + +function TaskRow({ task, rootId, expanded, onToggle, t }: Pick & { + task: VisibleTask + rootId: SessionId + expanded: boolean + onToggle: () => void +}) { + const owner = task.ownerId ?? t('unowned') + const blocked = task.status === 'pending' && !task.ready + const detailsId = `team-task-${rootId}-${task.id}` + return ( +
  • + + + + {expanded && ( +
    + {task.description &&

    {task.description}

    } +

    + {t('owner')}: + + {owner} + +

    +
    + )} +
  • + ) +} + +/** Render read-only tasks in source order; the enclosing subagent menu owns scrolling. */ +export function TeamBoard({ sessionId, useProjection, useSessions, t }: TeamBoardProps) { + const team = useProjection('agentTeam') + const hasMembers = useSessions(state => (state.projectionsBySession[sessionId]?.values.subagentCatalog?.length ?? 0) > 0) + const [expandedTaskId, setExpandedTaskId] = useState(null) + if (!team?.enabled) return null + const tasks = team.tasks.filter((task): task is VisibleTask => task.status !== 'deleted') + const failure = team.failure === undefined ? null : ( +
    {t('failure', { message: team.failure })}
    + ) + if (tasks.length === 0) return failure === null ? null :
    {failure}
    + return ( +
    +

    + + {t('tasks')} + {progressLabel(tasks, t)} +

    + {failure} +
      + {tasks.map(task => ( + { setExpandedTaskId(current => current === task.id ? null : task.id) }} + t={t} + /> + ))} +
    +
    + ) +} diff --git a/packages/client/ui-agent-team/src/client/TeamCommandRow.module.css b/packages/client/ui-agent-team/src/client/TeamCommandRow.module.css new file mode 100644 index 0000000000..a36f5ff903 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamCommandRow.module.css @@ -0,0 +1,44 @@ +.root { + display: flex; + flex-direction: column; +} + +.title { font-weight: 400; } + +.separator { + flex: none; + width: 2px; + height: 2px; + margin: 0 8px; + border-radius: 1px; + background: var(--dsw-alias-label-caption); +} + +.summary { + min-width: 0; + overflow: hidden; + flex: 1 1 auto; + font-size: var(--dsh-content-font-size-secondary, 13px); + line-height: calc(24px + var(--dsh-content-font-delta, 0px)); + text-overflow: ellipsis; + white-space: nowrap; +} + +.summary[data-error], +.body[data-error] { + color: var(--dsw-alias-state-error-primary); +} + +.body { + max-height: 260px; + margin: 4px 0 4px 4px; + padding: 12px 16px; + overflow: auto; + border: 0.5px solid var(--dsw-alias-border-l1); + border-radius: var(--dsw-radius-lg); + background: var(--dsw-alias-markdown-code-block); + color: var(--dsw-alias-label-primary); + font: var(--dsw-font-markdown-code-block-small); + white-space: pre-wrap; + overflow-wrap: anywhere; +} diff --git a/packages/client/ui-agent-team/src/client/TeamCommandRow.tsx b/packages/client/ui-agent-team/src/client/TeamCommandRow.tsx new file mode 100644 index 0000000000..dde0b5cced --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamCommandRow.tsx @@ -0,0 +1,65 @@ +/** Read-only historical /team failures and fallback output. */ +import { useState } from 'react' +import { DisclosureRow, IconUsersOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-chat/client' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { NS } from './locales.ts' +import css from './TeamCommandRow.module.css' + +/** Framework command data and the owning Team dictionary. */ +export type TeamCommandRowProps = PropsRuntime<'conversation.chat.commandview'> & PropsLocale + +const TEAM_ICON = + +function commandSummary(node: TeamCommandRowProps['node'], t: TeamCommandRowProps['t']): string { + const outcome = node.outcome + if (outcome === null) return t('command.running') + switch (outcome.kind) { + case 'success': + return outcome.text || t('command.done') + case 'error': { + const reason = outcome.text?.trim().split(/\r?\n/u)[0] + return reason ? t('command.failedReason', { reason }) : t('command.failed') + } + /* v8 ignore next -- CommandNode restricts outcomes to success or error. */ + default: return assertNever(outcome.kind) + } +} + +/** + * Render the recorded Team command with the shared agent glyph and disclosure. + * @param props - command record and localized Team text. + * @returns an outcome row; recorded failures and multiline output remain expandable. + */ +export function TeamCommandRow({ node, t }: Pick) { + const [expanded, setExpanded] = useState(false) + const running = node.outcome === null + const failed = node.outcome?.kind === 'error' + const summary = commandSummary(node, t) + const body = node.outcome?.text + const expandable = body !== undefined && body !== '' && (failed || body.includes('\n')) + return ( +
    + { setExpanded(value => !value) }} + collapsedContent={( + <> + + {summary} + + )} + > +
    {body}
    +
    +
    + ) +} diff --git a/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.module.css b/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.module.css new file mode 100644 index 0000000000..5763edbcbc --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.module.css @@ -0,0 +1,31 @@ +.dialog { + width: min(440px, 100%); + max-height: 100%; +} + +.content { + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; +} + +.copy { + min-width: 0; + overflow-wrap: anywhere; + color: var(--dsw-alias-label-secondary); + font-size: 14px; + line-height: 22px; +} + +.copy p { + margin: 0; +} + +.copy p + p { + margin-top: 12px; +} + +.error { + color: var(--dsw-alias-state-error-primary); + overflow-wrap: anywhere; +} diff --git a/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.tsx b/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.tsx new file mode 100644 index 0000000000..e02bc87ba3 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamDisableConfirmation.tsx @@ -0,0 +1,76 @@ +/** Session-targeted confirmation that outlives the model menu which opened it. */ +import { useState } from 'react' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives' +import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type { NS } from './locales.ts' +import css from './TeamDisableConfirmation.module.css' + +/** The originating Session remains the target while the dialog is open. */ +export interface TeamDisableRequest { + sessionId: SessionId +} + +/** Confirmation request and Session-bound selection callbacks supplied by the plugin. */ +export interface TeamDisableConfirmationInjected { + hooks: { disableRequest: HostObservable } + cancelDisable: (sessionId: SessionId) => void + disableTeam: (sessionId: SessionId) => Promise +} + +/** Root overlay props, independent of the model menu lifetime. */ +export type TeamDisableConfirmationProps = PropsRuntime<'shell.overlay'> + & InjectFace & PropsLocale + +/** + * Render the requested confirmation outside the model menu. + * @param props - request observation, command callbacks, and localized text. + * @returns the confirmation, or nothing when no request is pending. + */ +export function TeamDisableConfirmation({ useDisableRequest, ...props }: TeamDisableConfirmationProps) { + const request = useDisableRequest(value => value) + if (request === null) return null + return +} + +/** One confirmation keeps its failure visible until retry or cancellation. */ +function DisableConfirmationForm({ sessionId, cancelDisable, disableTeam, t }: { + sessionId: SessionId + cancelDisable: TeamDisableConfirmationInjected['cancelDisable'] + disableTeam: TeamDisableConfirmationInjected['disableTeam'] + t: TeamDisableConfirmationProps['t'] +}) { + const [state, setState] = useState<{ kind: 'ready' } | { kind: 'saving' } | { kind: 'failed'; message: string }>({ kind: 'ready' }) + const saving = state.kind === 'saving' + const cancel = (): void => { + if (!saving) cancelDisable(sessionId) + } + const confirm = (): void => { + if (saving) return + setState({ kind: 'saving' }) + void disableTeam(sessionId).then((failure) => { + if (failure === null) cancelDisable(sessionId) + else setState({ kind: 'failed', message: failure }) + }, (error: unknown) => { + setState({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) + }) + } + return ( + + + + + )} + > +
    +

    {t('disable.description')}

    +

    {t('disable.warning')}

    +
    + {state.kind === 'failed' &&

    {t('mode.failed', { message: state.message })}

    } +
    + ) +} diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css new file mode 100644 index 0000000000..75eedfb3e7 --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.module.css @@ -0,0 +1,52 @@ +.row { + position: relative; + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + min-height: 34px; + padding: 0 8px; + border-radius: var(--dsw-radius-md); + color: var(--dsw-alias-label-primary); + font-size: 13px; + line-height: 20px; +} + +.label { + display: inline-flex; + align-items: center; + gap: 4px; + min-width: 0; +} + +.infoButton { + position: relative; + z-index: 1; + flex: none; + width: 20px; + height: 20px; + padding: 0; + color: var(--dsw-alias-label-caption); +} + +/* Extend the native switch hit target without nesting the information button. */ +.row .toggle { + position: static; +} + +.toggle::after { + content: ''; + position: absolute; + inset: 0; + border-radius: var(--dsw-radius-md); +} + +.row:has(.toggle:focus-visible) { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .row:has(.toggle:not(:disabled)):hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} diff --git a/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx new file mode 100644 index 0000000000..cd0d3dcafa --- /dev/null +++ b/packages/client/ui-agent-team/src/client/TeamModeToggle.tsx @@ -0,0 +1,70 @@ +/** Session-owned Agent Teams selection in the model and reasoning menu. */ + +import { useState } from 'react' +import { Button, IconInfoOutlineRegular, Switch, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' +import type {} from '@deepseek-ai/dsh-agent-team/client' +import type {} from '@deepseek-ai/dsh-agent' +import type { NS } from './locales.ts' +import css from './TeamModeToggle.module.css' + +/** Session selection callbacks supplied by the Client plugin. */ +export interface TeamModeToggleInjected { + /** Save the selection; null means success, otherwise the string describes the failure. */ + selectTeamMode: (enabled: boolean) => Promise + /** Open a Session-targeted confirmation outside this menu. */ + requestDisableConfirmation: () => void +} + +/** Full props of the model-menu Team switch. */ +export type TeamModeToggleProps = PropsRuntime<'conversation.input.model.options'> + & PropsLocale & TeamModeToggleInjected + +/** + * Render the saved selection without an optimistic update. + * @param props - Session projection, menu state, localized copy, and selection callback. + * @returns the Team switch when the capability projection is available. + */ +export function TeamModeToggle(props: TeamModeToggleProps) { + const addressedChild = props.useSession(snapshot => snapshot.subagent !== null) + const listedChild = props.useSessions(state => state.byId[props.sessionId]?.origin === 'subagent') + if (addressedChild || listedChild) return null + return +} + +/** Read and change the selection only for root Sessions. */ +function RootTeamModeToggle({ + useProjection, locked, dismiss, reportFailure, selectTeamMode, requestDisableConfirmation, t, +}: TeamModeToggleProps) { + const mode = useProjection('agentTeam') + const modelSelection = useProjection('modelSelection') + const [pending, setPending] = useState(false) + if (mode === undefined) return null + const select = (enabled: boolean): void => { + if (!enabled && modelSelection !== undefined && modelSelection.lastUsed !== null) { + dismiss() + requestDisableConfirmation() + return + } + setPending(true) + void selectTeamMode(enabled).then((failure) => { + if (failure !== null) reportFailure(t('mode.failed', { message: failure })) + }, (error: unknown) => { + reportFailure(t('mode.failed', { message: error instanceof Error ? error.message : String(error) })) + }).finally(() => { setPending(false) }) + } + return ( +
    + + {t('mode.label')} + + + + + +
    + ) +} diff --git a/packages/experimental/client-ui-agent-team/src/client/index.ts b/packages/client/ui-agent-team/src/client/index.ts similarity index 60% rename from packages/experimental/client-ui-agent-team/src/client/index.ts rename to packages/client/ui-agent-team/src/client/index.ts index a4896c82af..23de9e7ee5 100644 --- a/packages/experimental/client-ui-agent-team/src/client/index.ts +++ b/packages/client/ui-agent-team/src/client/index.ts @@ -1,14 +1,14 @@ -/** Browser entry registering the Agent Teams conversation-header action. */ +/** Browser entry registering the task-board sections in the subagent catalog. */ import type { Context as ClientContext } from '@deepseek-ai/cordis' import { registerAgentTeamUi } from './mount.ts' export { inject } from './mount.ts' -export type { TeamActionInjected, TeamActionProps } from './TeamAction.tsx' +export type { TeamBoardProps } from './TeamBoard.tsx' export type { TeamKey } from './locales.ts' /** - * Register the Team locale dictionaries and header action on the Client Context. + * Register the task-board locale dictionaries and catalog sections on the Client Context. * @param ctx - Client Context with the declared `inject` services available. */ export function apply(ctx: ClientContext): void { diff --git a/packages/client/ui-agent-team/src/client/locales.ts b/packages/client/ui-agent-team/src/client/locales.ts new file mode 100644 index 0000000000..0c5b29a4fb --- /dev/null +++ b/packages/client/ui-agent-team/src/client/locales.ts @@ -0,0 +1,279 @@ +/** Agent teamwork Web dictionaries. */ + +/** Locale namespace owned by the Agent teamwork Web UI. */ +export const NS = 'agent-team' + +/** Simplified Chinese dictionary and key source. */ +export const zh = { + 'progress.completed': '{count} 已完成', + 'progress.active': '{count} 进行中', + 'progress.pending': '{count} 待处理', + 'command.title': '智能体团队协作', + 'command.running': '执行中', + 'command.done': '已完成', + 'command.failed': '执行失败', + 'command.failedReason': '执行失败:{reason}', + trigger: '任务板', + 'mode.label': '启用智能体团队协作', + 'mode.infoLabel': '关于智能体团队协作', + 'mode.description': '通过共享任务板协调多个智能体的分工与进度,复杂任务表现更佳,token 开销也相应更高。', + 'mode.failed': '无法确认智能体团队协作设置已保存,请重试:{message}', + 'disable.title': '确认停用智能体团队协作?', + 'disable.description': '对话过程中停用智能体团队协作,将停止共享任务工具和团队协调指令。', + 'disable.warning': '停用后可能影响缓存复用、增加后续 token 用量与开销,并影响当前任务的协作效果。', + 'disable.cancel': '取消', + 'disable.confirm': '确认停用', + 'disable.close': '关闭', + loading: '正在加载任务板…', + unavailable: '任务板暂不可用', + failure: '任务记录无效:{message}', + empty: '暂无共享任务,可以通过对话创建', + tasks: '共享任务', + owner: '负责人', + unowned: '未分配', + blocked: '被依赖阻塞', + 'status.pending': '待处理', + 'status.in_progress': '进行中', + 'status.completed': '已完成', +} satisfies Record + +/** Agent teamwork locale key union. */ +export type TeamKey = keyof typeof zh + +/** English dictionary checked against the Chinese key set. */ +export const en = { + 'progress.completed': '{count} completed', + 'progress.active': '{count} in progress', + 'progress.pending': '{count} pending', + 'command.title': 'Agent teamwork', + 'command.running': 'Running', + 'command.done': 'Completed', + 'command.failed': 'Failed', + 'command.failedReason': 'Failed: {reason}', + trigger: 'Task board', + 'mode.label': 'Enable agent teamwork', + 'mode.infoLabel': 'About agent teamwork', + 'mode.description': 'Coordinate work and progress across agents with a shared task board for better results on complex tasks, with correspondingly higher token costs.', + 'mode.failed': 'Could not confirm the agent teamwork setting was saved. Try again: {message}', + 'disable.title': 'Disable agent teamwork?', + 'disable.description': 'Disabling agent teamwork during a conversation stops the use of shared task tools and team coordination instructions.', + 'disable.warning': 'Disabling it may affect cache reuse, increase subsequent token usage and costs, and affect collaboration on the current task.', + 'disable.cancel': 'Cancel', + 'disable.confirm': 'Disable', + 'disable.close': 'Close', + loading: 'Loading task board…', + unavailable: 'Task board is unavailable', + failure: 'Invalid persisted task record: {message}', + empty: 'No shared tasks yet. Create them through the conversation.', + tasks: 'Shared tasks', + owner: 'Owner', + unowned: 'Unowned', + blocked: 'Blocked by dependencies', + 'status.pending': 'Pending', + 'status.in_progress': 'In progress', + 'status.completed': 'Completed', +} satisfies Record + +/** Japanese copy, checked against the English keys. */ +export const ja = { + 'progress.completed': '{count}件完了', + 'progress.active': '{count}件進行中', + 'progress.pending': '{count}件保留中', + 'command.title': 'エージェント連携', + 'command.running': '実行中', + 'command.done': '完了', + 'command.failed': '実行失敗', + 'command.failedReason': '実行失敗: {reason}', + 'mode.label': 'エージェント連携を有効にする', + 'mode.infoLabel': 'エージェント連携について', + 'mode.description': '共有タスクボードで複数のエージェントの分担と進捗を調整します。複雑なタスクでより良い結果が得られますが、その分トークンのコストも高くなります。', + 'mode.failed': 'エージェント連携の設定が保存されたことを確認できませんでした。再試行してください: {message}', + 'disable.title': 'エージェント連携を無効にしますか?', + 'disable.description': '会話中にエージェント連携を無効にすると、共有タスクツールとチーム調整用の指示の使用が停止されます。', + 'disable.warning': '無効にすると、キャッシュの再利用に影響し、その後のトークン使用量や費用が増加する可能性があります。また、現在のタスクでの連携に影響する可能性があります。', + 'disable.cancel': 'キャンセル', + 'disable.confirm': '無効にする', + 'disable.close': '閉じる', + 'trigger': 'タスクボード', + 'loading': 'タスクボードを読み込み中…', + 'unavailable': 'タスクボードは利用できません', + 'failure': '保存されたタスクレコードが無効です: {message}', + 'empty': '共有タスクはまだありません。会話から作成してください。', + 'tasks': '共有タスク', + 'owner': 'オーナー', + 'unowned': 'オーナーなし', + 'blocked': '依存関係によりブロック中', + 'status.pending': '保留中', + 'status.in_progress': '進行中', + 'status.completed': '完了', +} satisfies Record + +/** Spanish dictionary, checked against the English keys. */ +export const es = { + 'progress.completed': '{count} completado', + 'progress.active': '{count} en progreso', + 'progress.pending': '{count} pendiente', + 'command.title': 'Colaboración entre agentes', + 'command.running': 'En ejecución', + 'command.done': 'Completado', + 'command.failed': 'Error', + 'command.failedReason': 'Error: {reason}', + 'mode.label': 'Activar colaboración entre agentes', + 'mode.infoLabel': 'Acerca de la colaboración entre agentes', + 'mode.description': 'Coordina el trabajo y el progreso de varios agentes mediante un tablero de tareas compartido, con mejores resultados en tareas complejas y un coste de tokens proporcionalmente mayor.', + 'mode.failed': 'No se pudo confirmar que se guardó la configuración de colaboración entre agentes. Inténtalo de nuevo: {message}', + 'disable.title': '¿Desactivar la colaboración entre agentes?', + 'disable.description': 'Desactivar la colaboración entre agentes durante una conversación detiene el uso de las herramientas de tareas compartidas y las instrucciones de coordinación del equipo.', + 'disable.warning': 'La desactivación puede afectar a la reutilización de la caché, aumentar el consumo posterior de tokens y los costes, y afectar a la colaboración en la tarea actual.', + 'disable.cancel': 'Cancelar', + 'disable.confirm': 'Confirmar desactivación', + 'disable.close': 'Cerrar', + trigger: 'Tablero de tareas', + loading: 'Cargando tablero de tareas…', + unavailable: 'El tablero de tareas no está disponible', + failure: 'Registro de tarea persistente no válido: {message}', + empty: 'Aún no hay tareas compartidas. Créelos a través de la conversación.', + tasks: 'Tareas compartidas', + owner: 'propietario', + unowned: 'Sin dueño', + blocked: 'Bloqueado por dependencias', + 'status.pending': 'Pendiente', + 'status.in_progress': 'En progreso', + 'status.completed': 'Completado', +} satisfies Record + +/** French dictionary, checked against the English keys. */ +export const fr = { + 'progress.completed': '{count} terminé', + 'progress.active': '{count} en cours', + 'progress.pending': '{count} en attente', + 'command.title': 'Collaboration entre agents', + 'command.running': 'En cours', + 'command.done': 'Terminé', + 'command.failed': 'Échec', + 'command.failedReason': 'Échec : {reason}', + 'mode.label': 'Activer la collaboration entre agents', + 'mode.infoLabel': 'À propos de la collaboration entre agents', + 'mode.description': 'Coordonnez la répartition du travail et la progression de plusieurs agents via un tableau de tâches partagé, pour de meilleurs résultats sur les tâches complexes, avec un coût en tokens plus élevé en contrepartie.', + 'mode.failed': 'Impossible de confirmer l’enregistrement du réglage de collaboration entre agents. Réessayez : {message}', + 'disable.title': 'Désactiver la collaboration entre agents ?', + 'disable.description': 'Désactiver la collaboration entre agents pendant une conversation arrête l’utilisation des outils de tâches partagées et des instructions de coordination de l’équipe.', + 'disable.warning': 'La désactivation peut affecter la réutilisation du cache, augmenter la consommation ultérieure de tokens et les coûts, et affecter la collaboration sur la tâche en cours.', + 'disable.cancel': 'Annuler', + 'disable.confirm': 'Confirmer la désactivation', + 'disable.close': 'Fermer', + trigger: 'Tableau des tâches', + loading: 'Chargement du tableau des tâches…', + unavailable: 'Le tableau des tâches n’est pas disponible', + failure: 'Enregistrement de tâche persistant non valide : {message}', + empty: "Aucune tâche partagée pour l'instant. Créez-les à travers la conversation.", + tasks: 'Tâches partagées', + owner: 'Propriétaire', + unowned: 'Sans propriétaire', + blocked: 'Bloqué par les dépendances', + 'status.pending': 'En attente', + 'status.in_progress': 'En cours', + 'status.completed': 'Terminé', +} satisfies Record + +/** German dictionary, checked against the English keys. */ +export const de = { + 'progress.completed': '{count} abgeschlossen', + 'progress.active': '{count} in Bearbeitung', + 'progress.pending': '{count} ausstehend', + 'command.title': 'Agentenzusammenarbeit', + 'command.running': 'Wird ausgeführt', + 'command.done': 'Abgeschlossen', + 'command.failed': 'Fehlgeschlagen', + 'command.failedReason': 'Fehlgeschlagen: {reason}', + 'mode.label': 'Agentenzusammenarbeit aktivieren', + 'mode.infoLabel': 'Über Agentenzusammenarbeit', + 'mode.description': 'Koordiniert die Arbeitsteilung und den Fortschritt mehrerer Agenten über eine gemeinsame Aufgabenübersicht. Erzielt bessere Ergebnisse bei komplexen Aufgaben, bei entsprechend höheren Tokenkosten.', + 'mode.failed': 'Das Speichern der Einstellung zur Agentenzusammenarbeit konnte nicht bestätigt werden. Erneut versuchen: {message}', + 'disable.title': 'Agentenzusammenarbeit deaktivieren?', + 'disable.description': 'Wenn Sie die Agentenzusammenarbeit während eines Gesprächs deaktivieren, werden die Werkzeuge für gemeinsame Aufgaben und die Anweisungen zur Teamkoordination nicht mehr verwendet.', + 'disable.warning': 'Die Deaktivierung kann die Wiederverwendung des Caches beeinträchtigen, den späteren Tokenverbrauch und die Kosten erhöhen und die Zusammenarbeit bei der aktuellen Aufgabe beeinträchtigen.', + 'disable.cancel': 'Abbrechen', + 'disable.confirm': 'Deaktivierung bestätigen', + 'disable.close': 'Schließen', + trigger: 'Aufgabenübersicht', + loading: 'Aufgabenübersicht wird geladen…', + unavailable: 'Aufgabenübersicht ist nicht verfügbar', + failure: 'Ungültiger gespeicherter Aufgabeneintrag: {message}', + empty: 'Noch keine geteilten Aufgaben. Erstellen Sie sie durch das Gespräch.', + tasks: 'Geteilte Aufgaben', + owner: 'Besitzer', + unowned: 'Unbesessen', + blocked: 'Blockiert durch Abhängigkeiten', + 'status.pending': 'Ausstehend', + 'status.in_progress': 'In Bearbeitung', + 'status.completed': 'Abgeschlossen', +} satisfies Record + +/** Russian dictionary, checked against the English keys. */ +export const ru = { + 'progress.completed': '{count} завершено', + 'progress.active': '{count} в процессе', + 'progress.pending': '{count} в ожидании', + 'command.title': 'Совместная работа агентов', + 'command.running': 'Выполняется', + 'command.done': 'Завершено', + 'command.failed': 'Ошибка', + 'command.failedReason': 'Ошибка: {reason}', + 'mode.label': 'Включить совместную работу агентов', + 'mode.infoLabel': 'О совместной работе агентов', + 'mode.description': 'Координируйте распределение работы и прогресс нескольких агентов с помощью общей доски задач: лучшие результаты в сложных задачах при соответственно более высоких затратах на токены.', + 'mode.failed': 'Не удалось подтвердить сохранение настройки совместной работы агентов. Повторите попытку: {message}', + 'disable.title': 'Отключить совместную работу агентов?', + 'disable.description': 'Отключение совместной работы агентов во время разговора прекращает использование инструментов общих задач и инструкций по координации команды.', + 'disable.warning': 'Отключение может повлиять на повторное использование кэша, увеличить последующий расход токенов и затраты, а также повлиять на совместную работу над текущей задачей.', + 'disable.cancel': 'Отмена', + 'disable.confirm': 'Подтвердить отключение', + 'disable.close': 'Закрыть', + trigger: 'Доска задач', + loading: 'Загрузка доски задач…', + unavailable: 'Доска задач недоступна', + failure: 'Недопустимая сохранённая запись задачи: {message}', + empty: 'Общие задачи пока отсутствуют. Создайте их посредством разговора.', + tasks: 'Общие задачи', + owner: 'Владелец', + unowned: 'Невладеющий', + blocked: 'Заблокировано зависимостями', + 'status.pending': 'Ожидается', + 'status.in_progress': 'В процессе', + 'status.completed': 'Завершено', +} satisfies Record + +/** Portuguese dictionary, checked against the English keys. */ +export const pt = { + 'progress.completed': '{count} concluído', + 'progress.active': '{count} em andamento', + 'progress.pending': '{count} pendente', + 'command.title': 'Colaboração entre agentes', + 'command.running': 'Em execução', + 'command.done': 'Concluído', + 'command.failed': 'Falha', + 'command.failedReason': 'Falha: {reason}', + 'mode.label': 'Ativar colaboração entre agentes', + 'mode.infoLabel': 'Sobre a colaboração entre agentes', + 'mode.description': 'Coordene a divisão do trabalho e o progresso de vários agentes com um quadro de tarefas compartilhado, para melhores resultados em tarefas complexas, com custos de tokens proporcionalmente maiores.', + 'mode.failed': 'Não foi possível confirmar que a configuração de colaboração entre agentes foi salva. Tente novamente: {message}', + 'disable.title': 'Desativar a colaboração entre agentes?', + 'disable.description': 'Desativar a colaboração entre agentes durante uma conversa interrompe o uso das ferramentas de tarefas compartilhadas e das instruções de coordenação da equipe.', + 'disable.warning': 'A desativação pode afetar a reutilização do cache, aumentar o consumo posterior de tokens e os custos, e afetar a colaboração na tarefa atual.', + 'disable.cancel': 'Cancelar', + 'disable.confirm': 'Confirmar desativação', + 'disable.close': 'Fechar', + trigger: 'Quadro de tarefas', + loading: 'Carregando quadro de tarefas…', + unavailable: 'O quadro de tarefas não está disponível', + failure: 'Registro de tarefa persistente inválido: {message}', + empty: 'Ainda não há tarefas compartilhadas. Crie-os através da conversa.', + tasks: 'Tarefas compartilhadas', + owner: 'Proprietário', + unowned: 'Sem dono', + blocked: 'Bloqueado por dependências', + 'status.pending': 'Pendente', + 'status.in_progress': 'Em andamento', + 'status.completed': 'Concluído', +} satisfies Record diff --git a/packages/client/ui-agent-team/src/client/mount.ts b/packages/client/ui-agent-team/src/client/mount.ts new file mode 100644 index 0000000000..833267e39e --- /dev/null +++ b/packages/client/ui-agent-team/src/client/mount.ts @@ -0,0 +1,71 @@ +/** Source-safe task-board browser registration. */ + +import type { Context as ClientContext } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import type {} from '@deepseek-ai/dsh-client-ui-subagent/client' +import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-ui-model-selection/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { TeamDisableConfirmation, type TeamDisableConfirmationInjected, type TeamDisableRequest } from './TeamDisableConfirmation.tsx' +import { TeamModeToggle, type TeamModeToggleInjected } from './TeamModeToggle.tsx' +import { TeamBoard } from './TeamBoard.tsx' +import { TeamCommandRow } from './TeamCommandRow.tsx' +import { en, ja, es, fr, de, ru, pt, NS, zh, type TeamKey } from './locales.ts' + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + /** Shared task-board copy. */ + 'agent-team': TeamKey + } +} + +/** Required browser services for slots and localized copy. */ +export const inject = ['slots', 'locale'] + +/** + * Register the task-board dictionaries and subagent catalog sections. + * The panel reads the root Session’s `agentTeam` projection through standard Session hooks. + * @param ctx - Client Context carrying the injected locale and slot services. + */ +export function registerAgentTeamUi(ctx: ClientContext): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'client-ui-agent-team: dictionaries') + ctx.slots.inject('conversation.chat.commandview', () => ctx.slots.register({ + name: 'conversation.chat.commandview', key: 'team', locale: NS, + }, TeamCommandRow)) + ctx.inject(['remote', 'remote.agentTeams'], (scope) => { + scope.slots.inject('shell.overlay', function* () { + const disableRequest = createSnapshotStore(null) + const selectTeamMode = async (sessionId: SessionId, enabled: boolean): Promise => { + const response = await scope.remote.agentTeams.setEnabled(sessionId, enabled) + return response.ok ? null : response.error.message + } + yield () => { disableRequest.set(null) } + yield scope.slots.register({ + name: 'shell.overlay', id: 'agent-team.disable', locale: NS, + inject: (): TeamDisableConfirmationInjected => ({ + hooks: { disableRequest }, + cancelDisable: (sessionId) => { + if (disableRequest.getSnapshot()?.sessionId === sessionId) disableRequest.set(null) + }, + disableTeam: sessionId => selectTeamMode(sessionId, false), + }), + }, TeamDisableConfirmation) + yield scope.slots.inject('conversation.input.model.options', () => scope.slots.register({ + name: 'conversation.input.model.options', + id: 'agent-team', + locale: NS, + inject: (sessionId): TeamModeToggleInjected => ({ + selectTeamMode: enabled => selectTeamMode(sessionId, enabled), + requestDisableConfirmation: () => { disableRequest.set({ sessionId }) }, + }), + }, TeamModeToggle)) + }) + }) + ctx.slots.inject('conversation.session.header.actions.subagent.footer', () => ctx.slots.register({ + name: 'conversation.session.header.actions.subagent.footer', id: 'agent-team', locale: NS, + }, TeamBoard)) +} diff --git a/packages/experimental/client-ui-agent-team/src/css-modules.d.ts b/packages/client/ui-agent-team/src/css-modules.d.ts similarity index 100% rename from packages/experimental/client-ui-agent-team/src/css-modules.d.ts rename to packages/client/ui-agent-team/src/css-modules.d.ts diff --git a/packages/experimental/client-ui-agent-team/src/index.ts b/packages/client/ui-agent-team/src/index.ts similarity index 100% rename from packages/experimental/client-ui-agent-team/src/index.ts rename to packages/client/ui-agent-team/src/index.ts diff --git a/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts new file mode 100644 index 0000000000..ba964a033f --- /dev/null +++ b/packages/client/ui-agent-team/tests/browser-plugin.client.spec.ts @@ -0,0 +1,135 @@ +import { Context } from '@deepseek-ai/cordis' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { SessionId } from '@deepseek-ai/dsh-session/types' +import { RemoteError, TestRemote } from '@deepseek-ai/dsh-client-test-runtime' +import { TeamModeToggle, type TeamModeToggleInjected } from '../src/client/TeamModeToggle.tsx' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import { TeamBoard } from '../src/client/TeamBoard.tsx' +import { TeamCommandRow } from '../src/client/TeamCommandRow.tsx' +import { TeamDisableConfirmation, type TeamDisableConfirmationInjected } from '../src/client/TeamDisableConfirmation.tsx' +import { apply, inject } from '../src/client/index.ts' +import { apply as nodeApply } from '../src/index.ts' + +async function bench() { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + ctx.provide('locale', new LocaleRuntime(ctx)) + await ctx.plugin(SlotRegistry).await() + const collapseHeader = ctx.slots.register({ + name: 'root', + children: { + 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' }, + 'conversation.input.model': { kind: 'single', scope: 'session' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + }, + } as never, () => null) + const fiber = ctx.plugin({ inject: [...inject], apply }) + await fiber.await() + const entry = () => ctx.slots.entries('conversation.session.header.actions.subagent.footer') + .find(candidate => candidate.component === TeamBoard) + return { ctx, fiber, entry, collapseHeader } +} + +describe('task-board browser plugin', () => { + it('registers a disposable root task-board section without navigation or Team Remote services', async () => { + const b = await bench() + expect(inject).toEqual(['slots', 'locale']) + expect(b.entry()).toMatchObject({ + options: { id: 'agent-team' }, + locale: 'agent-team', + }) + expect(b.entry()!.inject).toBeUndefined() + expect(b.ctx.slots.entries('conversation.session.header.actions')).toHaveLength(0) + const t = b.ctx.locale.bind('agent-team') + expect(t('trigger')).toBe('Task board') + await b.fiber.dispose() + expect(b.entry()).toBeUndefined() + expect(t('empty')).toBe('empty') + }) + + it('re-registers when the conversation header slot is declared again', async () => { + const b = await bench() + expect(b.entry()).toBeDefined() + b.collapseHeader() + expect(b.entry()).toBeUndefined() + b.ctx.slots.register({ + name: 'root', + children: { 'conversation.session.header.actions.subagent.footer': { kind: 'list', scope: 'session' } }, + } as never, () => null) + await Promise.resolve() + expect(b.entry()).toBeDefined() + await b.fiber.dispose() + }) + + it('registers the mode switch when Agent Teams arrives and reports each execution outcome', async () => { + const b = await bench() + b.ctx.slots.register({ + name: 'conversation.input.model', + children: { 'conversation.input.model.options': { kind: 'list', scope: 'session' } }, + } as never, () => null) + const entry = () => b.ctx.slots.entries('conversation.input.model.options') + .find(candidate => candidate.component === TeamModeToggle) + expect(entry()).toBeUndefined() + const setEnabled = vi.fn() + new TestRemote(b.ctx, { agentTeams: { setEnabled } }) + await vi.waitFor(() => { expect(entry()).toBeDefined() }) + const injected = entry()!.inject as (sessionId: SessionId) => Record + const value: object = injected(SessionId('chosen-session')) + const mode = value as TeamModeToggleInjected + setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) + await expect(mode.selectTeamMode(true)).resolves.toBeNull() + expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', true) + setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) + await expect(mode.selectTeamMode(false)).resolves.toBeNull() + expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', false) + setEnabled.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'connection failed', {}) }) + await expect(mode.selectTeamMode(true)).resolves.toBe('connection failed') + const overlayEntry = () => b.ctx.slots.entries('shell.overlay').find(candidate => candidate.component === TeamDisableConfirmation) + const overlayValue: object = overlayEntry()!.inject!() + const overlay = overlayValue as TeamDisableConfirmationInjected + const request = overlay.hooks.disableRequest + expect(request.getSnapshot()).toBeNull() + const beforeConfirmation = setEnabled.mock.calls.length + mode.requestDisableConfirmation() + expect(request.getSnapshot()).toEqual({ sessionId: 'chosen-session' }) + expect(setEnabled).toHaveBeenCalledTimes(beforeConfirmation) + overlay.cancelDisable(SessionId('other-session')) + expect(request.getSnapshot()).toEqual({ sessionId: 'chosen-session' }) + setEnabled.mockResolvedValueOnce({ ok: true, value: undefined }) + await expect(overlay.disableTeam(SessionId('chosen-session'))).resolves.toBeNull() + expect(setEnabled).toHaveBeenLastCalledWith('chosen-session', false) + overlay.cancelDisable(SessionId('chosen-session')) + expect(request.getSnapshot()).toBeNull() + mode.requestDisableConfirmation() + await b.fiber.dispose() + expect(entry()).toBeUndefined() + expect(overlayEntry()).toBeUndefined() + expect(request.getSnapshot()).toBeNull() + }) + + it('binds Team command receipts to the command slot lifetime without Remote services', async () => { + const b = await bench() + const entry = () => b.ctx.slots.entries('conversation.chat.commandview').find(value => value.component === TeamCommandRow) + expect(entry()).toBeUndefined() + b.collapseHeader() + const registerParent = () => b.ctx.slots.register({ + name: 'root', + children: { 'conversation.chat.commandview': { kind: 'keyed', scope: 'session' } }, + } as never, () => null) + const collapse = registerParent() + await vi.waitFor(() => { expect(entry()).toBeDefined() }) + expect(entry()).toMatchObject({ options: { key: 'team' }, locale: 'agent-team' }) + expect(entry()!.inject).toBeUndefined() + collapse() + expect(entry()).toBeUndefined() + registerParent() + await vi.waitFor(() => { expect(entry()).toBeDefined() }) + await b.fiber.dispose() + expect(entry()).toBeUndefined() + }) + + it('keeps the node half inert', () => { + expect(() => { nodeApply() }).not.toThrow() + }) +}) diff --git a/packages/client/ui-agent-team/tests/team-board.client.spec.tsx b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx new file mode 100644 index 0000000000..b09aedc4e5 --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-board.client.spec.tsx @@ -0,0 +1,416 @@ +// @vitest-environment jsdom + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { TeamProjection, TeamTaskId, TeamTaskView as TeamTask } from '@deepseek-ai/dsh-agent-team/client' +import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts' +import { TeamBoard, type TeamBoardProps } from '../src/client/TeamBoard.tsx' +import { en, zh } from '../src/client/locales.ts' + +afterEach(() => { + cleanup() + vi.useRealTimers() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) + +const SESSION = 'root-session-id' as SessionId +const WORKER = 'worker-id' as SessionId +const NESTED = 'nested-id' as SessionId +const TASK_1 = 'task-1' as TeamTaskId +const TASK_2 = 'task-2' as TeamTaskId +const task: TeamTask = { + id: TASK_1, + revision: 1, + subject: 'Implement runtime', + description: 'Build the Team runtime', + status: 'in_progress', + ownerId: SESSION, + blockedBy: [], + writeScopes: ['src'], + ready: false, + writeScopeWarnings: ['write scopes overlap with task-2'], +} +const team: TeamProjection = { enabled: true, tasks: [task] } +type Projections = SessionListState['projectionsBySession'] + +function summary(id: SessionId, title?: string): SessionSummary { + return { + id, ...(title === undefined ? {} : { title }), displayTitle: title ?? id, + running: false, retainedBy: {}, blank: false, updatedAt: 0, + } +} + +function bench(options: { + projections?: Projections + sessionId?: SessionId + byId?: Record + value?: TeamProjection +} = {}) { + const sessionId = options.sessionId ?? SESSION + const byId = options.byId ?? { [SESSION]: summary(SESSION) } + const sessions = createSnapshotStore({ + ids: Object.keys(byId) as SessionId[], byId, phase: 'ready', + projectionsBySession: options.projections ?? { [SESSION]: { state: 'ready', error: null, values: { agentTeam: options.value ?? team } } }, + }) + const useProjection = ((_key: 'agentTeam', selector?: (value: TeamProjection | undefined) => unknown) => + bindSnapshotSelector(sessions)((state) => { + const value = state.projectionsBySession[sessionId]?.values.agentTeam + return selector === undefined ? value : selector(value) + })) as TeamBoardProps['useProjection'] + const props = { + sessionId, useProjection, + useSessions: bindSnapshotSelector(sessions), + t: makeTranslate(zh, commonZh), + } as TeamBoardProps + return { props, sessions } +} + +function setProjectionSnapshot( + sessions: ReturnType['sessions'], sessionId: SessionId, snapshot: Projections[SessionId], +): void { + act(() => { + const current = sessions.getSnapshot() + sessions.set({ ...current, projectionsBySession: { ...current.projectionsBySession, [sessionId]: snapshot } }) + }) +} + +function setProjection(sessions: ReturnType['sessions'], sessionId: SessionId, value: TeamProjection): void { + setProjectionSnapshot(sessions, sessionId, { state: 'ready', error: null, values: { agentTeam: value } }) +} + +function row(subject = task.subject): HTMLElement { + return screen.getByRole('button', { name: new RegExp(subject, 'u') }) +} + +function ownerValue(): string | null { + return document.querySelector('[data-team-task-owner] span:last-child')?.textContent ?? null +} + +function enableTooltips(): void { + class TooltipObserver implements ResizeObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element): void { + const size = { inlineSize: 160, blockSize: 30 } + this.callback([{ + target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), + }], this) + } + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', TooltipObserver) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) +} + +describe('TeamBoard', () => { + it('shows a nonclickable Checklist header and compact initially closed rows', () => { + const b = bench() + render() + const heading = screen.getByRole('heading') + expect(heading.textContent).toBe(`${zh.tasks}${b.props.t('progress.active', { count: 1 })}`) + expect(heading.querySelector('button')).toBeNull() + expect(heading.querySelector('[data-icon="dsw-icon-checklist-outline-regular"]')).toBeTruthy() + expect(screen.getAllByRole('button')).toEqual([row()]) + expect(row().getAttribute('aria-expanded')).toBe('false') + expect(row().textContent).toBe(task.subject) + expect(within(row()).getByRole('img', { name: zh['status.in_progress'] })).toBeTruthy() + expect(row().querySelector('[data-state="ongoing"]')).toBeTruthy() + expect(row().querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeTruthy() + expect(screen.queryByText(task.description)).toBeNull() + expect(screen.queryByText(zh.owner)).toBeNull() + expect(screen.queryByRole('button', { name: '展开' })).toBeNull() + }) + + it('expands the full description before the owner and keeps only one task open', () => { + const longSubject = 'A complete subject that must remain readable when the task is expanded' + const description = 'First line\n'.repeat(30) + 'Final description line' + const b = bench({ value: { ...team, tasks: [ + { ...task, subject: longSubject, description }, + { ...task, id: TASK_2, subject: 'Review implementation', ownerId: WORKER }, + ] } }) + render() + const first = row(longSubject) + fireEvent.click(first) + expect(first.getAttribute('aria-expanded')).toBe('true') + expect(row(longSubject)).toBe(first) + const details = document.getElementById(first.getAttribute('aria-controls')!)! + const owner = details.querySelector('[data-team-task-owner]')! + expect(owner.tagName).toBe('P') + expect(owner.textContent).toBe(`${zh.owner}: ${SESSION}`) + expect(ownerValue()).toBe(SESSION) + const paragraphs = details.querySelectorAll('p') + expect(paragraphs).toHaveLength(2) + expect(paragraphs[0]?.textContent).toBe(description) + expect(paragraphs[1]).toBe(owner) + expect(details.querySelector('dl, dt, dd')).toBeNull() + expect(screen.queryByText(TASK_1)).toBeNull() + expect(screen.queryByText('src')).toBeNull() + expect(screen.queryByText(task.writeScopeWarnings[0]!)).toBeNull() + expect(screen.getAllByRole('button')).toHaveLength(2) + fireEvent.click(row('Review implementation')) + expect(first.getAttribute('aria-expanded')).toBe('false') + expect(ownerValue()).toBe(WORKER) + expect(document.querySelectorAll('[data-team-task-details]')).toHaveLength(1) + expect(screen.queryByText(description)).toBeNull() + fireEvent.click(row('Review implementation')) + expect(ownerValue()).toBeNull() + expect(screen.getAllByRole('button').every(button => button.getAttribute('aria-expanded') === 'false')).toBe(true) + }) + + it('preserves source order, keeps completed tasks, and excludes deleted tombstones from rows and counts', () => { + const b = bench({ value: { ...team, tasks: [ + { ...task, subject: 'Pending first', status: 'pending', ready: true }, + { ...task, id: TASK_2, subject: 'Completed second', status: 'completed' }, + { ...task, id: 'third' as TeamTaskId, subject: 'Active third' }, + { ...task, id: 'deleted' as TeamTaskId, subject: 'Deleted task', status: 'deleted' }, + ] } }) + render() + expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Pending first', 'Completed second', 'Active third']) + expect(screen.getByRole('heading').textContent).toBe(`${zh.tasks}${[ + b.props.t('progress.completed', { count: 1 }), b.props.t('progress.active', { count: 1 }), b.props.t('progress.pending', { count: 1 }), + ].join('\u2002·\u2002')}`) + expect(screen.queryByText('Deleted task')).toBeNull() + expect(row('Pending first').querySelector('[data-state="idle"]')).toBeTruthy() + expect(row('Completed second').querySelector('[data-state="done"]')).toBeTruthy() + fireEvent.click(row('Completed second')) + expect(row('Completed second').getAttribute('aria-expanded')).toBe('true') + expect(ownerValue()).toBe(SESSION) + expect(screen.getByText(task.description)).toBeTruthy() + }) + + it('announces blocked status without displaying readiness, dependencies, scopes, warnings, or task ids', () => { + const { ownerId: _ownerId, ...unowned } = task + const b = bench({ value: { ...team, tasks: [ + { ...unowned, status: 'pending', blockedBy: [TASK_2, 'missing' as TeamTaskId] }, + { ...task, id: TASK_2, subject: 'Prepare shared types', status: 'completed' }, + ] } }) + render() + expect(within(row()).getByRole('img', { name: zh.blocked })).toBeTruthy() + expect(row().querySelector('[data-state="warning"]')).toBeTruthy() + fireEvent.click(row()) + expect(ownerValue()).toBe(zh.unowned) + const details = document.querySelector('[data-team-task-details]')! + expect(details.textContent).toBe(`${task.description}${zh.owner}: ${zh.unowned}`) + expect(details.querySelector('dl, dt, dd')).toBeNull() + for (const metadata of [ + TASK_1, TASK_2, 'Prepare shared types', 'missing', 'src', task.writeScopeWarnings[0]!, zh.blocked, + ]) expect(within(details).queryByText(metadata)).toBeNull() + expect(b.sessions.getSnapshot().projectionsBySession[SESSION]!.values.agentTeam?.tasks[0]).toEqual({ + ...unowned, status: 'pending', blockedBy: [TASK_2, 'missing' as TeamTaskId], + }) + }) + + it('keeps the pending glyph and shows only the owner when description is empty', () => { + render() + fireEvent.click(row()) + expect(within(row()).getByRole('img', { name: zh['status.pending'] })).toBeTruthy() + expect(row().querySelector('[data-state="idle"]')).toBeTruthy() + expect(ownerValue()).toBe(SESSION) + expect(document.querySelector('[data-team-task-details]')?.children).toHaveLength(1) + expect(document.querySelector('[data-team-task-details] p:not([data-team-task-owner])')).toBeNull() + }) + + it('uses the owner id independently of catalog descriptions and Session titles', () => { + const b = bench({ + byId: { [SESSION]: summary(SESSION), [NESTED]: { ...summary(NESTED, 'Session title'), parentId: WORKER } }, + projections: { + [SESSION]: { state: 'ready', error: null, values: { + agentTeam: { ...team, tasks: [{ ...task, ownerId: NESTED }] }, + } }, + [WORKER]: { state: 'ready', error: null, values: { + subagentCatalog: [{ id: NESTED, createdAt: 0, mode: 'continuable', label: 'Catalog responsibility' }], + } }, + }, + }) + render() + fireEvent.click(row()) + expect(ownerValue()).toBe(NESTED) + setProjectionSnapshot(b.sessions, WORKER, { state: 'ready', error: null, values: {} }) + act(() => { b.sessions.update((draft) => { draft.byId[NESTED] = { ...summary(NESTED), displayTitle: 'Display title' } }) }) + expect(ownerValue()).toBe(NESTED) + setProjection(b.sessions, SESSION, { ...team, tasks: [{ ...task, ownerId: WORKER }] }) + expect(ownerValue()).toBe(WORKER) + }) + + it('uses owner id when neither root nor parent projections exist', () => { + const b = bench({ value: { ...team, tasks: [{ ...task, ownerId: NESTED }] }, byId: { + [NESTED]: { ...summary(NESTED), parentId: WORKER }, + } }) + render() + fireEvent.click(row()) + expect(ownerValue()).toBe(NESTED) + }) + + it('hides retained tasks while Team is disabled and shows them when enabled', () => { + const b = bench() + render() + setProjection(b.sessions, SESSION, { ...team, enabled: false }) + expect(screen.queryByRole('region')).toBeNull() + expect(screen.queryByText(task.subject)).toBeNull() + setProjection(b.sessions, SESSION, team) + expect(row()).toBeTruthy() + }) + + it('accepts absent baselines, capability removal, empty tasks, and deleted-only snapshots', () => { + const b = bench({ projections: {} }) + render() + expect(screen.queryByRole('region')).toBeNull() + setProjectionSnapshot(b.sessions, SESSION, { state: 'idle', error: null, values: { agentTeam: team } }) + expect(row()).toBeTruthy() + setProjectionSnapshot(b.sessions, SESSION, { state: 'idle', error: null, values: {} }) + expect(screen.queryByRole('region')).toBeNull() + for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) { + setProjection(b.sessions, SESSION, { enabled: true, tasks }) + expect(screen.queryByText(zh.empty)).toBeNull() + expect(screen.queryByRole('heading')).toBeNull() + expect(screen.queryByRole('button')).toBeNull() + expect(screen.queryByRole('region')).toBeNull() + expect(document.querySelector('[data-team-panel]')).toBeNull() + } + }) + + it('reads only the current Session projection', () => { + const b = bench({ sessionId: WORKER }) + render() + expect(screen.queryByRole('region')).toBeNull() + setProjection(b.sessions, WORKER, { ...team, tasks: [{ ...task, subject: 'Current task' }] }) + expect(row('Current task')).toBeTruthy() + setProjection(b.sessions, SESSION, { ...team, tasks: [{ ...task, subject: 'Other task' }] }) + expect(screen.queryByText('Other task')).toBeNull() + }) + + it('keeps failures beside valid tasks but shows only an alert without visible tasks', () => { + const b = bench({ value: { ...team, failure: 'revision is not contiguous' } }) + const view = render() + expect(screen.getByRole('alert').textContent).toBe('任务记录无效:revision is not contiguous') + expect(row()).toBeTruthy() + expect(screen.getByRole('heading')).toBeTruthy() + for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) { + setProjectionSnapshot(b.sessions, SESSION, { state: 'ready', error: null, values: { + agentTeam: { enabled: true, tasks, failure: 'invalid task' }, + subagentCatalog: [{ id: WORKER, createdAt: 0, mode: 'continuable', label: 'Worker' }], + } }) + const alert = screen.getByRole('alert') + expect(alert.textContent).toBe('任务记录无效:invalid task') + expect(screen.getAllByRole('alert')).toHaveLength(1) + expect(view.container.textContent).toBe(alert.textContent) + expect(view.container.querySelector('[data-with-members="true"]')).toBeNull() + expect(screen.queryByRole('heading')).toBeNull() + expect(screen.queryByRole('region')).toBeNull() + expect(screen.queryByText(zh.empty)).toBeNull() + expect(document.querySelector('[data-team-panel]')).toBeNull() + } + setProjection(b.sessions, SESSION, { enabled: false, tasks: [], failure: 'invalid task' }) + expect(view.container.childElementCount).toBe(0) + }) + + it('renders nothing for empty or deleted-only tasks even when members exist', () => { + const b = bench() + const view = render() + for (const tasks of [[], [{ ...task, status: 'deleted' as const }]]) { + setProjectionSnapshot(b.sessions, SESSION, { state: 'ready', error: null, values: { + agentTeam: { enabled: true, tasks }, + subagentCatalog: [{ id: WORKER, createdAt: 0, mode: 'continuable', label: 'Worker' }], + } }) + expect(view.container.childElementCount).toBe(0) + } + }) + + it('keeps live updates and expansion tied to task identity without sorting or polling', () => { + const b = bench() + render() + fireEvent.click(row()) + setProjection(b.sessions, SESSION, { ...team, tasks: [ + { ...task, id: TASK_2, subject: 'New task', status: 'pending', ready: true }, + { ...task, status: 'completed', description: 'Updated details' }, + ] }) + expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['New task', task.subject]) + expect(row().getAttribute('aria-expanded')).toBe('true') + expect(row('New task').getAttribute('aria-expanded')).toBe('false') + expect(screen.getByText('Updated details')).toBeTruthy() + setProjection(b.sessions, SESSION, { ...team, tasks: [{ ...task, status: 'deleted' }] }) + expect(screen.queryByText('Updated details')).toBeNull() + }) + + it('uses translated English progress and details without Show more or Show less controls', () => { + const b = bench() + render() + expect(screen.getByRole('heading').textContent).toBe(`${en.tasks}${makeTranslate(en)('progress.active', { count: 1 })}`) + fireEvent.click(row()) + expect(ownerValue()).toBe(SESSION) + expect(document.querySelector('[data-team-task-owner]')?.textContent).toBe(`${en.owner}: ${SESSION}`) + expect(screen.queryByText(TASK_1)).toBeNull() + expect(screen.queryByText('Show more')).toBeNull() + expect(screen.queryByText('Show less')).toBeNull() + }) + + it('shows the clipped owner tooltip after 500ms of hover', () => { + vi.useFakeTimers() + enableTooltips() + const ownerId = '8c0404a0-4c67-48ab-9513-50b4a755d6de' as SessionId + const b = bench({ + value: { ...team, tasks: [{ ...task, ownerId }] }, + }) + const view = render() + fireEvent.click(row()) + const owner = screen.getByText(ownerId) + expect(owner.parentElement?.hasAttribute('data-team-task-owner')).toBe(true) + const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(80) + vi.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(80) + fireEvent.pointerEnter(owner) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.queryByRole('tooltip')).toBeNull() + fireEvent.pointerLeave(owner) + scrollWidth.mockImplementation(function (this: Element) { return this === owner ? 240 : 80 }) + fireEvent.pointerEnter(owner) + act(() => { vi.advanceTimersByTime(499) }) + expect(screen.queryByRole('tooltip')).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + expect(screen.getByRole('tooltip').textContent).toBe(ownerId) + expect(view.container.contains(screen.getByRole('tooltip'))).toBe(false) + expect(document.querySelectorAll('[data-team-task-owner]')).toHaveLength(1) + fireEvent.click(row()) + expect(screen.queryByRole('tooltip')).toBeNull() + expect(ownerValue()).toBeNull() + }) + + it('delays clipped collapsed subject hover by 500ms while keeping keyboard focus immediate', () => { + vi.useFakeTimers() + enableTooltips() + const view = render() + const button = row() + const subject = screen.getByText(task.subject) + const scrollWidth = vi.spyOn(Element.prototype, 'scrollWidth', 'get').mockReturnValue(80) + vi.spyOn(Element.prototype, 'clientWidth', 'get').mockReturnValue(80) + fireEvent.pointerEnter(button) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.queryByRole('tooltip')).toBeNull() + fireEvent.pointerLeave(button) + scrollWidth.mockImplementation(function (this: Element) { return this === subject ? 180 : 80 }) + fireEvent.pointerEnter(button) + act(() => { vi.advanceTimersByTime(499) }) + expect(screen.queryByRole('tooltip')).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + expect(screen.getByRole('tooltip').textContent).toBe(task.subject) + expect(view.container.contains(screen.getByRole('tooltip'))).toBe(false) + fireEvent.click(button) + expect(row()).toBe(button) + expect(screen.queryByRole('tooltip')).toBeNull() + fireEvent.pointerLeave(button) + fireEvent.pointerEnter(button) + act(() => { vi.advanceTimersByTime(500) }) + expect(screen.queryByRole('tooltip')).toBeNull() + fireEvent.click(button) + fireEvent.pointerLeave(button) + fireEvent.keyDown(document.body, { key: 'Tab' }) + fireEvent.focus(button) + expect(screen.getByRole('tooltip').textContent).toBe(task.subject) + }) +}) diff --git a/packages/client/ui-agent-team/tests/team-command.client.spec.tsx b/packages/client/ui-agent-team/tests/team-command.client.spec.tsx new file mode 100644 index 0000000000..999b336108 --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-command.client.spec.tsx @@ -0,0 +1,98 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { cleanup, fireEvent, render } from '@testing-library/react' +import { CommandId } from '@deepseek-ai/dsh-commands/brand' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { IconUsersOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { TeamCommandRow, type TeamCommandRowProps } from '../src/client/TeamCommandRow.tsx' +import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts' + +afterEach(cleanup) + +type Node = TeamCommandRowProps['node'] +function command(args: string | null, outcome: Node['outcome']): Node { + return { kind: 'command', seq: 1, time: 1, commandId: CommandId('team-command'), name: 'team', args, outcome } +} + +describe.each([ + { id: 'zh', dictionary: zh }, { id: 'en', dictionary: en }, { id: 'ja', dictionary: ja }, { id: 'es', dictionary: es }, + { id: 'fr', dictionary: fr }, { id: 'de', dictionary: de }, { id: 'ru', dictionary: ru }, { id: 'pt', dictionary: pt }, +])('Team command fallback in $id', ({ dictionary }) => { + const t = makeTranslate(dictionary) + + it.each(['status', 'ON', '', null])('shows a localized pending status for unrecognized input %j', (args) => { + const view = render() + expect(view.getByText(dictionary['command.title'])).toBeTruthy() + expect(view.getByText(dictionary['command.running'])).toBeTruthy() + expect(view.container.querySelector('[data-team-command]')?.getAttribute('aria-busy')).toBe('true') + expect(view.container.querySelector('[data-team-command]')?.getAttribute('data-state')).toBe('running') + expect(view.queryByRole('button')).toBeNull() + }) + + it.each(['status', 'ON', '', null])('preserves successful output for unrecognized input %j', (args) => { + const text = 'Agent Teams enabled.' + const node = command(args, { kind: 'success', text }) + const original = JSON.stringify(node) + const view = render() + expect(view.getByText(dictionary['command.title'])).toBeTruthy() + expect(view.getByText(text)).toBeTruthy() + expect(view.queryByRole('button')).toBeNull() + expect(view.container.querySelector('[data-team-command]')?.getAttribute('data-state')).toBe('ok') + expect(JSON.stringify(node)).toBe(original) + }) + + it.each([undefined, ''])('uses a localized completed fallback for empty output %j', (text) => { + const outcome: Node['outcome'] = { kind: 'success', ...text === undefined ? {} : { text } } + const view = render() + expect(view.getByText(dictionary['command.title'])).toBeTruthy() + expect(view.getByText(dictionary['command.done'])).toBeTruthy() + }) + + it.each(['on', 'off', 'status', null])('keeps the raw failure expandable for input %j', (args) => { + const raw = ' Save failed\r\nThe original diagnostic remains available.\n' + const node = command(args, { kind: 'error', text: raw }) + const original = JSON.stringify(node) + const view = render() + expect(view.getByText(dictionary['command.title'])).toBeTruthy() + expect(view.getByText(t('command.failedReason', { reason: 'Save failed' }))).toBeTruthy() + expect(view.container.querySelector('[data-team-command]')?.getAttribute('data-state')).toBe('error') + const toggle = view.getByRole('button', { expanded: false }) + fireEvent.keyDown(toggle, { key: 'Enter' }) + expect(view.container.querySelector('pre')?.textContent).toBe(raw) + fireEvent.keyDown(toggle, { key: ' ' }) + expect(view.container.querySelector('pre')).toBeNull() + expect(JSON.stringify(node)).toBe(original) + }) + + it.each([undefined, '', '\n '])('uses a localized failure fallback for empty reason %j', (text) => { + const outcome: Node['outcome'] = { kind: 'error', ...text === undefined ? {} : { text } } + const view = render() + expect(view.getByText(dictionary['command.failed'])).toBeTruthy() + }) +}) + +it('uses the shared agent glyph for a failed command', () => { + const view = render() + const icon = render() + expect(view.container.querySelector('svg')?.outerHTML).toBe(icon.container.querySelector('svg')?.outerHTML) +}) + +it('keeps a long single-line failure expandable', () => { + const raw = 'The original failure detail '.repeat(20) + const view = render() + fireEvent.click(view.getByRole('button', { expanded: false })) + expect(view.container.querySelector('pre')?.textContent).toBe(raw) +}) + +it.each(['success', 'error'] as const)('relocalizes the title without rewriting expanded %s output', (kind) => { + const node = command('status', { kind, text: 'Recorded output\nAdditional recorded detail.' }) + const original = JSON.stringify(node) + const view = render() + expect(view.getByText(en['command.title'])).toBeTruthy() + fireEvent.click(view.getByRole('button', { expanded: false })) + expect(view.container.querySelector('pre')?.textContent).toBe(node.outcome?.text) + view.rerender() + expect(view.getByText(zh['command.title'])).toBeTruthy() + expect(view.container.querySelector('pre')?.textContent).toBe(node.outcome?.text) + expect(JSON.stringify(node)).toBe(original) +}) diff --git a/packages/client/ui-agent-team/tests/team-disable-confirmation-callbacks.client.spec.tsx b/packages/client/ui-agent-team/tests/team-disable-confirmation-callbacks.client.spec.tsx new file mode 100644 index 0000000000..92fa679c4c --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-disable-confirmation-callbacks.client.spec.tsx @@ -0,0 +1,43 @@ +// @vitest-environment jsdom + +import type { ComponentProps } from 'react' +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { Button } from '@deepseek-ai/dsh-client-ui-primitives' +import { TeamDisableConfirmation, type TeamDisableConfirmationProps } from '../src/client/TeamDisableConfirmation.tsx' +import { zh } from '../src/client/locales.ts' + +vi.mock('../src/client/TeamDisableConfirmation.module.css', () => ({ default: {} })) +vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + // Deliver repeated activations to the form even while its native button would suppress them. + Button: (props: ComponentProps) => , + } +}) + +afterEach(cleanup) + +it('keeps one disable operation pending despite repeated callbacks without optional stylesheet classes', async () => { + const pending = Promise.withResolvers() + onTestFinished(async () => { await act(async () => { pending.resolve(null) }) }) + const sessionId = SessionId('pending-disable-session') + const disableTeam = vi.fn(() => pending.promise) + const cancelDisable = vi.fn() + const useDisableRequest: TeamDisableConfirmationProps['useDisableRequest'] = select => select({ sessionId }) + const props = { useDisableRequest, disableTeam, cancelDisable, t: makeTranslate(zh) } as TeamDisableConfirmationProps + render() + const confirm = screen.getByRole('button', { name: zh['disable.confirm'] }) + fireEvent.click(confirm) + expect(confirm.getAttribute('aria-disabled')).toBe('true') + fireEvent.click(confirm) + fireEvent.click(screen.getByRole('button', { name: zh['disable.cancel'] })) + expect(disableTeam).toHaveBeenCalledExactlyOnceWith(sessionId) + expect(cancelDisable).not.toHaveBeenCalled() + expect(screen.getByRole('dialog', { name: zh['disable.title'] })).toBeTruthy() + await act(async () => { pending.resolve(null) }) + expect(cancelDisable).toHaveBeenCalledExactlyOnceWith(sessionId) +}) diff --git a/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx new file mode 100644 index 0000000000..58b3fa9004 --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-disable-confirmation.client.spec.tsx @@ -0,0 +1,172 @@ +// @vitest-environment jsdom + +import { afterEach, expect, it, onTestFinished, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { + TeamDisableConfirmation, type TeamDisableConfirmationProps, type TeamDisableRequest, +} from '../src/client/TeamDisableConfirmation.tsx' +import { zh } from '../src/client/locales.ts' + +afterEach(cleanup) + +const ORIGINAL = SessionId('original-session') +const REPLACEMENT = SessionId('replacement-session') + +function props( + request: TeamDisableRequest | null = { sessionId: ORIGINAL }, + disableTeam = vi.fn(async () => null), +) { + const useDisableRequest: TeamDisableConfirmationProps['useDisableRequest'] = select => select(request) + const cancelDisable = vi.fn() + return { + props: { useDisableRequest, cancelDisable, disableTeam, t: makeTranslate(zh) } as TeamDisableConfirmationProps, + cancelDisable, + disableTeam, + } +} + +function pendingDisable() { + const result = Promise.withResolvers() + onTestFinished(async () => { + await act(async () => { result.resolve(null) }) + }) + return result +} + +it('renders nothing when no disable request exists', () => { + const input = props(null) + const view = render() + expect(view.container.childElementCount).toBe(0) + expect(screen.queryByRole('dialog')).toBeNull() + expect(screen.queryByRole('button')).toBeNull() + expect(input.disableTeam).not.toHaveBeenCalled() + expect(input.cancelDisable).not.toHaveBeenCalled() +}) + +it('shows the localized title, two paragraphs, and actions without a checkbox', () => { + const input = props() + render() + const dialog = within(screen.getByRole('dialog', { name: '确认停用智能体团队协作?' })) + expect(dialog.getByRole('heading', { name: '确认停用智能体团队协作?' })).toBeTruthy() + expect(dialog.getByText(zh['disable.description'], { selector: 'p' })).toBeTruthy() + expect(dialog.getByText(zh['disable.warning'], { selector: 'p' })).toBeTruthy() + expect(dialog.getAllByRole('paragraph')).toHaveLength(2) + const cancel = dialog.getByRole('button', { name: zh['disable.cancel'] }) + expect(cancel.hasAttribute('disabled')).toBe(false) + expect(document.activeElement).toBe(cancel) + expect(dialog.getByRole('button', { name: zh['disable.confirm'] }).hasAttribute('disabled')).toBe(false) + expect(dialog.getByRole('button', { name: zh['disable.close'] })).toBeTruthy() + expect(dialog.queryByRole('checkbox')).toBeNull() + expect(dialog.queryByRole('alert')).toBeNull() + expect(input.disableTeam).not.toHaveBeenCalled() +}) + +it.each(['cancel', 'close', 'Escape'] as const)('dismisses through %s without disabling Team', (action) => { + const input = props() + const view = render() + if (action === 'Escape') fireEvent.keyDown(document, { key: 'Escape' }) + else fireEvent.click(screen.getByRole('button', { name: zh[`disable.${action}`] })) + expect(input.cancelDisable).toHaveBeenCalledExactlyOnceWith(ORIGINAL) + expect(input.disableTeam).not.toHaveBeenCalled() + view.rerender( select(null)} />) + expect(screen.queryByRole('dialog')).toBeNull() + fireEvent.keyDown(document, { key: 'Escape' }) + expect(input.cancelDisable).toHaveBeenCalledTimes(1) +}) + +it('disables the originating Session once and blocks cancellation until success', async () => { + const result = pendingDisable() + const input = props({ sessionId: ORIGINAL }, vi.fn(() => result.promise)) + const view = render() + const confirm = screen.getByRole('button', { name: zh['disable.confirm'] }) + fireEvent.click(confirm) + expect(input.disableTeam).toHaveBeenCalledExactlyOnceWith(ORIGINAL) + expect(confirm.hasAttribute('disabled')).toBe(true) + const cancel = screen.getByRole('button', { name: zh['disable.cancel'] }) + expect(cancel.hasAttribute('disabled')).toBe(true) + fireEvent.click(confirm) + fireEvent.click(cancel) + fireEvent.click(screen.getByRole('button', { name: zh['disable.close'] })) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(input.disableTeam).toHaveBeenCalledTimes(1) + expect(input.cancelDisable).not.toHaveBeenCalled() + expect(screen.getByRole('dialog')).toBeTruthy() + await act(async () => { result.resolve(null) }) + expect(input.cancelDisable).toHaveBeenCalledExactlyOnceWith(ORIGINAL) + view.rerender( select(null)} />) + expect(screen.queryByRole('dialog')).toBeNull() +}) + +it.each(['returned', 'error', 'string'] as const)('keeps a %s failure visible and allows retry', async (failure) => { + const result = pendingDisable() + const disableTeam = vi.fn() + .mockImplementationOnce(async () => { + if (failure === 'error') throw new Error('offline') + if (failure === 'string') throw 'offline' + return 'offline' + }) + .mockImplementationOnce(() => result.promise) + const input = props({ sessionId: ORIGINAL }, disableTeam) + const view = render() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['disable.confirm'] })) }) + expect(screen.getByRole('alert').textContent).toBe(input.props.t('mode.failed', { message: 'offline' })) + expect(input.cancelDisable).not.toHaveBeenCalled() + expect(screen.getByRole('button', { name: zh['disable.cancel'] }).hasAttribute('disabled')).toBe(false) + expect(screen.getByRole('button', { name: zh['disable.confirm'] }).hasAttribute('disabled')).toBe(false) + view.rerender( select({ sessionId: ORIGINAL })} />) + expect(screen.getByRole('alert').textContent).toContain('offline') + fireEvent.click(screen.getByRole('button', { name: zh['disable.confirm'] })) + expect(disableTeam.mock.calls).toEqual([[ORIGINAL], [ORIGINAL]]) + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.getByRole('button', { name: zh['disable.confirm'] }).hasAttribute('disabled')).toBe(true) + await act(async () => { result.resolve(null) }) + expect(input.cancelDisable).toHaveBeenCalledExactlyOnceWith(ORIGINAL) +}) + +it('clears the previous failure when the request targets a different Session', async () => { + const input = props({ sessionId: ORIGINAL }, vi.fn() + .mockResolvedValueOnce('old failure').mockResolvedValueOnce(null)) + const view = render() + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['disable.confirm'] })) }) + expect(screen.getByRole('alert').textContent).toContain('old failure') + view.rerender( select({ sessionId: REPLACEMENT })} />) + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.getByRole('button', { name: zh['disable.confirm'] }).hasAttribute('disabled')).toBe(false) + await act(async () => { fireEvent.click(screen.getByRole('button', { name: zh['disable.confirm'] })) }) + expect(input.disableTeam.mock.calls).toEqual([[ORIGINAL], [REPLACEMENT]]) + expect(input.cancelDisable).toHaveBeenCalledExactlyOnceWith(REPLACEMENT) +}) + +it.each(['success', 'returned', 'error'] as const)('isolates a replacement request from the old pending %s', async (outcome) => { + const original = pendingDisable() + const replacement = pendingDisable() + const input = props({ sessionId: ORIGINAL }, vi.fn() + .mockImplementationOnce(() => original.promise).mockImplementationOnce(() => replacement.promise)) + const view = render() + fireEvent.click(screen.getByRole('button', { name: zh['disable.confirm'] })) + expect(screen.getByRole('button', { name: zh['disable.confirm'] }).hasAttribute('disabled')).toBe(true) + view.rerender( select({ sessionId: REPLACEMENT })} />) + const confirm = screen.getByRole('button', { name: zh['disable.confirm'] }) + expect(confirm.hasAttribute('disabled')).toBe(false) + expect(screen.getByRole('button', { name: zh['disable.cancel'] }).hasAttribute('disabled')).toBe(false) + expect(screen.queryByRole('alert')).toBeNull() + fireEvent.click(confirm) + expect(input.disableTeam.mock.calls).toEqual([[ORIGINAL], [REPLACEMENT]]) + await act(async () => { + if (outcome === 'error') original.reject(new Error('old failure')) + else original.resolve(outcome === 'success' ? null : 'old failure') + }) + expect(screen.getByRole('dialog', { name: zh['disable.title'] })).toBeTruthy() + expect(screen.queryByRole('alert')).toBeNull() + expect(confirm.hasAttribute('disabled')).toBe(true) + if (outcome === 'success') expect(input.cancelDisable).toHaveBeenCalledExactlyOnceWith(ORIGINAL) + else expect(input.cancelDisable).not.toHaveBeenCalled() + fireEvent.click(confirm) + fireEvent.keyDown(document, { key: 'Escape' }) + expect(input.disableTeam).toHaveBeenCalledTimes(2) + expect(input.cancelDisable).not.toHaveBeenCalledWith(REPLACEMENT) + await act(async () => { replacement.resolve(null) }) + expect(input.cancelDisable.mock.calls).toEqual(outcome === 'success' ? [[ORIGINAL], [REPLACEMENT]] : [[REPLACEMENT]]) +}) diff --git a/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx new file mode 100644 index 0000000000..13a1da8450 --- /dev/null +++ b/packages/client/ui-agent-team/tests/team-mode.client.spec.tsx @@ -0,0 +1,131 @@ +// @vitest-environment jsdom + +import { afterEach, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, render, screen } from '@testing-library/react' +import { SessionId } from '@deepseek-ai/dsh-session' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { TeamModeToggle, type TeamModeToggleProps } from '../src/client/TeamModeToggle.tsx' +import { de, en, es, fr, ja, pt, ru, zh } from '../src/client/locales.ts' + +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +function props(enabled: boolean | undefined, selectTeamMode = vi.fn(async () => null as string | null), child?: 'addressed' | 'listed', requestedModel: boolean | 'loading' = false): TeamModeToggleProps { + return { + sessionId: SessionId('root'), + useSession: (select: (value: { subagent: object | null }) => unknown) => select({ subagent: child === 'addressed' ? {} : null }), + useSessions: (select: (value: { byId: object }) => unknown) => select({ byId: child === 'listed' ? { root: { origin: 'subagent' } } : {} }), + useProjection: (key: string) => key === 'modelSelection' + ? requestedModel === 'loading' ? undefined : { lastUsed: requestedModel ? { provider: 'mock', model: 'mock' } : null, next: { provider: 'mock', model: 'mock' } } + : enabled === undefined ? undefined : { enabled, tasks: [] }, + locked: false, dismiss: vi.fn(), reportFailure: vi.fn(), selectTeamMode, requestDisableConfirmation: vi.fn(), + t: makeTranslate(zh), + } as TeamModeToggleProps +} + +it('renders only available mode and waits for persisted state before displaying a new selection', async () => { + let finish!: (result: string | null) => void + const select = vi.fn(() => new Promise((resolve) => { finish = resolve })) + const view = render() + expect(screen.queryByRole('switch')).toBeNull() + view.rerender() + const toggle = screen.getByRole('switch', { name: '启用智能体团队协作' }) + fireEvent.click(toggle) + expect(select).toHaveBeenCalledWith(true) + expect(toggle.getAttribute('aria-checked')).toBe('false') + expect(toggle.hasAttribute('disabled')).toBe(true) + await act(async () => { finish(null) }) + view.rerender() + expect(toggle.getAttribute('aria-checked')).toBe('true') +}) + +it.each(['returned', 'error', 'string'])('reports rejected mode writes through the menu host (%s)', async (failure) => { + const p = props(false, vi.fn(async () => { + if (failure === 'error') throw new Error('offline') + if (failure === 'string') throw 'offline' + return 'offline' + })) + render() + await act(async () => { fireEvent.click(screen.getByRole('switch')) }) + expect(p.reportFailure).toHaveBeenCalledWith(expect.stringContaining('offline')) + expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') +}) + +it.each(Object.entries({ zh, en, ja, es, fr, de, ru, pt }).flatMap(([locale, dictionary]) => + [false, true].map(locked => ({ locale, dictionary, locked })), +))('opens the $locale explanation without changing Team mode (locked: $locked)', ({ dictionary, locked }) => { + vi.stubGlobal('ResizeObserver', class { + observe() {} + unobserve() {} + disconnect() {} + }) + const input = props(false) + render() + const info = screen.getByRole('button', { name: dictionary['mode.infoLabel'] }) + expect(info.hasAttribute('disabled')).toBe(false) + fireEvent.click(info) + const tooltip = screen.getByRole('tooltip', { hidden: true }) + expect(tooltip.textContent).toBe(dictionary['mode.description']) + expect(info.getAttribute('aria-describedby')).toBe(tooltip.id) + expect(document.body.contains(tooltip)).toBe(true) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false') + fireEvent.keyDown(info, { key: 'Escape' }) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + fireEvent.click(info) + fireEvent.pointerDown(document.body) + expect(screen.queryByRole('tooltip', { hidden: true })).toBeNull() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) + +it('requests confirmation before disabling after a recorded model request', () => { + const input = props(true, undefined, undefined, true) + render() + fireEvent.click(screen.getByRole('switch')) + expect(input.dismiss).toHaveBeenCalledOnce() + expect(input.dismiss).toHaveBeenCalledBefore(vi.mocked(input.requestDisableConfirmation)) + expect(input.requestDisableConfirmation).toHaveBeenCalledOnce() + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true') +}) + +it.each([false, true])('enables directly regardless of model history (requested: %s)', async (requested) => { + const input = props(false, undefined, undefined, requested) + render() + await act(async () => { fireEvent.click(screen.getByRole('switch')) }) + expect(input.selectTeamMode).toHaveBeenCalledWith(true) + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() +}) + +it('disables directly when a model is selected but no request has been recorded', async () => { + const input = props(true) + render() + await act(async () => { fireEvent.click(screen.getByRole('switch')) }) + expect(input.selectTeamMode).toHaveBeenCalledWith(false) + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() +}) + +it('waits for model history before allowing the switch to change', () => { + const input = props(true, undefined, undefined, 'loading') + render() + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) + fireEvent.click(screen.getByRole('switch')) + expect(input.selectTeamMode).not.toHaveBeenCalled() + expect(input.requestDisableConfirmation).not.toHaveBeenCalled() +}) + +it('disables selection while the Session is locked', () => { + render() + expect(screen.getByRole('switch').hasAttribute('disabled')).toBe(true) +}) + +it.each(['addressed', 'listed'] as const)('hides the switch on a child Session (%s)', (source) => { + const input = props(false, undefined, source) + const useProjection = vi.fn((): never => { throw new Error('Child must not read Team mode') }) + render() + expect(screen.queryByRole('switch')).toBeNull() + expect(useProjection).not.toHaveBeenCalled() + expect(input.selectTeamMode).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-agent-team/tsconfig.json b/packages/client/ui-agent-team/tsconfig.json new file mode 100644 index 0000000000..429b9adac3 --- /dev/null +++ b/packages/client/ui-agent-team/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": ["src"], + "references": [ + { "path": "../../../vendor/cordis" }, + { "path": "../../team/agent-team" }, + { "path": "../../api/session-controller/tsconfig.client.json" }, + { "path": "../../api/remotes/tsconfig.client.json" }, + { "path": "../ui-model-selection" }, + { "path": "../ui-layout" }, + { "path": "../../core/agent" }, + { "path": "../ui-subagent" }, + { "path": "../locale/tsconfig.client.json" }, + { "path": "../store" }, + { "path": "../ui-conversation/tsconfig.client.json" }, + { "path": "../ui-chat/tsconfig.client.json" }, + { "path": "../../util/values" }, + { "path": "../ui-primitives" }, + { "path": "../ui-renderer" }, + { "path": "../ui-slots" }, + { "path": "../../core/session" } + ] +} diff --git a/packages/experimental/client-ui-agent-team/tsdown.config.ts b/packages/client/ui-agent-team/tsdown.config.ts similarity index 54% rename from packages/experimental/client-ui-agent-team/tsdown.config.ts rename to packages/client/ui-agent-team/tsdown.config.ts index 71d5bd77f8..7aa03cebc1 100644 --- a/packages/experimental/client-ui-agent-team/tsdown.config.ts +++ b/packages/client/ui-agent-team/tsdown.config.ts @@ -1,3 +1,3 @@ -import { clientBundle } from '../../client/tsdown.client.ts' +import { clientBundle } from '../tsdown.client.ts' export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 5b652c5425..54168bf257 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -18,11 +18,11 @@ en: 9386791a9e5efa00 zh: 7cb9f3bbc42319d6 /deepseek-ai-dsh-client-ui-chat/hidden-chat-rows: - en: b0c4e6711d69d2f8 - zh: 09add0ea1a243922 + en: 91b7c7a5263eda35 + zh: 16d39b45edee038f /deepseek-ai-dsh-client-ui-chat/command-and-failure-rows: - en: be90c24392fb021b - zh: 992b8745b385f9ab + en: c5b23d0ed29a0425 + zh: 689bab2c8253294a /deepseek-ai-dsh-client-ui-chat/turn-token-usage: en: cfdfe3d99d3f4e09 zh: 9330bad3d3f7a689 @@ -33,8 +33,8 @@ en: b0d806604bc17006 zh: 18dabe5dc2d0d419 /deepseek-ai-dsh-client-ui-chat/grouped-rendering: - en: 3afad0b4c6bf9ce0 - zh: d8179ba4ee9fcd61 + en: b1630d93a52f483e + zh: 59cb81ca50ecffc4 /deepseek-ai-dsh-client-ui-chat/scroll-ownership: en: dd4e69828096c3a0 zh: 2a9bc370f44efcd7 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 56b30d271b..b23b9dc3e1 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -54,7 +54,7 @@ Settings → General → Open chat links in selects the destination for ordinary ## Hidden Chat rows -Chat omits system-prompt, ordinary Context injection, and `permission` command rows in every work-details mode. Context containing tool additions or removals remains visible. The filter changes neither recorded Session events nor Trajectory inspection. Non-human Turn triggers remain independent, bordered notices with a contrasting neutral background; other command rows remain in Chat. +Chat omits system-prompt, ordinary Context injection, and `permission` command rows in every work-details mode. It also hides pending and successful `/team on` and `/team off` receipts, identified by their recorded name and trimmed arguments; failures and commands with missing or unrecognized arguments remain visible. Context containing tool additions or removals remains visible. The filter changes neither recorded Session events nor Trajectory inspection and excludes hidden receipts from flow spacing and process summaries. Non-human Turn triggers remain independent, bordered notices with a contrasting neutral background; other command rows remain in Chat. When an Assistant attempt retires without a visible message, Chat hides its already-published Node instead of removing its key. A retry in the same Step reuses that key when visible content returns. This also applies when the loaded window lacks the Step start. @@ -63,6 +63,8 @@ Text and reasoning contribute to Assistant visibility only when they contain a n ## Command and failure rows +Subagent result notices use the Users icon and show only the localized execution outcome in their heading, without a task description or child ID. Completed means that execution ended normally, not that its output passed validation. Historical notices without a readable outcome retain the generic title; unfamiliar outcomes display “Subagent run ended unexpectedly”. Expanded notices preserve their original model-facing body. + Generic command rows retain the ordinary command glyph in every lifecycle state; failure remains explicit through the row state and summary. Every terminal Turn failure renders its inline red-dot row; a quota failure's row states the neutral `message.failure.quota` copy instead of the provider message. The transient notice for a newly appended `QUOTA` or `ACCOUNT_QUOTA` comes from this package's frame-wide entry in `shell.overlay`, which outlives the Chat panel: it offers the one live notice to the `shell.quota-notice` chain and falls back to its own warning Toast, while an entry that claims the code replaces that fallback. Only Sessions this Client has bound and materialized publish; quota failures in Sessions it never opened do not. A newer notice replaces the current one unless a claiming entry retains it with `keepOpen()`: that call returns a release the caller owns and must run on unmount, any live hold keeps the claiming entry mounted and drops later notices, and releasing resumes later notices without replaying the dropped ones. The fallback Toast has no deferral of its own: while the Desktop account's opaque native Platform page covers the document, it still runs underneath and its display timer may elapse unseen, dismissing the notice itself, so only the persistent failure row remains. A release drops only its own hold, so one that runs after a dismissal or a newer hold leaves that newer hold intact. Dismissal and sign-out clear every hold, and dropped notices are not queued while their persistent failure rows still render. History replacement and pagination never publish a notice. Intermediate retries do not create a terminal row; output-token limits use the amber warning dot. A Turn that restart recovery closed as `interrupted` renders a localized stopped row stating that the DSH process exited mid-Turn, without a code chip, and its process summary reads Stopped. Chat adapts Markdown targets at `MarkdownDelegateProvider.getTriggerProps`. The assistant-node Slot obtains `useContextMenu` directly and passes a file-path adapter to the optional mention service; intermediate flow and node owners carry no menu callbacks. Paths resolve against the originating Session’s current working directory when the gesture begins. Menus retain that captured path and line even if focus changes. Undeclared plugin links keep native behavior. @@ -127,7 +129,7 @@ Scroll-edge fades initialize when `ResizeObserver` reports the open group's layo Each group owns local `useDisclosure` state that survives mode changes while its component stays mounted. -The session-scoped `conversation.chat.reasoning.body` single Slot offers the original reasoning text and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the original text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. The [reasoning display rules](src/client/conversation-nodes/README.md#display-modes) define which blocks produce rows. +The session-scoped `conversation.chat.reasoning.body` single Slot offers the original `rawText`, display-ready `text`, and streaming state only when its body is expanded. Its official entry registers at priority 100 and calls the `conversation.chat.reasoning.content` Factory. A replacement uses a lower priority number and may call that same Factory with original or derived text. The root-scoped Factory requires no Session and fixes compact typography. Its optional `labels` accepts complete `MarkdownLabels` unchanged; omission uses Chat's localized defaults. The host supplies no inline fallback or plugin action state. Display extensions must preserve access to the untranslated text and own their controls inside their Body wrapper. Extensions do not replace the reasoning preview or its disclosure policy. The [reasoning display rules](src/client/conversation-nodes/README.md#display-modes) define which blocks produce rows. The Chat-node slot injects a reset-bound `useDisclosure` Hook for reasoning and tools. Intermediate renderers forward it without subscribing; each invocation owns independent open state. Source callbacks retain their receiver and stable identity. When an enclosing Turn actually hides a process member, its seat resets those disclosures without replacing component keys or changing the Hook reference. Display-mode changes preserve their open state. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 1cc14f917a..e5f8add05b 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -54,7 +54,7 @@ Session 作用域的 `conversation.chat.user.content` Factory 只渲染用户内 ## Chat 隐藏的行 -Chat 在所有工作步骤展示模式下都不显示系统提示词行、普通上下文注入和 `permission` 命令行。包含工具添加或移除记录的上下文仍然可见。该过滤不改变已记录的 Session 事件或 Trajectory 查看能力。非人工轮次触发仍作为独立通知显示,其他命令行仍保留在 Chat 中。 +Chat 在所有工作步骤展示模式下都不显示系统提示词行、普通上下文注入和 `permission` 命令行。记录中的命令名和去除首尾空白后的参数确定为 `/team on` 或 `/team off` 时,也隐藏执行中与成功回执;失败以及参数缺失或无法识别的命令仍然可见。包含工具添加或移除记录的上下文仍然可见。该过滤不改变已记录的 Session 事件或 Trajectory 查看能力,隐藏回执也不计入行间距和过程摘要。非人工轮次触发仍作为独立通知显示,其他命令行仍保留在 Chat 中。 Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node,不移除其 key。同一 Step 的重试再次产生可见内容时,复用该 key。已加载窗口缺少 Step 起点时也遵循此规则。 @@ -63,6 +63,8 @@ Assistant 尝试结束且没有可见消息时,Chat 隐藏已发布的 Node, ## 指令与失败行 +子智能体结果通知使用 Users 图标,标题仅显示本地化的执行状态,不附加任务描述或子智能体 ID。完成表示执行正常结束,不表示输出已通过验证。历史通知没有可读取的结束状态时保留通用标题;未知状态显示“子智能体异常结束”。展开后的通知保留原始模型可见正文。 + 通用指令行在所有生命周期状态中都保留普通指令图标;失败仍通过行状态与摘要表达。每个终止轮次都渲染自己的红点行;欠费失败的行使用中立的 `message.failure.quota` 文案,而不是提供方消息。新追加的 `QUOTA` 或 `ACCOUNT_QUOTA` 产生的瞬时提示来自本包注册在 `shell.overlay` 的全局条目,它不随 Chat 面板消失:该条目把唯一一条实时提示交给 `shell.quota-notice` 链,并在无人接管时回退到自己的警告 Toast,接管该错误码的条目会替换该回退。只有本 Client 已绑定并已物化的 Session 会发布提示;它从未打开的 Session 中的欠费不会发布。更新的提示会替换当前提示,除非认领条目用 `keepOpen()` 保持住当前提示:该调用返回一个由调用方持有、必须在卸载时调用的释放函数,只要存在保持,认领条目就继续挂载,后续提示被丢弃,释放后恢复后续提示但不重放已丢弃的提示。回退 Toast 自身没有延后策略:当 Desktop 账号的不透明原生 Platform 页盖住本页时,它仍会在下方运行,其显示计时器可能在不可见时走完并自行撤下提示,因此只留下持久化失败行。释放只移除自己的保持,因此它在关闭或更新的保持之后执行时不会影响更新的保持。关闭与退出登录会清空所有保持;被丢弃的提示不排队,其对应的持久化失败行仍会渲染。历史替换和分页不会发布提示。中间重试不会创建终止行;输出 token 上限使用琥珀色警告点。重启恢复以 `interrupted` 结束的轮次会渲染本地化的停止行,说明 DSH 进程在轮次中途退出,不显示代码标签,其过程摘要显示“已停止”。 Chat 在 `MarkdownDelegateProvider.getTriggerProps` 接入处适配 Markdown 目标。助手节点 Slot 直接获取 `useContextMenu`,向可选的文件引用服务传入路径适配函数;消息流和节点中间层不再携带菜单回调。手势发生时按原始 Session 的当前工作目录解析路径,菜单保留捕获的路径和行号,不受焦点变化影响。未声明的插件链接保留原生行为。 @@ -127,7 +129,7 @@ Chat Builder 按节点发布 `bottomSource`:节点可见且属于已加载的 每个组拥有本地 `useDisclosure` 状态,组件保持挂载时,模式切换保留该状态。 -Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始思考文本和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看原文的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。哪些块生成思考行由[思考展示规则](src/client/conversation-nodes/README.zh.md#display-modes)定义。 +Session 作用域的 `conversation.chat.reasoning.body` single Slot 仅在思考正文展开时提供原始文本 `rawText`、显示文本 `text` 和流式状态。官方条目以优先级 100 注册,并调用 `conversation.chat.reasoning.content` Factory。替换项使用更小的优先级数值,可向同一个 Factory 传入原文或派生显示文本。root 作用域的 Factory 不要求 Session,并固定使用紧凑排版。其可选 `labels` 原样接受完整的 `MarkdownLabels`,省略时使用 Chat 的默认本地化文案。宿主不提供内联 fallback 或插件操作状态。显示扩展必须保留查看未翻译文本的能力,并在自己的 Body 包装内维护控件。扩展不替换思考预览或展开策略。哪些块生成思考行由[思考展示规则](src/client/conversation-nodes/README.zh.md#display-modes)定义。 Chat 节点 slot 为推理与工具注入绑定重置来源的 `useDisclosure` 钩子。中间 renderer 只透传、不订阅,每次调用拥有独立展开状态。来源回调保留接收对象及稳定引用。外层轮次实际隐藏过程成员时,所在节点重置这些开合状态,不替换组件 key,也不改变钩子引用。展示模式切换保留展开状态。 diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 5f640dbbad..9929770b35 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -344,10 +344,10 @@ right: 0; bottom: 16px; left: 0; - /* Above the sticky composer (z-index 7) so the control stays clickable and - visible over the input card. Exception: while an @/slash menu is open the - seat lifts to 9 (ui-conversation ConversationRoot) so the menu is never - covered by this control. */ + /* Above transcript sticky chrome (CodeBlock banners 6, the pinned compaction + header and turn rail 7) and below the composer seat (9, ui-conversation + ConversationRoot), so menus the composer opens upward cover this control. + At rest the control sits 16px above the input card. */ z-index: 8; height: 0; display: flex; diff --git a/packages/client/ui-chat/src/client/chat/ReasoningContent.tsx b/packages/client/ui-chat/src/client/chat/ReasoningContent.tsx index 2289bf3404..da220164ea 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningContent.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningContent.tsx @@ -18,7 +18,7 @@ export const ReasoningContent = memo(function ReasoningContent({ text, running, /** * Render the default Body through the same Factory available to third-party wrappers. - * @param props - original reasoning and the framework's Factory renderer. + * @param props - display-ready reasoning and the framework's Factory renderer. * @returns an occurrence of the official reasoning Content Factory. */ export function DefaultReasoningBody({ text, running, renderFactorySlot }: ReasoningBodyProps) { diff --git a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx index 347ce6bee4..a91ef3a198 100644 --- a/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx +++ b/packages/client/ui-chat/src/client/chat/ReasoningRow.tsx @@ -3,6 +3,7 @@ import { memo, useMemo } from 'react' import { DisclosureRow, IconThinkOutlineRegular, TextShimmer } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { ChatViewSlotProps, UseDisclosure, UsePresentation } from '../contract/slots.ts' +import { reasoningText } from '../reasoning-text.ts' import a11yCss from './accessibility.module.css' import css from './ReasoningRow.module.css' @@ -36,7 +37,7 @@ function latestCompletedParagraphFirstLine(text: string): string { * collapsed summary omits double-asterisk markers; expanded content renders * the complete Markdown with secondary typography. A streaming preview advances * when a paragraph's first line completes. Mode changes toggle CSS display without unmounting - * collapsed summaries. + * collapsed summaries. The Body Slot receives both original and display-ready text. * @param props.text - complete or streaming reasoning text. * @param props.running - whether this block is the streaming tail. * @param props.usePresentation - live display-policy selector for this reasoning row. @@ -46,7 +47,7 @@ function latestCompletedParagraphFirstLine(text: string): string { * @returns the reasoning disclosure. */ export const ReasoningRow = memo(function ReasoningRow({ - text, running, textInteractionSource = false, usePresentation, useDisclosure, renderSlot, t, + text: rawText, running, textInteractionSource = false, usePresentation, useDisclosure, renderSlot, t, }: { text: string running: boolean @@ -56,6 +57,10 @@ export const ReasoningRow = memo(function ReasoningRow({ t: ChatViewSlotProps['t'] } & Pick, 'renderSlot'>) { const { expanded, toggle } = useDisclosure() + const { text, hidden } = useMemo(() => { + const text = reasoningText(rawText) + return { text, hidden: text !== rawText && text.trim() === '' } + }, [rawText]) const summaryText = running ? latestCompletedParagraphFirstLine(text) : firstLine(text) const summary = useMemo(() => summaryText.replaceAll('**', ''), [summaryText]) const preview = usePresentation(policy => !expanded && summary !== '' @@ -72,9 +77,11 @@ export const ReasoningRow = memo(function ReasoningRow({ ), [running, summary]) const content = useMemo(() => expanded ? (
    - {renderSlot('conversation.chat.reasoning.body', { text, running })} + {renderSlot('conversation.chat.reasoning.body', { rawText, text, running })}
    - ) : undefined, [expanded, renderSlot, running, text, textInteractionSource]) + ) : undefined, [expanded, renderSlot, running, rawText, text, textInteractionSource]) + + if (hidden) return null return (
    > = { goal: IconGoalOutlineRegular, agent: IconPaperPlaneOutlineRegular, team: IconAgentPresetOutlineRegular, - subagent: IconAgentPresetOutlineRegular, + subagent: IconUsersOutlineRegular, github: IconBranchOutlineRegular, webhook: IconGlobeOutlineRegular, schedule: IconClockOutlineRegular, diff --git a/packages/client/ui-chat/src/client/chat/stat-dialog.module.css b/packages/client/ui-chat/src/client/chat/stat-dialog.module.css index 4c5de52c51..769718d513 100644 --- a/packages/client/ui-chat/src/client/chat/stat-dialog.module.css +++ b/packages/client/ui-chat/src/client/chat/stat-dialog.module.css @@ -15,8 +15,8 @@ Both bounds yield to a viewport narrower than themselves (12px margins), so a fixed floor cannot push the panel past the placement clamp. */ width: max-content; - min-width: min(300px, calc(100vw - 24px)); - max-width: min(440px, calc(100vw - 24px)); + min-width: min(300px, calc(100vw - 24px), var(--dsh-anchored-max-width, 100vw)); + max-width: min(440px, calc(100vw - 24px), var(--dsh-anchored-max-width, 100vw)); padding: 16px; border: 0; border-radius: var(--dsw-radius-lg); @@ -28,6 +28,11 @@ line-height: 18px; color: var(--dsw-alias-label-secondary); cursor: default; + max-height: var(--dsh-anchored-max-height, none); + overflow-x: hidden; + overflow-y: auto; + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } /* Dialog heading row: the section name left, the section's headline value diff --git a/packages/client/ui-chat/src/client/chat/turn-trigger.ts b/packages/client/ui-chat/src/client/chat/turn-trigger.ts index d4912668ea..ade8093490 100644 --- a/packages/client/ui-chat/src/client/chat/turn-trigger.ts +++ b/packages/client/ui-chat/src/client/chat/turn-trigger.ts @@ -13,6 +13,20 @@ function field(source: Record, key: string): string { return typeof source[key] === 'string' ? source[key] : '' } +/** Missing or malformed historical reasons stay generic; unfamiliar reasons never imply success. */ +function subagentTitle(reason: unknown): ChatKey { + if (typeof reason !== 'string' || reason === '') return 'message.trigger.subagent' + switch (reason) { + case 'completed': return 'message.trigger.subagent.completed' + case 'aborted': return 'message.trigger.subagent.aborted' + case 'error': return 'message.trigger.subagent.error' + case 'max-tokens': return 'message.trigger.subagent.maxTokens' + case 'refusal': return 'message.trigger.subagent.refusal' + // Backends may extend the recorded reason vocabulary. + default: return 'message.trigger.subagent.unknown' + } +} + /** * Describe a waking message using its recorded source. * @param node - durable context, including the original notification body. @@ -40,11 +54,10 @@ export function turnTriggerDetails(node: ContextMessageNode): { title = 'message.trigger.team' icon = 'team' break - case 'subagent-settled': { - title = 'message.trigger.subagent' + case 'subagent-settled': + title = subagentTitle(source.stopReason) icon = 'subagent' break - } case 'webhook': { const github = field(source, 'provider') === 'github' title = github ? 'message.trigger.github' : 'message.trigger.webhook' diff --git a/packages/client/ui-chat/src/client/contract/chat-visibility.ts b/packages/client/ui-chat/src/client/contract/chat-visibility.ts index 2fd60b4b1d..8f1c6f89b5 100644 --- a/packages/client/ui-chat/src/client/contract/chat-visibility.ts +++ b/packages/client/ui-chat/src/client/contract/chat-visibility.ts @@ -2,15 +2,21 @@ import type { ChatNode } from './chat-nodes.ts' /** - * Exclude system prompts, ordinary Context, and permission commands from visible Chat rows. - * Context containing tool changes retains its notice row. + * Exclude system prompts, ordinary Context, permission commands, and normal Team toggle receipts. + * Failed Team toggles and Context containing tool changes remain visible. * @param node - projected Chat node. * @returns whether the node contributes a visible Chat row. */ export function isVisibleChatNode(node: ChatNode): boolean { + if (node.kind === 'command') { + if (node.data.name === 'permission') return false + if (node.data.name === 'team' && node.data.outcome?.kind !== 'error') { + const selection = node.data.args?.trim() + if (selection === 'on' || selection === 'off') return false + } + } return node.visibility === 'visible' && node.kind !== 'system-prompt' && (node.kind !== 'context' || node.data.content.some(block => block.type === 'tool-addition' || block.type === 'tool-removal')) - && !(node.kind === 'command' && node.data.name === 'permission') } diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index 9479bde696..a879601747 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -79,16 +79,22 @@ export interface QuotaNoticeState { seq: number } -/** Original model-provided reasoning offered to the expanded Body Slot. */ +/** Original and display-ready reasoning offered to the expanded Body Slot. */ export interface ReasoningBodyOwnerProps { - /** Complete or streaming reasoning text. */ + /** Complete or streaming model output. */ + readonly rawText: string + /** Reasoning text prepared for display. */ readonly text: string /** Whether the reasoning tail is still streaming. */ readonly running: boolean } /** Session-independent original or derived display input to the Content Factory. */ -export interface ReasoningContentInput extends ReasoningBodyOwnerProps { +export interface ReasoningContentInput { + /** Caller-selected Markdown. */ + readonly text: string + /** Whether the supplied text is still streaming. */ + readonly running: boolean /** Localized Markdown controls, used unchanged when supplied; omission uses Chat's defaults. */ readonly labels?: MarkdownLabels } @@ -468,9 +474,9 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { */ 'conversation.chat.commandview': { kind: 'keyed'; scope: 'session'; owner: CommandRowOwnerProps } /** - * Expanded reasoning body with the unchanged model text. The official entry + * Expanded reasoning body with raw and display-ready text. The official entry * has priority 100 and calls the reasoning Content Factory; smaller priority - * values replace it. Contributions must preserve access to the original text. + * values replace it. Contributions must preserve access to untranslated display text. */ 'conversation.chat.reasoning.body': { kind: 'single'; scope: 'session'; owner: ReasoningBodyOwnerProps } /** diff --git a/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts b/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts index 3b82dc2ecb..785ea85f54 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/process-activity.ts @@ -1,4 +1,5 @@ /** Tool-category and live-detail interpretation owned by Chat grouping. */ +import { reasoningText } from '../reasoning-text.ts' import type { ToolArgs } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { ProcessActivity, ProcessActivitySummary } from '../contract/process-groups.ts' import type { ChatNode } from '../contract/chat-nodes.ts' @@ -99,7 +100,7 @@ function liveReasoningDetail(nodes: readonly ChatNode[]): string { for (let blockIndex = node.data.blocks.length - 1; blockIndex >= 0; blockIndex--) { const block = node.data.blocks[blockIndex] if (block?.kind !== 'reasoning') continue - const paragraphs = block.text.split(/\r?\n[\t ]*\r?\n/) + const paragraphs = reasoningText(block.text).split(/\r?\n[\t ]*\r?\n/) for (let paragraphIndex = paragraphs.length - 1; paragraphIndex >= 0; paragraphIndex--) { const detail = normalizeLiveToolDetail(paragraphs[paragraphIndex]?.replaceAll('**', '')) if (detail !== '') return detail diff --git a/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts b/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts index fbaf31f882..ddb05d9ce5 100644 --- a/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts +++ b/packages/client/ui-chat/src/client/conversation-nodes/request-prompt.ts @@ -56,6 +56,8 @@ function stableRequestPromptAnchor( * their step's input; in-history updates stay at their own positions. The * request-prompt Definition owns replacement and later-series cards. Positional * replacements advance the effective prompt without changing historical cards. + * A published node becomes `hidden` under the same key while a prepended replacement + * leaves its prompt order unknown, and `visible` again once older history resolves it. * @param inspect - Pure surface interpretation supplied by uiConversation. * @returns The Chat system-prompt Definition. */ @@ -75,7 +77,11 @@ export function systemMessageDefinition(inspect: SystemPromptInspector): Convers buildViewNode: (context) => { const state = context.state?.introduced if (state === undefined || state.text === '' - || context.start?.event.type !== 'system/message' || context.start.event.surfaceOp !== 'append') return null + || context.start?.event.type !== 'system/message' || context.start.event.surfaceOp !== 'append') { + const current = context.current.get('chat') as ChatNode | null | undefined + if (current?.kind !== 'system-prompt') return null + return chatNode(context, 'system-prompt', current.anchorSeq, current.data, { visibility: 'hidden' }) + } const anchor = state.update ? state.seq : requestPromptAnchor(context.start, undefined, true) return chatNode(context, 'system-prompt', anchor, { text: state.text, ...state.update ? { update: true } : {} }) }, diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 6f0e6eda52..221ab256e8 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -55,6 +55,12 @@ export const zh = { 'message.trigger.agent': '收到任务消息', 'message.trigger.team': '收到团队消息', 'message.trigger.subagent': '子任务状态更新', + 'message.trigger.subagent.completed': '子智能体已完成任务', + 'message.trigger.subagent.aborted': '子智能体任务已停止', + 'message.trigger.subagent.error': '子智能体执行失败', + 'message.trigger.subagent.maxTokens': '子智能体已达 token 上限', + 'message.trigger.subagent.refusal': '子智能体拒绝执行', + 'message.trigger.subagent.unknown': '子智能体异常结束', 'message.trigger.github': '收到 GitHub 事件', 'message.trigger.webhook': '收到外部事件', 'message.trigger.schedule': '自动化任务', @@ -257,6 +263,12 @@ export const en = { 'message.trigger.agent': 'Task message received', 'message.trigger.team': 'Team message received', 'message.trigger.subagent': 'Subtask status updated', + 'message.trigger.subagent.completed': 'Subagent run completed', + 'message.trigger.subagent.aborted': 'Subagent run stopped', + 'message.trigger.subagent.error': 'Subagent run failed', + 'message.trigger.subagent.maxTokens': 'Subagent reached the token limit', + 'message.trigger.subagent.refusal': 'Subagent declined the task', + 'message.trigger.subagent.unknown': 'Subagent run ended unexpectedly', 'message.trigger.github': 'GitHub event received', 'message.trigger.webhook': 'External event received', 'message.trigger.schedule': 'Automation task', @@ -456,6 +468,12 @@ export const ja = { 'message.trigger.agent': 'タスクメッセージを受信しました', 'message.trigger.team': 'チームメッセージを受信しました', 'message.trigger.subagent': 'サブタスクの状態が更新されました', + 'message.trigger.subagent.completed': 'サブエージェントの実行が完了しました', + 'message.trigger.subagent.aborted': 'サブエージェントの実行が停止しました', + 'message.trigger.subagent.error': 'サブエージェントの実行が失敗しました', + 'message.trigger.subagent.maxTokens': 'サブエージェントがトークンの上限に達しました', + 'message.trigger.subagent.refusal': 'サブエージェントがタスクを拒否しました', + 'message.trigger.subagent.unknown': 'サブエージェントの実行が予期せず終了しました', 'message.trigger.github': 'GitHubイベントを受信しました', 'message.trigger.webhook': '外部イベントを受信しました', 'message.trigger.schedule': '自動化タスク', @@ -655,6 +673,12 @@ export const es = { 'message.trigger.agent': 'Mensaje de tarea recibido', 'message.trigger.team': 'Mensaje del equipo recibido', 'message.trigger.subagent': 'Estado de subtarea actualizado', + 'message.trigger.subagent.completed': 'Ejecución del subagente completada', + 'message.trigger.subagent.aborted': 'Ejecución del subagente detenida', + 'message.trigger.subagent.error': 'La ejecución del subagente falló', + 'message.trigger.subagent.maxTokens': 'El subagente alcanzó el límite de tokens', + 'message.trigger.subagent.refusal': 'El subagente rechazó la tarea', + 'message.trigger.subagent.unknown': 'La ejecución del subagente terminó de forma inesperada', 'message.trigger.github': 'Evento GitHub recibido', 'message.trigger.webhook': 'Evento externo recibido', 'message.trigger.schedule': 'Tarea de automatización', @@ -854,6 +878,12 @@ export const fr = { 'message.trigger.agent': 'Message de tâche reçu', 'message.trigger.team': "Message d'équipe reçu", 'message.trigger.subagent': 'Statut de la sous-tâche mis à jour', + 'message.trigger.subagent.completed': 'Exécution du sous-agent terminée', + 'message.trigger.subagent.aborted': 'Exécution du sous-agent arrêtée', + 'message.trigger.subagent.error': 'Échec de l’exécution du sous-agent', + 'message.trigger.subagent.maxTokens': 'Le sous-agent a atteint la limite de jetons', + 'message.trigger.subagent.refusal': 'Le sous-agent a refusé la tâche', + 'message.trigger.subagent.unknown': 'L’exécution du sous-agent s’est terminée de façon inattendue', 'message.trigger.github': 'Événement GitHub reçu', 'message.trigger.webhook': 'Événement externe reçu', 'message.trigger.schedule': "Tâche d'automatisation", @@ -1053,6 +1083,12 @@ export const de = { 'message.trigger.agent': 'Aufgabennachricht erhalten', 'message.trigger.team': 'Teamnachricht erhalten', 'message.trigger.subagent': 'Unteraufgabenstatus aktualisiert', + 'message.trigger.subagent.completed': 'Ausführung des Subagenten abgeschlossen', + 'message.trigger.subagent.aborted': 'Ausführung des Subagenten gestoppt', + 'message.trigger.subagent.error': 'Ausführung des Subagenten fehlgeschlagen', + 'message.trigger.subagent.maxTokens': 'Subagent hat das Token-Limit erreicht', + 'message.trigger.subagent.refusal': 'Subagent hat die Aufgabe abgelehnt', + 'message.trigger.subagent.unknown': 'Ausführung des Subagenten unerwartet beendet', 'message.trigger.github': 'GitHub-Ereignis empfangen', 'message.trigger.webhook': 'Externes Ereignis empfangen', 'message.trigger.schedule': 'Automatisierungsaufgabe', @@ -1252,6 +1288,12 @@ export const ru = { 'message.trigger.agent': 'Сообщение о задаче получено', 'message.trigger.team': 'Сообщение команды получено', 'message.trigger.subagent': 'Статус подзадачи обновлен', + 'message.trigger.subagent.completed': 'Работа субагента завершена', + 'message.trigger.subagent.aborted': 'Работа субагента остановлена', + 'message.trigger.subagent.error': 'Работа субагента завершилась с ошибкой', + 'message.trigger.subagent.maxTokens': 'Субагент достиг лимита токенов', + 'message.trigger.subagent.refusal': 'Субагент отказался выполнять задачу', + 'message.trigger.subagent.unknown': 'Работа субагента неожиданно завершилась', 'message.trigger.github': 'Событие GitHub получено', 'message.trigger.webhook': 'Получено внешнее событие', 'message.trigger.schedule': 'Задача автоматизации', @@ -1451,6 +1493,12 @@ export const pt = { 'message.trigger.agent': 'Mensagem de tarefa recebida', 'message.trigger.team': 'Mensagem da equipe recebida', 'message.trigger.subagent': 'Status da subtarefa atualizado', + 'message.trigger.subagent.completed': 'Execução do subagente concluída', + 'message.trigger.subagent.aborted': 'Execução do subagente interrompida', + 'message.trigger.subagent.error': 'Falha na execução do subagente', + 'message.trigger.subagent.maxTokens': 'O subagente atingiu o limite de tokens', + 'message.trigger.subagent.refusal': 'O subagente recusou a tarefa', + 'message.trigger.subagent.unknown': 'A execução do subagente terminou inesperadamente', 'message.trigger.github': 'GitHub evento recebido', 'message.trigger.webhook': 'Evento externo recebido', 'message.trigger.schedule': 'Tarefa de automação', diff --git a/packages/client/ui-chat/src/client/reasoning-text.ts b/packages/client/ui-chat/src/client/reasoning-text.ts new file mode 100644 index 0000000000..c690e8795c --- /dev/null +++ b/packages/client/ui-chat/src/client/reasoning-text.ts @@ -0,0 +1,25 @@ +/** Display text preparation for model reasoning. */ + +/** + * Prepare complete or streaming reasoning for display. + * @param text - original complete or streaming reasoning. + * @returns display text, or empty text when no displayable content is available. + */ +export function reasoningText(text: string): string { + if (text[0] !== '<') return text + /* v8 ignore start -- Custom rendering behavior is outside unit coverage. */ + const opening = '' + if (opening.startsWith(text)) return '' + if (!text.startsWith(opening)) return text + const closing = '' + const end = text.indexOf(closing, opening.length) + if (end === -1) return '' + let start = end + closing.length + while (start < text.length) { + if (text[start] === '\n') start++ + else if (text[start] === '\r' && text[start + 1] === '\n') start += 2 + else break + } + return text.slice(start) + /* v8 ignore stop */ +} diff --git a/packages/client/ui-chat/tests/chat-visibility.client.spec.ts b/packages/client/ui-chat/tests/chat-visibility.client.spec.ts new file mode 100644 index 0000000000..70b2d38fef --- /dev/null +++ b/packages/client/ui-chat/tests/chat-visibility.client.spec.ts @@ -0,0 +1,68 @@ +import { describe, expect, it } from 'vitest' +import { CommandId } from '@deepseek-ai/dsh-commands/brand' +import type { ChatNode } from '../src/client/contract/chat-nodes.ts' +import { isVisibleChatNode } from '../src/client/contract/chat-visibility.ts' + +const placement = { + key: 'command:test', id: 'test', target: 'chat', anchorSeq: 1, + location: { kind: 'unresolved' }, visibility: 'visible', +} as const + +function command(args: string | null, outcome: ChatNode<'command'>['data']['outcome'], name: string | null = 'team'): ChatNode<'command'> { + return { + ...placement, kind: 'command', + data: { kind: 'command', seq: 1, time: 0, commandId: CommandId('test'), name, args, outcome }, + } +} + +describe('Chat-only command visibility', () => { + it.each(['on', 'off', ' on ', '\toff\n'])('omits pending and successful Team selection %j without rewriting the record', (args) => { + for (const outcome of [null, { kind: 'success', text: 'Unchanged recorded output' }] as const) { + const node = command(args, outcome) + const before = JSON.stringify(node) + expect(isVisibleChatNode(node)).toBe(false) + expect(JSON.stringify(node)).toBe(before) + } + }) + + it.each(['on', 'off', null, 'invalid'])('keeps a failed Team command visible for input %j', (args) => { + expect(isVisibleChatNode(command(args, { kind: 'error', text: 'The operation failed' }))).toBe(true) + }) + + it.each(['ON', 'status', '', null])('does not infer a toggle from result text for input %j', (args) => { + expect(isVisibleChatNode(command(args, { kind: 'success', text: 'Agent Teams enabled.' }))).toBe(true) + expect(isVisibleChatNode(command(args, null))).toBe(true) + }) + + it.each(['other', null])('retains unrelated and window-cut commands named %j', (name) => { + expect(isVisibleChatNode(command('on', { kind: 'success', text: 'done' }, name))).toBe(true) + }) + + it('retains a failed toggle after its hidden pending record settles', () => { + const pending = command('on', null) + const failed = { ...pending, data: { ...pending.data, outcome: { kind: 'error' as const, text: 'Save failed' } } } + expect(isVisibleChatNode(pending)).toBe(false) + expect(isVisibleChatNode(failed)).toBe(true) + }) + + it('keeps the existing permission and explicit hidden-node policies', () => { + expect(isVisibleChatNode(command('on', { kind: 'error', text: 'failure' }, 'permission'))).toBe(false) + expect(isVisibleChatNode({ ...command('on', { kind: 'error', text: 'failure' }), visibility: 'hidden' })).toBe(false) + }) +}) + +it('keeps ordinary prompt/context hidden but retains tool changes', () => { + const prompt: ChatNode<'system-prompt'> = { ...placement, kind: 'system-prompt', data: { text: 'system instructions' } } + const context: ChatNode<'context'> = { + ...placement, kind: 'context', + data: { + kind: 'context', seq: 1, time: 0, content: [{ type: 'text', text: 'context' }], source: null, + producer: { role: 'inject', label: null }, form: null, + }, + } + expect(isVisibleChatNode(prompt)).toBe(false) + expect(isVisibleChatNode(context)).toBe(false) + for (const type of ['tool-addition', 'tool-removal'] as const) { + expect(isVisibleChatNode({ ...context, data: { ...context.data, content: [{ type, toolName: 'example' }] } })).toBe(true) + } +}) diff --git a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts index 6a2871d0fb..979747c8ea 100644 --- a/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts +++ b/packages/client/ui-chat/tests/conversation-node-definitions.client.spec.ts @@ -2254,6 +2254,18 @@ describe('built-in conversation node Definitions', () => { .map(candidate => candidate.data)).toEqual([{ text: 'A' }, { text: 'B', update: true }, { text: 'C' }]) }) + it('hides a published prompt node while a prepended replacement makes its prompt unknown', () => { + const value = assembler([systemAt(10, 'Shown')], true) + const { key } = node(snapshot(value), 'system-prompt')! + expect(snapshot(value).nodes.get(key)?.visibility).toBe('visible') + value.prepend([systemAt(5, 'Older', 2)], true) + value.flush() + expect(snapshot(value).nodes.get(key)).toMatchObject({ visibility: 'hidden', data: { text: 'Shown' } }) + value.prepend([systemAt(1, 'First')], false) + value.flush() + expect(snapshot(value).nodes.get(key)).toMatchObject({ visibility: 'visible', data: { text: 'Shown', update: true } }) + }) + it('never renders a system/message as a transcript bubble', () => { const value = assembler([ at(1, 'turn/start', { turn: 1 }), diff --git a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx index c2e0543f3c..1bd1e90c75 100644 --- a/packages/client/ui-chat/tests/reasoning-component-fixture.tsx +++ b/packages/client/ui-chat/tests/reasoning-component-fixture.tsx @@ -5,7 +5,7 @@ import { zh as commonZh } from '@deepseek-ai/dsh-client-locale/src/locales/zh.ts import type { PropsRenderFactories } from '@deepseek-ai/dsh-client-ui-slots' import type { ReasoningContentInput } from '../src/client/contract/slots.ts' import type { AssistantMarkdownProps } from '../src/client/chat/AssistantMarkdown.tsx' -import { ReasoningContent } from '../src/client/chat/ReasoningContent.tsx' +import { DefaultReasoningBody, ReasoningContent } from '../src/client/chat/ReasoningContent.tsx' import { zh } from '../src/client/locale.ts' const t = makeTranslate(zh, commonZh) @@ -23,7 +23,9 @@ function content(input: ReasoningContentInput) { /** Render the production child component without emulating a registry or its dispatch. */ export const renderReasoningSlot: AssistantMarkdownProps['renderSlot'] = (key: string, input: object) => { if (key !== 'conversation.chat.reasoning.body') throw new Error(`Unexpected reasoning Slot: ${key}`) - return content(input as ReasoningContentInput) + return createElement(DefaultReasoningBody, { + ...input, renderFactorySlot: renderReasoningFactory, + } as ComponentProps) } /** Supply the official component at the Factory call seam of a standalone component unit. */ diff --git a/packages/client/ui-chat/tests/reasoning-content.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-content.client.spec.tsx index f56a1c37d8..f1b2f159c6 100644 --- a/packages/client/ui-chat/tests/reasoning-content.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-content.client.spec.tsx @@ -67,7 +67,9 @@ describe('reasoning Content Factory', () => { it('restores the registered default after a wrapping plugin unloads and removes the Factory with its owner', async () => { const b = await createReasoningRenderFixture('en') - const view = b.render(b.renderSlot('conversation.chat.reasoning.body', { text: 'Original thought', running: false })) + const view = b.render(b.renderSlot('conversation.chat.reasoning.body', { + rawText: 'Original model thought', text: 'Original thought', running: false, + })) expect(view.getByText('Original thought')).toBeTruthy() expect(b.runtime.slots.entries('conversation.chat.reasoning.body')[0]?.options.priority).toBe(100) const plugin = await b.runtime.mount({ inject: ['slots'], apply: (ctx) => { diff --git a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx index 42bf510e98..6494ce61c5 100644 --- a/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx +++ b/packages/client/ui-chat/tests/reasoning-row.client.spec.tsx @@ -39,7 +39,7 @@ describe('AssistantMarkdown reasoning blocks', () => { expect(view.getAllByRole('button')).toHaveLength(1) expect(view.container.querySelectorAll('[data-variant="think"]')).toHaveLength(1) fireEvent.click(view.getByRole('button')) - expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { text, running: false }) + expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { rawText: text, text, running: false }) expect(view.getByText('Visible reasoning').tagName).toBe('STRONG') expect(blocks.map(block => block.text)).toEqual(texts) }) @@ -134,7 +134,7 @@ describe('AssistantMarkdown reasoning blocks', () => { }) describe('ReasoningRow', () => { - it('offers only text and streaming state to the standard Body Slot after expansion', () => { + it('offers original and display text after expansion', () => { const calls = vi.fn() const extension: AssistantMarkdownProps['renderSlot'] = (key, owner, options) => { calls(key, owner) @@ -144,7 +144,7 @@ describe('ReasoningRow', () => { usePresentation={useDetailedPresentation} renderSlot={extension} t={t} />) expect(calls).not.toHaveBeenCalled() fireEvent.click(view.getByRole('button')) - expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { text: 'Original thought', running: false }) + expect(calls).toHaveBeenCalledWith('conversation.chat.reasoning.body', { rawText: 'Original thought', text: 'Original thought', running: false }) expect(view.getAllByText('Original thought')).toHaveLength(1) expect(view.getAllByRole('button')).toHaveLength(1) }) diff --git a/packages/client/ui-chat/tests/reasoning-text.client.spec.ts b/packages/client/ui-chat/tests/reasoning-text.client.spec.ts new file mode 100644 index 0000000000..9e8a7b1874 --- /dev/null +++ b/packages/client/ui-chat/tests/reasoning-text.client.spec.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { reasoningText } from '../src/client/reasoning-text.ts' + +describe('reasoning display text', () => { + it.each([ + '', + 'Ordinary reasoning', + '普通思考正文', + '\n Original text \n', + 'Original text', + ])('preserves ordinary reasoning %j', (text) => { + expect(reasoningText(text)).toBe(text) + }) +}) diff --git a/packages/client/ui-chat/tests/turn-trigger.client.spec.tsx b/packages/client/ui-chat/tests/turn-trigger.client.spec.tsx index c45672dac5..bbb2999cc7 100644 --- a/packages/client/ui-chat/tests/turn-trigger.client.spec.tsx +++ b/packages/client/ui-chat/tests/turn-trigger.client.spec.tsx @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { cleanup, fireEvent, render } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' -import { IconClockOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' +import { IconClockOutlineRegular, IconUsersOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { ChatNode } from '../src/client/contract/chat-nodes.ts' import { TurnTriggerNodeView } from '../src/client/chat/TurnTriggerNodeView.tsx' import { turnTriggerDetails } from '../src/client/chat/turn-trigger.ts' @@ -72,6 +72,37 @@ describe('Turn trigger notices', () => { expect(node.data.source).toEqual({ kind: 'schedule' }) }) + it.each([ + ['completed', 'Subagent run completed', '子智能体已完成任务'], + ['aborted', 'Subagent run stopped', '子智能体任务已停止'], + ['error', 'Subagent run failed', '子智能体执行失败'], + ['max-tokens', 'Subagent reached the token limit', '子智能体已达 token 上限'], + ['refusal', 'Subagent declined the task', '子智能体拒绝执行'], + ['backend-specific', 'Subagent run ended unexpectedly', '子智能体异常结束'], + ])('presents only the recorded %s outcome in both locales', (stopReason, english, chinese) => { + const source = { kind: 'subagent-settled', stopReason, senderSessionId: 'child-1' } + const node = trigger(source) + const view = render() + expect(view.getByRole('button').textContent).toContain(english) + expect(view.getByRole('button').textContent).not.toContain(' · ') + const reference = render() + expect(view.getByRole('button').querySelector('svg')?.outerHTML) + .toBe(reference.container.querySelector('svg')?.outerHTML) + view.rerender() + expect(view.getByRole('button').textContent).toContain(chinese) + expect(view.getByRole('button').textContent).not.toContain(' · ') + fireEvent.click(view.getByRole('button')) + expect(view.container.querySelector('[data-context-text]')?.textContent) + .toBe('Recorded notification\nwith its original body.') + expect(node.data.source).toEqual(source) + }) + + it.each([undefined, null, false, 12, {}, '', []])('does not infer an absent or malformed outcome %j from English text', (stopReason) => { + const node = trigger({ kind: 'subagent-settled', stopReason, summary: 'Background subagent child-1 finished.' }) + node.data.content = [{ type: 'text', text: 'Background subagent child-1 finished.' }] + expect(turnTriggerDetails(node.data)).toEqual({ title: 'message.trigger.subagent', icon: 'subagent' }) + }) + it('opens the recorded notice body and closes it independently of the Turn', () => { const view = render() const button = view.getByRole('button') diff --git a/packages/client/ui-cli-account/README.i18n.yaml b/packages/client/ui-cli-account/README.i18n.yaml index 9653b0aba3..f7f68c15df 100644 --- a/packages/client/ui-cli-account/README.i18n.yaml +++ b/packages/client/ui-cli-account/README.i18n.yaml @@ -3,50 +3,50 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/client/ui-cli-account/README.md /: - en: 2a9fe27e72f4a975 - zh: 969761d0befd982e + en: 4a0a76a25ebb3b03 + zh: 6a1cd7a4696ca49d /deepseek-ai-dsh-client-ui-cli-account: en: 9459a591a9b82dd8 zh: cb4059b1ef791c5c /deepseek-ai-dsh-client-ui-cli-account/summary: - en: cb14be46b7eb347e - zh: 2f4478ad48ea8fd2 + en: 4feaf77d30c415fe + zh: f8d86b6ca72a4e93 /deepseek-ai-dsh-client-ui-cli-account/table-of-contents: en: d152484eb41ac6b4 zh: 5b6bd00fce5371c3 /deepseek-ai-dsh-client-ui-cli-account/use-this-package: - en: 82bc46a60479254c - zh: 8b0ea3415ab8a35b + en: 43b3c3104286861b + zh: 7f7730703060dbcb /deepseek-ai-dsh-client-ui-cli-account/use-this-package/when-to-choose-it: - en: c63cdee18f15d294 - zh: ce6105e42a08add5 + en: b516e012a3b8495d + zh: ff798425ebae7f24 /deepseek-ai-dsh-client-ui-cli-account/use-this-package/register-an-account: - en: 14d247f65f5a3dfa - zh: 7300c38f179e5ee1 + en: fec230814ae2f80c + zh: f4ebea2c5ae751d8 /deepseek-ai-dsh-client-ui-cli-account/use-this-package/present-the-section: - en: faab698b3dd76448 - zh: 85d24414e05606f5 + en: e5c950686c4acf7e + zh: f0db1365c0ab023f /deepseek-ai-dsh-client-ui-cli-account/use-this-package/following-operations: - en: 2c9eb9885c50592e - zh: bc7619a5173f161b -/deepseek-ai-dsh-client-ui-cli-account/use-this-package/shared-dictionary-keys: - en: f9a8b0974afb8bf9 - zh: 334b9d8fc711aec1 + en: d14325ddd63f868c + zh: b61ebab9f850570a +/deepseek-ai-dsh-client-ui-cli-account/use-this-package/shared-copy: + en: 118fe2bb507c1f41 + zh: eaf7c056c07a5910 /deepseek-ai-dsh-client-ui-cli-account/understand-the-implementation: - en: 5ec779496ac5f7dd - zh: ec3938ad0a9656d9 + en: 7424937025fc08fa + zh: 5abca9c27bc44baa /deepseek-ai-dsh-client-ui-cli-account/further-exploration: - en: 368d56aaef042324 - zh: 00314c6285c0beb9 + en: 1c86df041107a86e + zh: a6bec2531493df16 /deepseek-ai-dsh-client-ui-cli-account/model-experience: - en: 47f94c48dcc93bae - zh: 9584dee7c543c6c7 + en: 71f520816cb6b812 + zh: 6504c82f890b013c /deepseek-ai-dsh-client-ui-cli-account/model-experience/kv-cache-effect: en: 4cd0965a7997970e - zh: 81b3b87b2ba4756f + zh: 690e5a9d945f7f6e /deepseek-ai-dsh-client-ui-cli-account/known-limitations-and-deferred-work: - en: bb83d0b097834b84 - zh: c39b0869c99aa9eb + en: 3ffb89f2ebe275bf + zh: 668e21ef156658f4 /deepseek-ai-dsh-client-ui-cli-account/known-limitations-and-deferred-work/dev-note: - en: 00853dccb6e5f32c - zh: 8b082da910fc429a + en: 8305fa65f9dd0e8f + zh: 50607c5699fa5b26 diff --git a/packages/client/ui-cli-account/README.md b/packages/client/ui-cli-account/README.md index 2d3a3a88a2..1e628f24d8 100644 --- a/packages/client/ui-cli-account/README.md +++ b/packages/client/ui-cli-account/README.md @@ -1,5 +1,5 @@ --- -description: "Show a CLI app plugin's account section, title tag, activation prompt, confirmations, and notices on the Plugins page through `ctx.cliAccounts`, following the plugin's Host account Remote with copy the plugin translates." +description: "Register a CLI app plugin's account on the Host with `ctx.cliAccounts` and show its section, title tag, activation prompt, confirmations, and notices on the Plugins page through one `cliAccounts` Remote, with the plugin's own text and the shared copy of this package." kind: "package-reference" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -CLI app plugins such as Feishu and WeCom show their account on the Plugins page by registering it with `ctx.cliAccounts`. The registry follows the plugin's account stream, opens an authorization link once in the browser that started the operation, and renders the section, title tag, activation prompt, confirmations, and notices. Each plugin keeps its own Remote operations, presentation, and dictionary. The Web and Desktop compositions mount the registry through [`dsh-web-app`](../../bundle/web-app/README.md). +CLI app plugins such as Feishu and WeCom register their account on the Host with `ctx.cliAccounts` to show it on the Plugins page. The registry serves every account through one `cliAccounts` Remote and starts or cancels only the operations each account lists. The browser half renders each account's section, title tag, activation prompt, confirmations, and notices, and opens an authorization link once in the browser that started the operation. Plugins supply their text as `LocalizedText`; the shared copy comes from this package's dictionary. The Web and Desktop compositions load both halves through [`dsh-web-app`](../../bundle/web-app/README.md). ## Table of Contents @@ -25,53 +25,52 @@ CLI app plugins such as Feishu and WeCom show their account on the Plugins page ## Use this package -A plugin's browser half registers its account once, with its Remote operations, its dictionary, and a presenter that maps the page snapshot to what the section shows. +A plugin's Host row registers its account once; the plugin ships no browser code for the account. ### When to choose it -Choose it for the page half of a plugin built on [`@deepseek-ai/dsh-cli-account`](../../connector/cli-account/README.md), whose Remote streams a `CliAccountView`. A plugin that connects a hosted service over MCP uses the MCP account surfaces instead. +Choose it for a plugin built on [`@deepseek-ai/dsh-cli-account`](../../connector/cli-account/README.md), whose vendor CLI keeps the account. A plugin that connects a hosted service over MCP uses the MCP account surfaces instead. ### Register an account -The plugin's browser half injects `locale` and `cliAccounts`, registers its dictionary, and registers its account for its own lifetime: +The plugin's Host row registers its `CliAccountRuntime` while the registry runs, so a composition without the registry, such as a headless profile, skips the registration: ```ts ignore-check -export const inject = ['remote', 'locale', 'cliAccounts'] +import type {} from '@deepseek-ai/dsh-client-ui-cli-account' export function apply(ctx: Context): void { - ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'acme: dictionaries') - const t = ctx.locale.bind(NS) - ctx.effect(() => ctx.cliAccounts.register({ - packageName: '@acme/cli', locale: NS, - follow: signal => ctx.remote.acme.follow(signal), - cancel: id => ctx.remote.acme.cancel(id), - notices: { connect: () => t('notice.connected') }, - present: (snapshot, page) => presentAccount(snapshot, page, t), - }), 'acme: account') + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['cliAccounts'], (scope) => { + scope.effect(() => scope.cliAccounts.register({ + packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) } ``` -`packageName` is the npm package whose bundle page carries the section and tag. `locale` names the plugin's dictionary namespace, which must translate every [shared key](#shared-dictionary-keys); TypeScript rejects a namespace that lacks one. `follow` and `cancel` call the plugin's Remote. `notices` maps an operation kind to the translated notice its success reports in the browser that started it; unlisted kinds report none. The plugin lists `@deepseek-ai/dsh-client-ui-cli-account` in `dsh.client.inject` and imports its types with `import type`. The returned disposer removes the surfaces and closes the account's Host stream. A registration whose package is already registered throws and leaves none of its surfaces behind. +`packageName` is the npm package whose bundle page carries the section and tag; a second registration for the same package throws. `source` is the account, which `CliAccountRuntime` implements. `operations` lists the kinds a page button may start, each with the optional text its success reports in the browser that started it; the registry rejects any other kind. `copy` holds the section title, the hint under it, and the activation prompt's title, body, and Connect label. The plugin imports the registry's types with `import type`. The returned disposer withdraws the account from every page. ### Present the section -`present(snapshot, page)` runs while a surface renders and returns a `CliAccountDisplay`: the phase, an optional status label, buttons, detail, extra rows, and failure, with every string translated. It reads only the snapshot, so translating through `ctx.locale.bind` follows a language switch. Button callbacks use `page`: `start(call)` runs one Remote start at a time, and `cancel`, `openAuthorization`, and `retry` act on the followed operation and the Host stream. The snapshot carries the Host view, whether the stream is delivering or has stopped, whether a page action is pending, and the latest notice. +`present(view)` maps the account view to a `CliAccountDisplay`: the phase, the status line, the optional title tag, buttons, the operation Connect starts in the activation prompt, detail, notes, and failure with its untranslated diagnostic items. The registry calls it for every stream on each change, so it only maps the view. Every string is `LocalizedText`, which each browser resolves in its active language. A button carries a command: `start` with one of the registered operation kinds, `cancel` for the operation in progress, which the Host ignores in a phase that is not cancellable, or `open` to reopen its authorization link. A button with `confirm` asks first and runs only after the user accepts. | Surface | Behavior | |---|---| -| Section | Title, status, buttons, detail, extra rows, failure, and hint; the status defaults to the phase's `status.*` copy, with `connecting` labelled as checking. Buttons are disabled while a page action is pending or the Host stream is down, except while stopped so retry can reopen it. A button with `confirm` asks first and runs only after the user accepts. A failure shows the plugin's guidance, then the classified command, exit code, and allowlisted details | -| Title tag | Shown only on the enabled bundle's page or one of its row pages, and only once the phase settles | -| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and runs the section's first primary button that asks no confirmation. It dismisses itself once the phase settles elsewhere | -| Notice | The latest outcome, outside the Plugins panel's lifetime: the plugin's success copy, or the shared failure copy with a warning icon | +| Section | Title, status, buttons, detail, notes, failure, and hint. Buttons are disabled while an action this browser started is pending or the Host stream is down. A failure shows the plugin's text, then its diagnostic items | +| Title tag | The display's `badge`, shown only on the enabled bundle's page or one of its row pages, and only while the display has one | +| Activation prompt | Open while the phase is `disconnected` after the bundle is switched on; Connect opens the bundle page and starts the display's `connect` operation, if it names one. It dismisses itself once the phase settles elsewhere | +| Notice | The latest outcome in this browser, outside the Plugins panel's lifetime: the operation's success text, or the shared failure copy with a warning icon | ### Following operations -The page follows the operation its latest start returned, from that answer until the stream delivers the operation's result; each start attempt first drops the operation followed before, so a rejected start leaves none and reports the `action-failed` notice once. Clicks while a page action is pending are ignored. Each link the followed operation offers opens once in a new window, over HTTPS only, and a later operation that offers the same link opens it again. A result that a later operation replaces before the stream delivers it reports nothing. A stream that fails for good marks the snapshot stopped, and `retry` reopens it once, however often it is called. Removing the registration closes the stream; afterwards the page opens no link and reports no notice, while Host-owned operations keep running. +Each browser opens one stream when the Web app loads, and the Host checks every account that runs no operation for each new stream; an account registered while a stream is open is checked at once. A browser follows the operation its latest start returned, from that answer until the stream delivers the operation's result; each start attempt first drops the operation followed before, so a rejected start leaves none and reports the failure notice once. Clicks while an action is pending are ignored. Each link the followed operation offers opens once in a new window, over HTTPS only. Other browsers show the same section but open no link and report no notice. A stream that fails for good shows the account service as not running with Retry, which reopens the stream once however often it is pressed. Unloading the browser half closes the stream; Host-owned operations keep running. - -### Shared dictionary keys +### Shared copy -The surfaces read these keys from the plugin's namespace: `section.title`, `hint`, `close`, `action.cancel`, `action.connect`, `activation.title`, `activation.body`, `activation.later`, `failure.details` (with `{details}`), `failure.exitCode` (with `{code}`), `notice.action-failed`, `badge.` for every phase but `checking`, and `status.` for every phase but `connecting`. +The `cliAccount` dictionary holds the copy every account shares: Close, Cancel, Retry, Later, the diagnostic label, the failure notice, and the not-running status, tag, and detail. Every other string comes from the plugin. ----- @@ -81,15 +80,21 @@ The surfaces read these keys from the plugin's namespace: `section.title`, `hint
    Implementation internals — click to expand -`register()` creates one `CliAccountConnection` per account. It mirrors the plugin's `follow` stream and keeps the Host view, whether the stream is delivering, whether a page action is pending, and the latest notice. The registration contributes `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, a `plugins.detail.badge` entry with id `.account`, and a `shell.overlay` notice with id `.account-toast`. Each entry declares the plugin's namespace, so the renderer supplies its `t`, and all four inject one face that shares one snapshot and calls the plugin's presenter. The registration is one effect of this plugin's fiber: a setup failure disposes what it already added, and teardown removes the slot entries before closing the stream, whichever of the plugin's disposer and this plugin's unload runs first. +The Host half, `CliAccounts`, is a Remote service. `register()` observes the account's source, and each `watch` stream reads every account's entry after each change, coalescing changes that arrive before the next read: the copy, `present(view)`, the operation in progress, and the latest result with its success text. `start` and `cancel` route by package to the account's source. + +The browser half mounts the `cliAccounts` Remote and opens one `watch` stream through `CliAccountsConnection`, which keeps one snapshot store per account: the Host entry, whether the stream is delivering or has stopped, whether an action this browser started is pending, and the latest notice. For each account the Host reports, it registers `plugins.bundle.config` and `plugins.bundle.activation` keyed by the package name, a `plugins.detail.badge` entry with id `.account`, and a `shell.overlay` notice with id `.account-toast`, all under the `cliAccount` namespace and injecting one face. An account the Host drops loses its four entries, and unloading withdraws the entries and the stream before the Remote. | File | Role | |---|---| -| [`src/client/index.ts`](src/client/index.ts) | The `ctx.cliAccounts` registry and the four slot registrations | -| [`src/client/types.ts`](src/client/types.ts) | Registration, display, snapshot, and dictionary types | -| [`src/client/connection.ts`](src/client/connection.ts) | The Host view mirror, link opening, notices, and pending-action guard | +| [`src/index.ts`](src/index.ts) | The `ctx.cliAccounts` registry and its Remote | +| [`src/client/index.ts`](src/client/index.ts) | The browser entry bound to the generated Remote | +| [`src/client/mount.ts`](src/client/mount.ts) | The Remote mount, the dictionary, and the slot registrations of each account | +| [`src/client/connection.ts`](src/client/connection.ts) | The stream mirror, link opening, notices, and pending-action guard | | [`src/client/components.tsx`](src/client/components.tsx) | The surfaces and the slot entries that read the face | -| [`src/index.ts`](src/index.ts) | The empty Node half | +| [`src/client/locales.ts`](src/client/locales.ts) | The shared dictionary | +| [`src/client/types.ts`](src/client/types.ts) | Snapshot, notice, and face types | + +The registration, display, and entry types live in [`@deepseek-ai/dsh-cli-account/types`](../../connector/cli-account/src/types.ts).
    @@ -98,7 +103,7 @@ The surfaces read these keys from the plugin's namespace: `section.title`, `hint ## Further Exploration -- [CLI account library](../../connector/cli-account/README.md) — the Host half that streams the view. +- [CLI account library](../../connector/cli-account/README.md) — the account runtime and the page types. - [Plugin manager page](../ui-plugin-manager/README.md) — the Plugins page and its bundle slots. - [Client package map](../README.md) — adjacent browser UI packages. @@ -107,7 +112,7 @@ The surfaces read these keys from the plugin's namespace: `section.title`, `hint ## Model Experience -None, as the account surfaces are browser UI and add no model input. Each plugin documents the CLI and skills its account enables. +None, as the registry and its surfaces are Plugins page UI and add no model input. Each plugin documents the CLI and skills its account enables. #### KV Cache effect @@ -117,9 +122,9 @@ None; registering or removing an account changes no model-visible text. -- The six display phases are fixed; a plugin maps any further account state onto one of them. -- The shared dictionary keys are the same for every plugin; a plugin cannot rename them. -- Each account opens its own Host stream. +- The five display phases are fixed; a plugin maps any further account state onto one of them. +- A plugin whose Host row fails to load shows no account section; the Plugins page still lists the bundle with its load failure. +- Each browser that loads the Web app starts a check of every idle account. - The Web and Desktop compositions load the registry whether or not a CLI app plugin is installed. @@ -128,6 +133,6 @@ None; registering or removing an account changes no model-visible text.
    Working context for maintainers — click to expand -Client specs drive `CliAccountConnection` with a fake Remote stream, render the surfaces with a key-echo translator, and register accounts against a real slot registry. +Host specs drive the registry with fake account sources. Client specs drive `CliAccountsConnection` with a fake Remote stream, render the surfaces with the Chinese dictionary, and mount the browser half against a real slot registry and locale runtime. Source coverage excludes `src/client/index.ts`, which imports the generated Remote that exists only in `lib/`.
    diff --git a/packages/client/ui-cli-account/README.zh.md b/packages/client/ui-cli-account/README.zh.md index a0cc82ae28..fcae2aa577 100644 --- a/packages/client/ui-cli-account/README.zh.md +++ b/packages/client/ui-cli-account/README.zh.md @@ -1,5 +1,5 @@ --- -description: "通过 `ctx.cliAccounts` 在插件页显示 CLI 应用插件的账号区块、标题旁标签、开启引导、确认和提示,内容跟随插件的 Host 账号 Remote,文案由插件翻译。" +description: "通过 `ctx.cliAccounts` 在 Host 上注册 CLI 应用插件的账号,并经由一个 `cliAccounts` Remote 在插件页显示其区块、标题旁标签、开启引导、确认和提示,文案来自插件自己的文本和本包的共用文案。" kind: "package-reference" --- @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -飞书、企业微信等 CLI 应用插件通过 `ctx.cliAccounts` 注册账号,在插件页显示账号。注册表跟随插件的账号流,在发起操作的浏览器中把授权链接打开一次,并渲染区块、标题旁标签、开启引导、确认和提示。每个插件保留各自的 Remote 操作、展示推导和字典。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 挂载注册表。 +飞书、企业微信等 CLI 应用插件在 Host 上通过 `ctx.cliAccounts` 注册账号,在插件页显示账号。注册表通过一个 `cliAccounts` Remote 提供所有账号,并且只启动或取消各账号列出的操作。浏览器一半渲染每个账号的区块、标题旁标签、开启引导、确认和提示,并在发起操作的浏览器中把授权链接打开一次。插件以 `LocalizedText` 提供自己的文案;共用文案来自本包的字典。Web 与桌面端组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 加载这两半。 ## 目录 @@ -25,53 +25,52 @@ kind: "package-reference" ## 使用此包 -插件的浏览器一半注册一次账号,提供自己的 Remote 操作、字典,以及把页面快照映射为区块内容的展示函数。 +插件的 Host 行注册一次账号;插件不为账号提供任何浏览器代码。 ### 何时选择 -用于基于 [`@deepseek-ai/dsh-cli-account`](../../connector/cli-account/README.zh.md) 的插件的页面一半,其 Remote 流式推送 `CliAccountView`。通过 MCP 接入托管服务的插件改用 MCP 账号界面。 +用于基于 [`@deepseek-ai/dsh-cli-account`](../../connector/cli-account/README.zh.md) 的插件,其厂商 CLI 保存账号。通过 MCP 接入托管服务的插件改用 MCP 账号界面。 ### 注册账号 -插件的浏览器一半注入 `locale` 和 `cliAccounts`,注册字典,并在自身生命周期内注册账号: +插件的 Host 行在注册表运行时注册其 `CliAccountRuntime`,因此没有注册表的组合(如 headless profile)会跳过注册: ```ts ignore-check -export const inject = ['remote', 'locale', 'cliAccounts'] +import type {} from '@deepseek-ai/dsh-client-ui-cli-account' export function apply(ctx: Context): void { - ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'acme: dictionaries') - const t = ctx.locale.bind(NS) - ctx.effect(() => ctx.cliAccounts.register({ - packageName: '@acme/cli', locale: NS, - follow: signal => ctx.remote.acme.follow(signal), - cancel: id => ctx.remote.acme.cancel(id), - notices: { connect: () => t('notice.connected') }, - present: (snapshot, page) => presentAccount(snapshot, page, t), - }), 'acme: account') + const account = new AcmeAccount(options) + ctx.effect(() => () => account.dispose(), 'acme: account') + ctx.inject(['cliAccounts'], (scope) => { + scope.effect(() => scope.cliAccounts.register({ + packageName: '@acme/cli', source: account, copy, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Acme connected', zh: 'Acme 已连接' } }], + present: presentAccount, + }), 'acme: Plugins page account') + }) } ``` -`packageName` 是其插件包页面承载区块和标签的 npm 包。`locale` 指定插件的字典命名空间,它必须翻译每个[共用键](#shared-dictionary-keys);缺少任何一个,TypeScript 都会拒绝该命名空间。`follow` 和 `cancel` 调用插件的 Remote。`notices` 把操作类型映射为该操作成功时、在发起它的浏览器中报告的已翻译提示;未列出的类型不报告提示。插件把 `@deepseek-ai/dsh-client-ui-cli-account` 列入 `dsh.client.inject`,并用 `import type` 导入其类型。返回的销毁函数会移除这些界面并关闭该账号的 Host 流。如果注册的包已被注册,调用会抛出异常,且不留下任何界面。 +`packageName` 是其插件包页面承载区块和标签的 npm 包;同一个包再次注册会抛出异常。`source` 是账号,由 `CliAccountRuntime` 实现。`operations` 列出页面按钮可以启动的操作类型,每项可带该操作成功时在发起它的浏览器中报告的文本;注册表拒绝其他类型。`copy` 包含区块标题、区块下方的提示,以及开启引导的标题、正文和连接按钮文案。插件用 `import type` 导入注册表的类型。返回的销毁函数会把账号从所有页面撤下。 ### 展示区块 -`present(snapshot, page)` 在界面渲染时运行,返回 `CliAccountDisplay`:阶段、可选的状态文案、按钮、说明、附加行和失败信息,其中所有文案都已翻译。它只读取快照,因此通过 `ctx.locale.bind` 翻译时会跟随语言切换。按钮回调使用 `page`:`start(call)` 一次只运行一个 Remote 启动调用,`cancel`、`openAuthorization` 和 `retry` 作用于被跟随的操作和 Host 流。快照包含 Host 视图、流是否在推送或已停止、是否有页面操作未完成,以及最新提示。 +`present(view)` 把账号视图映射为 `CliAccountDisplay`:阶段、状态行、可选的标题旁标签、按钮、开启引导中“连接”启动的操作、说明、附加行,以及带不翻译诊断项的失败信息。注册表在每次变化时为每条流调用它,因此它只做视图映射。所有文案都是 `LocalizedText`,由各浏览器按当前语言解析。按钮携带一个命令:`start` 启动某个已注册的操作类型,`cancel` 取消进行中的操作(处于不可取消的阶段时 Host 会忽略),`open` 重新打开其授权链接。带 `confirm` 的按钮会先询问,用户确认后才执行。 | 界面 | 行为 | |---|---| -| 区块 | 标题、状态、按钮、说明、附加行、失败和提示;状态默认取该阶段的 `status.*` 文案,`connecting` 显示为检查中。页面操作未完成或 Host 流中断时按钮禁用,但在已停止时保持可用,以便重试重新打开流。带 `confirm` 的按钮会先询问,用户确认后才执行。失败时先显示插件的恢复建议,再显示分类后的命令、退出码和白名单字段 | -| 标题旁标签 | 只在已启用插件包的页面或其某一行的页面上、并且阶段确定后显示 | -| 开启引导 | 开启插件包后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并执行区块中第一个不需要确认的主要按钮。阶段确定为其他状态后自行关闭 | -| 提示 | 在插件面板生命周期之外报告最新结果:插件的成功文案,或带警告图标的共用失败文案 | +| 区块 | 标题、状态、按钮、说明、附加行、失败信息和提示。本浏览器发起的操作未完成,或 Host 流中断时,按钮不可用。失败时先显示插件的文案,再显示其诊断项 | +| 标题旁标签 | 显示 display 的 `badge`,只出现在已启用插件包的页面或其某一行的页面上,且只在 display 带有标签时显示 | +| 开启引导 | 插件包开启后,阶段为 `disconnected` 时打开;“连接”会打开插件包页面,并在 display 给出 `connect` 时启动该操作。阶段确定为其他值后自动关闭 | +| 提示 | 本浏览器的最新结果,不受插件面板生命周期限制:操作成功的文本,或带警告图标的共用失败文案 | ### 跟随操作 -页面跟随其最近一次启动调用返回的操作,从调用返回起,直到流送达该操作的结果;每次发起启动都会先放下之前跟随的操作,因此启动被拒绝时不跟随任何操作,并只报告一次 `action-failed` 提示。有页面操作未完成时,点击会被忽略。被跟随的操作提供的每个链接只在新窗口中打开一次,且只打开 HTTPS 链接;后续操作提供同一链接时会再次打开。如果某个结果在流送达之前就被后续操作取代,则不报告任何提示。流永久失败时快照标记为已停止,`retry` 会重新打开一次,无论调用多少次。移除注册会关闭流;此后页面不再打开链接、不再报告提示,而 Host 持有的操作继续运行。 +每个浏览器在 Web 应用加载时打开一条流,Host 为每条新流检查每个没有在运行操作的账号;流打开期间注册的账号会立即检查。浏览器跟随其最近一次启动返回的操作,从返回时起,直到流推送该操作的结果;每次尝试启动都会先放弃之前跟随的操作,因此被拒绝的启动不会留下被跟随的操作,并只报告一次失败提示。操作未完成时的点击会被忽略。被跟随的操作提供的每个链接只在新窗口中打开一次,且只打开 HTTPS 链接。其他浏览器显示同样的区块,但不打开链接,也不报告提示。流永久失败时,区块显示账号服务未运行,并提供“重试”;无论按多少次,都只重新打开流一次。卸载浏览器一半会关闭流;Host 持有的操作继续运行。 - -### 共用字典键 +### 共用文案 -这些界面从插件的命名空间读取以下键:`section.title`、`hint`、`close`、`action.cancel`、`action.connect`、`activation.title`、`activation.body`、`activation.later`、`failure.details`(含 `{details}`)、`failure.exitCode`(含 `{code}`)、`notice.action-failed`、除 `checking` 外每个阶段的 `badge.`,以及除 `connecting` 外每个阶段的 `status.`。 +`cliAccount` 字典包含所有账号共用的文案:关闭、取消、重试、稍后、排障信息标签、失败提示,以及未运行时的状态、标签和说明。其余文案都来自插件。 ----- @@ -79,17 +78,23 @@ export function apply(ctx: Context): void { ## 理解实现
    -实现内部细节——点击展开 +实现细节——点击展开 -`register()` 为每个账号创建一个 `CliAccountConnection`。它镜像插件的 `follow` 流,保存 Host 视图、流是否在推送、是否有页面操作未完成,以及最新提示。一次注册会贡献以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`、id 为 `.account` 的 `plugins.detail.badge` 条目,以及 id 为 `.account-toast` 的 `shell.overlay` 提示。每个条目都声明插件的命名空间,因此渲染器会提供它的 `t`;四个条目注入同一个 face,共享同一份快照,并调用插件的展示函数。注册是本插件 fiber 上的一个 effect:初始化失败时会销毁已经添加的部分;无论插件的销毁函数和本插件的卸载哪个先发生,拆除时都会先移除插槽条目,再关闭流。 +Host 一半 `CliAccounts` 是一个 Remote 服务。`register()` 观察账号来源,每条 `watch` 流在每次变化后读取每个账号的条目,并合并在下一次读取前到达的变化:文案、`present(view)`、进行中的操作,以及带成功文本的最新结果。`start` 和 `cancel` 按包路由到该账号的来源。 + +浏览器一半挂载 `cliAccounts` Remote,并通过 `CliAccountsConnection` 打开一条 `watch` 流,为每个账号保存一个快照 store:Host 条目、流是否在推送或已停止、本浏览器发起的操作是否未完成,以及最新提示。对 Host 报告的每个账号,它注册以包名为键的 `plugins.bundle.config` 和 `plugins.bundle.activation`、id 为 `.account` 的 `plugins.detail.badge` 条目,以及 id 为 `.account-toast` 的 `shell.overlay` 提示,全部使用 `cliAccount` 命名空间并注入同一个 face。Host 撤下的账号会失去这四个条目;卸载时先撤下条目和流,再撤下 Remote。 | 文件 | 职责 | |---|---| -| [`src/client/index.ts`](src/client/index.ts) | `ctx.cliAccounts` 注册表与四个插槽注册 | -| [`src/client/types.ts`](src/client/types.ts) | 注册、展示、快照与字典类型 | -| [`src/client/connection.ts`](src/client/connection.ts) | Host 视图镜像、链接打开、提示与未完成操作保护 | -| [`src/client/components.tsx`](src/client/components.tsx) | 各个界面,以及从 face 读取数据的插槽条目 | -| [`src/index.ts`](src/index.ts) | 空的 Node 一半 | +| [`src/index.ts`](src/index.ts) | `ctx.cliAccounts` 注册表及其 Remote | +| [`src/client/index.ts`](src/client/index.ts) | 绑定生成的 Remote 的浏览器入口 | +| [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、字典,以及每个账号的插槽注册 | +| [`src/client/connection.ts`](src/client/connection.ts) | 流的镜像、链接打开、提示和未完成操作保护 | +| [`src/client/components.tsx`](src/client/components.tsx) | 各界面,以及读取 face 的插槽条目 | +| [`src/client/locales.ts`](src/client/locales.ts) | 共用字典 | +| [`src/client/types.ts`](src/client/types.ts) | 快照、提示和 face 类型 | + +注册、display 和条目类型位于 [`@deepseek-ai/dsh-cli-account/types`](../../connector/cli-account/src/types.ts)。
    @@ -98,28 +103,28 @@ export function apply(ctx: Context): void { ## 延伸阅读 -- [CLI 账号库](../../connector/cli-account/README.zh.md)——推送视图的 Host 一半。 -- [插件管理页面](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 -- [客户端包索引](../README.zh.md)——相邻的浏览器 UI 包。 +- [CLI 账号库](../../connector/cli-account/README.zh.md)——账号运行时和页面类型。 +- [插件管理页](../ui-plugin-manager/README.zh.md)——插件页及其插件包插槽。 +- [客户端包地图](../README.zh.md)——相邻的浏览器 UI 包。 ----- ## 模型体验 -无,因为账号界面是浏览器 UI,不增加任何模型输入。每个插件各自说明其账号启用的 CLI 和技能。 +无,注册表及其界面属于插件页 UI,不增加模型输入。各插件自行说明其账号启用的 CLI 和技能。 -#### KV 缓存影响 +#### KV Cache 影响 -无;注册或移除账号不会改变任何模型可见文本。 +无;注册或移除账号不改变任何模型可见文本。 ## 已知限制与后续工作 -- 六种显示阶段是固定的;插件要把其他账号状态映射到其中之一。 -- 共用字典键对所有插件都相同;插件不能改名。 -- 每个账号各自打开一条 Host 流。 +- 五个显示阶段固定不变;插件需把其他账号状态映射到其中之一。 +- Host 行加载失败的插件不显示账号区块;插件页仍会列出该插件包及其加载失败。 +- 每个加载 Web 应用的浏览器都会触发一次对所有空闲账号的检查。 - 无论是否安装了 CLI 应用插件,Web 与桌面端组合都会加载注册表。 @@ -128,6 +133,6 @@ export function apply(ctx: Context): void {
    维护者工作上下文——点击展开 -客户端测试用模拟的 Remote 流驱动 `CliAccountConnection`,用回显键名的翻译函数渲染各个界面,并在真实的插槽注册表上注册账号。 +Host 测试用假的账号来源驱动注册表。客户端测试用假的 Remote 流驱动 `CliAccountsConnection`,用中文字典渲染各界面,并在真实的插槽注册表和 locale 运行时上挂载浏览器一半。源码覆盖率排除 `src/client/index.ts`,因为它导入只存在于 `lib/` 中的生成 Remote。
    diff --git a/packages/client/ui-cli-account/package.json b/packages/client/ui-cli-account/package.json index 25d6607899..ef409bee23 100644 --- a/packages/client/ui-cli-account/package.json +++ b/packages/client/ui-cli-account/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-cli-account", - "description": "CLI account surfaces for CLI app plugins: the account section, title tag, activation prompt, and notices on the Plugins page, over each plugin's account Remote", + "description": "CLI account surfaces for CLI app plugins: the Host registry plugins register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", "version": "0.2.2-alpha.2", "publishConfig": { "access": "public" @@ -24,12 +24,21 @@ }, "./src/*": "./src/*", "./package.json": "./package.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + }, "./locale/*.json": "./locale/*.json" }, "dsh": { "client": { "inject": [ "@deepseek-ai/dsh-api-remotes", + "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-layout", "@deepseek-ai/dsh-client-ui-plugin-manager" ], @@ -41,6 +50,10 @@ "watch": "tsdown --watch" }, "license": "MIT", + "dependencies": { + "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "zod": "4.4.3" + }, "peerDependencies": { "@deepseek-ai/cordis": "workspace:~" }, @@ -57,7 +70,7 @@ "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", - "@deepseek-ai/dsh-typert-protocol": "workspace:*", + "@deepseek-ai/dsh-package-manifest": "workspace:*", "@testing-library/react": "^16.3.3", "react": "^18.2.0", "react-dom": "^18.2.0" @@ -66,6 +79,10 @@ "locale/*.json", "lib/index.js", "lib/client.js", - "lib/types/**/*.d.ts" + "lib/types/**/*.d.ts", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts" ] } diff --git a/packages/client/ui-cli-account/src/client/components.tsx b/packages/client/ui-cli-account/src/client/components.tsx index 0d304fb54f..f43e67e6e4 100644 --- a/packages/client/ui-cli-account/src/client/components.tsx +++ b/packages/client/ui-cli-account/src/client/components.tsx @@ -1,84 +1,99 @@ /** * The account surfaces of one registered CLI plugin: the section, title tag, activation prompt, confirmation, and notice, - * with the slot entries that read them from the registration's face. + * with the slot entries that read them from the account's face. */ import { useEffect, useState, type ReactNode } from 'react' import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives' import type { InjectFace, PropsRuntime, Translate } from '@deepseek-ai/dsh-client-ui-slots' import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type { CliAccountButton, CliAccountCommand, CliAccountFailure, CliAccountPhase } from '@deepseek-ai/dsh-cli-account/types' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import css from './CliAccount.module.css' -import type { - CliAccountAction, CliAccountConfirmation, CliAccountDisplay, CliAccountFace, CliAccountFailure, CliAccountKey, CliAccountNotice, - CliAccountPhase, -} from './types.ts' +import type { CliAccountKey } from './locales.ts' +import type { CliAccountFace, CliAccountNotice, CliAccountSnapshot } from './types.ts' type FaceProps = InjectFace & { t: Translate } +type Resolve = (text: LocalizedText) => string +/** The phase a surface shows: the Host's, or `stopped` once this browser's stream failed for good. */ +type ShownPhase = CliAccountPhase | 'stopped' -const TONE: Record = { +const TONE: Record = { checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', stopped: 'warning', } -const BADGE_TONE: Record, TagTone> = { - connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning', +const BADGE_TONE: Record = { + checking: 'outline', connecting: 'info', connected: 'success', disconnected: 'outline', unavailable: 'warning', stopped: 'warning', } -/** What the section shows about one plugin's account. */ -export interface CliAccountSectionProps extends CliAccountDisplay { +function shownPhase(snapshot: CliAccountSnapshot): ShownPhase { + return snapshot.stopped ? 'stopped' : snapshot.entry.display.phase +} + +/** What the section shows about one account in this browser. */ +export interface CliAccountSectionProps { readonly t: Translate - readonly packageName: string - /** Whether an action this page started has not answered. */ - readonly busy: boolean - /** Whether the Host stream is delivering; buttons stay enabled while stopped so retry can reopen it. */ - readonly linked: boolean + readonly resolveText: Resolve + readonly snapshot: CliAccountSnapshot + readonly onCommand: (command: CliAccountCommand) => void + readonly onRetry: () => void } function describe(t: Translate, failure: CliAccountFailure): string | undefined { - const command = failure.command - if (command === undefined) return undefined - const details = [ - command.command, - ...command.exitCode === null ? [] : [t('failure.exitCode', { code: String(command.exitCode) })], - ...(failure.details ?? []).filter(detail => detail !== undefined), - ].join(' · ') - return t('failure.details', { details }) + const details = failure.details ?? [] + return details.length === 0 ? undefined : t('failure.details', { details: details.join(' · ') }) } /** * The account section on a plugin's bundle page. - * @param props - the plugin's display, the page state, and the plugin's translator. - * @returns the title, status line, detail, rows, failure, hint, and the confirmation an action asked for. + * @param props - the account's snapshot, the command and retry callbacks, and the translators. + * @returns the title, status line, detail, rows, failure, hint, and the confirmation a button asked for. */ -export function CliAccountSection(props: CliAccountSectionProps): ReactNode { - const { t, packageName, phase, status, busy, linked, actions = [], detail, notes = [], failure } = props - const [confirming, setConfirming] = useState<{ readonly action: CliAccountAction; readonly confirm: CliAccountConfirmation }>() +export function CliAccountSection({ t, resolveText, snapshot, onCommand, onRetry }: CliAccountSectionProps): ReactNode { + const { entry, busy, linked, stopped } = snapshot + const [confirming, setConfirming] = useState() + const display = entry.display + const phase = shownPhase(snapshot) // Reopening a stopped stream is the one action that does not need the Host stream. - const disabled = busy || (!linked && phase !== 'stopped') - const button = (action: CliAccountAction): ReactNode => { - const { confirm } = action - const onClick = confirm === undefined ? action.onClick : () => { setConfirming({ action, confirm }) } - return + const disabled = busy || (!linked && !stopped) + const button = (item: CliAccountButton): ReactNode => { + const label = resolveText(item.label) + const onClick = item.confirm === undefined ? () => { onCommand(item.command) } : () => { setConfirming(item) } + return } + const failure = stopped ? undefined : display.failure const diagnostic = failure === undefined ? undefined : describe(t, failure) + const confirm = confirming?.confirm return ( -
    -

    {t('section.title')}

    +
    +

    {resolveText(entry.copy.title)}

    - {status ?? t(`status.${phase === 'connecting' ? 'checking' : phase}`)} -
    {actions.map(button)}
    -
    - {detail === undefined ? null :

    {detail}

    } - {notes.map(note => ( -
    - {note.text} - {note.action === undefined ? null :
    {button(note.action)}
    } + {stopped ? t('status.stopped') : resolveText(display.status)} +
    + {stopped + ? + : display.buttons.map(button)}
    - ))} - {failure === undefined ? null :

    {failure.text}{diagnostic === undefined ? null : <> {diagnostic}}

    } -

    {t('hint')}

    - {confirming === undefined ? null : ( - { setConfirming(undefined) }} onConfirm={confirming.action.onClick} /> +
    + {stopped + ?

    {t('detail.stopped')}

    + : display.detail === undefined ? null :

    {resolveText(display.detail)}

    } + {stopped ? null : display.notes.map((note) => { + const text = resolveText(note.text) + return ( +
    + {text} + {note.button === undefined ? null :
    {button(note.button)}
    } +
    + ) + })} + {failure === undefined ? null : ( +

    {resolveText(failure.text)}{diagnostic === undefined ? null : <> {diagnostic}}

    + )} +

    {resolveText(entry.copy.hint)}

    + {confirming === undefined || confirm === undefined ? null : ( + { setConfirming(undefined) }} onConfirm={() => { onCommand(confirming.command) }} /> )}
    ) @@ -89,58 +104,66 @@ export type CliAccountBadgeSubject = | { readonly kind: 'item' } | { readonly kind: 'bundle' | 'row'; readonly pkg: { readonly name: string; readonly enabled: boolean } } -/** The tag's subject and phase, with the plugin's translator. */ +/** The tag's subject, phase, and text. */ export interface CliAccountBadgeProps { - readonly t: Translate /** The `subject` of the `plugins.detail.badge` slot props. */ readonly subject: CliAccountBadgeSubject readonly packageName: string - readonly phase: CliAccountPhase + readonly phase: ShownPhase + /** The tag's text; absent while nothing is settled. */ + readonly text: string | undefined } /** * The account tag beside a plugin bundle's title. - * @param props - the open detail page's subject, the plugin's package, its phase, and its translator. - * @returns the tag once the phase settles on the page of the enabled plugin bundle or of one of its rows, or null. + * @param props - the open detail page's subject, the account's package, its phase, and the tag's text. + * @returns the tag on the page of the enabled plugin bundle or of one of its rows, or null. */ -export function CliAccountBadge({ t, subject, packageName, phase }: CliAccountBadgeProps): ReactNode { - if (subject.kind === 'item' || subject.pkg.name !== packageName || !subject.pkg.enabled || phase === 'checking') return null - return {t(`badge.${phase}`)} +export function CliAccountBadge({ subject, packageName, phase, text }: CliAccountBadgeProps): ReactNode { + if (text === undefined || subject.kind === 'item' || subject.pkg.name !== packageName || !subject.pkg.enabled) return null + return {text} } -/** The prompt's phase and callbacks, with the plugin's translator. */ +/** The prompt's phase, text, and callbacks. */ export interface CliAccountActivationProps { readonly t: Translate - readonly phase: CliAccountPhase + readonly phase: ShownPhase + readonly title: string + readonly body: string + /** The connect button's label. */ + readonly connect: string readonly onDismiss: () => void readonly onConnect: () => void } /** * Guidance after the user switches a plugin bundle on while its account is not connected. - * @param props - the phase, the dismiss and connect callbacks, and the plugin's translator. + * @param props - the phase, the plugin's text, the dismiss and connect callbacks, and the kit translator. * @returns a prompt shown while disconnected; it dismisses itself once the phase settles elsewhere. */ -export function CliAccountActivation({ t, phase, onDismiss, onConnect }: CliAccountActivationProps): ReactNode { +export function CliAccountActivation({ t, phase, title, body, connect, onDismiss, onConnect }: CliAccountActivationProps): ReactNode { const needed = phase === 'disconnected' useEffect(() => { if (phase !== 'checking' && !needed) onDismiss() }, [phase, needed, onDismiss]) return ( - - + }> -

    {t('activation.body')}

    +

    {body}

    ) } -/** The question, its callbacks, and the plugin's translator for the shared buttons. */ +/** A confirmation's text and callbacks, with the kit translator for the shared buttons. */ export interface CliAccountConfirmProps { readonly t: Translate - readonly confirmation: CliAccountConfirmation + readonly title: string + readonly body: string + /** The confirm button's label. */ + readonly label: string readonly onClose: () => void readonly onConfirm: () => void } @@ -150,81 +173,88 @@ export interface CliAccountConfirmProps { * @param props - the question and the close and confirm callbacks. * @returns a dialog that closes before it confirms. */ -export function CliAccountConfirm({ t, confirmation, onClose, onConfirm }: CliAccountConfirmProps): ReactNode { +export function CliAccountConfirm({ t, title, body, label, onClose, onConfirm }: CliAccountConfirmProps): ReactNode { return ( - - + }> -

    {confirmation.body}

    +

    {body}

    ) } -/** The latest notice, the plugin's success copy, and its dismissal. */ +/** The latest notice and its dismissal, with both translators. */ export interface CliAccountToastProps { readonly t: Translate - readonly notice: CliAccountNotice | undefined - readonly notices: Readonly string>>> + readonly resolveText: Resolve + readonly notice: CliAccountNotice | undefined readonly onDone: () => void } /** * Account outcomes reported outside the Plugins panel's lifetime. - * @param props - the latest notice, the plugin's success copy, its dismissal, and the plugin's translator. - * @returns the toast for the notice, or null when there is none or its operation has no copy. + * @param props - the latest notice, its dismissal, and the translators. + * @returns the toast for the notice, or null. */ -export function CliAccountToast({ t, notice, notices, onDone }: CliAccountToastProps): ReactNode { +export function CliAccountToast({ t, resolveText, notice, onDone }: CliAccountToastProps): ReactNode { if (notice === undefined) return null if (notice.kind === 'action-failed') { return } onDone={onDone} /> } - const text = notices[notice.operation] - return text === undefined ? null : + return } /** * The `plugins.bundle.config` entry. - * @param props - the registration's face and the plugin's translator. + * @param props - the account's face and the kit translator. * @returns the section for the current snapshot. */ -export function CliAccountSectionEntry({ useCliAccount, present, page, packageName, t }: FaceProps): ReactNode { +export function CliAccountSectionEntry({ useCliAccount, resolveText, run, retry, t }: FaceProps): ReactNode { const snapshot = useCliAccount(value => value) - return + return } /** * The `plugins.detail.badge` entry. - * @param props - the open detail page's subject, the registration's face, and the plugin's translator. - * @returns the tag for the registration's bundle, or null on any other page. + * @param props - the open detail page's subject, the account's face, and the kit translator. + * @returns the tag for the account's bundle, or null on any other page. */ export function CliAccountBadgeEntry(props: FaceProps & PropsRuntime<'plugins.detail.badge'>): ReactNode { - const { useCliAccount, present, page, packageName, subject, t } = props - const phase = useCliAccount(value => present(value, page).phase) - return + const { useCliAccount, resolveText, packageName, subject, t } = props + const phase = useCliAccount(shownPhase) + const badge = useCliAccount(value => value.entry.display.badge) + const text = phase === 'stopped' ? t('badge.stopped') : badge === undefined ? undefined : resolveText(badge) + return } /** - * The `plugins.bundle.activation` entry; Connect opens the bundle page and runs the section's first primary action - * that asks no confirmation. - * @param props - activation callbacks, the registration's face, and the plugin's translator. + * The `plugins.bundle.activation` entry; Connect opens the bundle page and starts the display's `connect` command. + * @param props - activation callbacks, the account's face, and the kit translator. * @returns the prompt for the current snapshot. */ export function CliAccountActivationEntry(props: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode { - const { useCliAccount, present, page, onDismiss, onOpenDetails, t } = props - const display = present(useCliAccount(value => value), page) - const connect = display.actions?.find(action => action.variant === 'primary' && action.confirm === undefined) - const onConnect = (): void => { onOpenDetails(); connect?.onClick() } - return + const { useCliAccount, resolveText, run, onDismiss, onOpenDetails, t } = props + const snapshot = useCliAccount(value => value) + const { activation } = snapshot.entry.copy + const { connect } = snapshot.entry.display + const onConnect = (): void => { + onOpenDetails() + if (connect !== undefined) run(connect) + } + return ( + + ) } /** * The `shell.overlay` entry. - * @param props - the registration's face and the plugin's translator. + * @param props - the account's face and the kit translator. * @returns the toast for the latest notice, or null. */ -export function CliAccountToastEntry({ useCliAccount, notices, dismissNotice, t }: FaceProps): ReactNode { +export function CliAccountToastEntry({ useCliAccount, resolveText, dismissNotice, t }: FaceProps): ReactNode { const notice = useCliAccount(value => value.notice) - return + return } diff --git a/packages/client/ui-cli-account/src/client/connection.ts b/packages/client/ui-cli-account/src/client/connection.ts index 2444e220ea..7698be63e3 100644 --- a/packages/client/ui-cli-account/src/client/connection.ts +++ b/packages/client/ui-cli-account/src/client/connection.ts @@ -1,16 +1,18 @@ -/** Browser mirror of one CLI plugin's Host account view and the Plugins page's account actions. */ +/** Browser mirror of the registered CLI accounts and the Plugins page's account actions. */ import type { Context } from '@deepseek-ai/cordis' import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client' -import type { CliOperationId } from '@deepseek-ai/dsh-cli-account/types' +import type { CliAccountCommand, CliAccountEntry, CliAccountsView, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import type { - AnyCliAccountView, CliAccountNotice, CliAccountPage, CliAccountRegistration, CliAccountSnapshot, CliOperationKindOf, -} from './types.ts' +import type { CliAccountFace, CliAccountNotice, CliAccountSnapshot } from './types.ts' -/** The registration's Remote operations and notices, with the Host stream's diagnostic name. */ -export type CliAccountConnectionOptions = - Pick, 'follow' | 'cancel' | 'notices'> & { readonly name: string } +/** The `cliAccounts` Remote methods the mirror uses. */ +export interface CliAccountsRemote { + watch(signal: AbortSignal): AsyncIterable + start(packageName: string, operation: string): Promise> + cancel(packageName: string, id: CliOperationId): Promise> +} function openAuthorizationPage(url: string | undefined): void { if (url !== undefined && URL.canParse(url) && new URL(url).protocol === 'https:') window.open(url, '_blank', 'noopener,noreferrer') @@ -22,77 +24,43 @@ async function settle(call: Promise>): Promise { return result.value } -/** One Host subscription per registered account, shared by every surface of that account on the Plugins page. */ -export class CliAccountConnection { - /** The page's whole view, published after each stream item or page action settles. */ - readonly state: SnapshotStore> = createSnapshotStore>({ - view: undefined, linked: false, stopped: false, busy: false, notice: undefined, - }) +/** One Host subscription per browser, shared by every account surface on the Plugins page. */ +export class CliAccountsConnection { + /** Each registered account's snapshot source by bundle package, republished when the Host adds or removes an account. */ + readonly accounts: SnapshotStore>> = + createSnapshotStore>>(new Map()) + private readonly stores = new Map>() /** - * The operation the page's latest start returned, with the links already opened for it; only its links open a window - * here. It lasts until the stream delivers its result; each start attempt drops it first. + * The operation each account's latest start in this browser returned, with the links already opened for it; only its + * links open a window here. It lasts until the stream delivers its result; each start attempt drops it first. */ - private started: { readonly id: CliOperationId; readonly opened: Set } | undefined + private readonly started = new Map }>() + private stopped = false private seq = 0 private disposed = false - private stream!: RemoteStream + private stream!: RemoteStream private observing!: Promise - /** The page actions, bound so a plugin's buttons can call them directly. */ - readonly page: CliAccountPage = { - start: (call) => { this.start(call) }, - cancel: () => { this.cancel() }, - openAuthorization: () => { this.openAuthorization() }, - retry: () => { this.retry() }, - } - - /** Clear the current notice; bound for the notice's dismissal. */ - readonly dismissNotice = (): void => { this.patch({ notice: undefined }) } - /** * @param ctx - the browser context carrying the Remote client. - * @param options - the plugin's Remote operations and success notices, and the stream's diagnostic name. + * @param remote - the `cliAccounts` Remote. */ - constructor(private readonly ctx: Context, private readonly options: CliAccountConnectionOptions) { + constructor(private readonly ctx: Context, private readonly remote: CliAccountsRemote) { this.subscribe() } /** - * Start an operation through the plugin's Remote; a click while another action is pending is ignored. - * The page then follows the returned operation in place of any earlier one; a rejected start leaves it following - * none and reports the `action-failed` notice. - * @param call - the plugin's Remote start method. + * Bind one account's page actions. + * @param packageName - the account's bundle package. + * @returns the actions a surface entry injects. */ - start(call: () => Promise>): void { - void this.run(async () => { - this.started = undefined - const id = await settle(call()) - if (this.disposed) return - this.started = { id, opened: new Set() } - const current = this.state.getSnapshot().view - if (current !== undefined) this.follow(current) - }) - } - - /** Cancel the current operation when the Host marks it cancellable. */ - cancel(): void { - const operation = this.state.getSnapshot().view?.operation - if (operation === undefined || !operation.cancellable) return - void this.run(async () => { await settle(this.options.cancel(operation.id)) }) - } - - /** Open the current operation's authorization link again, over HTTPS only. */ - openAuthorization(): void { - openAuthorizationPage(this.state.getSnapshot().view?.operation?.authorizationUrl) - } - - /** Reopen the Host stream after it stopped; ignored while it runs, while a reopen is pending, or after disposal. */ - retry(): void { - if (this.disposed || !this.state.getSnapshot().stopped) return - // Clearing `stopped` before the reopen awaits claims it, so a second retry finds nothing to reopen. - this.patch({ view: undefined, stopped: false }) - void this.reopen() + actions(packageName: string): Pick { + return { + run: (command) => { this.run(packageName, command) }, + retry: () => { this.retry() }, + dismissNotice: () => { this.patch(packageName, { notice: undefined }) }, + } } /** @@ -106,27 +74,62 @@ export class CliAccountConnection { await this.observing } + private run(packageName: string, command: CliAccountCommand): void { + const entry = this.stores.get(packageName)?.getSnapshot().entry + if (entry === undefined) return + switch (command.kind) { + case 'start': + void this.act(packageName, async () => { + this.started.delete(packageName) + const id = await settle(this.remote.start(packageName, command.operation)) + if (this.disposed) return + this.started.set(packageName, { id, opened: new Set() }) + const current = this.stores.get(packageName)?.getSnapshot().entry + if (current !== undefined) this.follow(current) + }) + return + case 'cancel': { + const operation = entry.operation + if (operation === undefined) return + void this.act(packageName, async () => { await settle(this.remote.cancel(packageName, operation.id)) }) + return + } + case 'open': openAuthorizationPage(entry.operation?.authorizationUrl); return + } + } + + /** Reopen the Host stream after it stopped; ignored while it runs, while a reopen is pending, or after disposal. */ + private retry(): void { + if (this.disposed || !this.stopped) return + // Clearing `stopped` before the reopen awaits claims it, so a second retry finds nothing to reopen. + this.stopped = false + for (const packageName of this.stores.keys()) this.patch(packageName, { stopped: false }) + void this.reopen() + } + private subscribe(): void { - this.stream = this.ctx.remote.$stream({ - name: this.options.name, open: this.options.follow, - ended: () => new Error(`${this.options.name} stream ended`), - carrierFailed: () => { this.patch({ linked: false }) }, + this.stream = this.ctx.remote.$stream({ + name: 'CLI accounts', open: signal => this.remote.watch(signal), + ended: () => new Error('CLI accounts stream ended'), + carrierFailed: () => { this.setLinked(false) }, }) this.observing = this.observe(this.stream) } - private async observe(stream: RemoteStream): Promise { + private async observe(stream: RemoteStream): Promise { try { for await (const item of stream) { // An item the stream yielded just before disposal must not reach the disposed page. if (this.disposed) return - this.patch({ view: item.value, linked: true }) - this.follow(item.value) + this.show(item.value.accounts) item.accept() } } catch { - // A terminal failure, such as a Host without the plugin's service, ends the stream; a disposed page shows nothing. - if (!this.disposed) this.patch({ linked: false, stopped: true }) + // A terminal failure, such as a Host without the registry, ends the stream; a disposed page shows nothing. + if (this.disposed) return + this.stopped = true + this.setLinked(false) + for (const packageName of this.stores.keys()) this.patch(packageName, { stopped: true }) } } @@ -136,47 +139,73 @@ export class CliAccountConnection { if (!this.disposed) this.subscribe() } - /** Open each new link of the followed operation once, and report how it ended when the view carries its result. */ - private follow(view: View): void { - const started = this.started + private show(entries: readonly CliAccountEntry[]): void { + const names = new Set(entries.map(entry => entry.packageName)) + let changed = false + for (const packageName of [...this.stores.keys()]) { + if (names.has(packageName)) continue + this.stores.delete(packageName) + this.started.delete(packageName) + changed = true + } + for (const entry of entries) { + const store = this.stores.get(entry.packageName) + if (store === undefined) { + this.stores.set(entry.packageName, createSnapshotStore({ + entry, linked: true, stopped: false, busy: false, notice: undefined, + })) + changed = true + } else { + store.set({ ...store.getSnapshot(), entry, linked: true, stopped: false }) + } + this.follow(entry) + } + if (changed) this.accounts.set(new Map(this.stores)) + } + + /** Open each new link of the account's followed operation once, and show the Host's notice once the entry carries its result. */ + private follow(entry: CliAccountEntry): void { + const started = this.started.get(entry.packageName) if (started === undefined) return - const url = view.operation?.id === started.id ? view.operation.authorizationUrl : undefined + const url = entry.operation?.id === started.id ? entry.operation.authorizationUrl : undefined if (url !== undefined && !started.opened.has(url)) { started.opened.add(url) openAuthorizationPage(url) } - const result = view.result + const result = entry.result if (result?.id !== started.id) return - this.started = undefined - const operation = result.kind as CliOperationKindOf - if (result.outcome === 'succeeded' && this.options.notices[operation] !== undefined) { - this.notify({ kind: 'succeeded', operation }) - } + this.started.delete(entry.packageName) + if (result.notice !== undefined) this.notify(entry.packageName, { kind: 'succeeded', text: result.notice }) } - private async run(operation: () => Promise): Promise { - if (this.state.getSnapshot().busy) return - this.patch({ busy: true }) + private async act(packageName: string, operation: () => Promise): Promise { + if (this.stores.get(packageName)?.getSnapshot().busy !== false) return + this.patch(packageName, { busy: true }) try { await operation() } catch { // The Host keeps the diagnostic; the page reports one retryable outcome. - this.notify({ kind: 'action-failed' }) + this.notify(packageName, { kind: 'action-failed' }) } finally { - this.patch({ busy: false }) + this.patch(packageName, { busy: false }) } } - private patch(change: Partial>): void { - this.state.set({ ...this.state.getSnapshot(), ...change }) + private setLinked(linked: boolean): void { + for (const packageName of this.stores.keys()) this.patch(packageName, { linked }) + } + + private patch(packageName: string, change: Partial): void { + const store = this.stores.get(packageName) + if (store !== undefined) store.set({ ...store.getSnapshot(), ...change }) } private notify( - notice: { readonly kind: 'succeeded'; readonly operation: CliOperationKindOf } | { readonly kind: 'action-failed' }, + packageName: string, notice: { readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly kind: 'action-failed' }, ): void { if (this.disposed) return this.seq += 1 - const next: CliAccountNotice> = { ...notice, seq: this.seq } - this.patch({ notice: next }) + const next: CliAccountNotice = { ...notice, seq: this.seq } + this.patch(packageName, { notice: next }) } } diff --git a/packages/client/ui-cli-account/src/client/index.ts b/packages/client/ui-cli-account/src/client/index.ts index c89e1492da..00d484c972 100644 --- a/packages/client/ui-cli-account/src/client/index.ts +++ b/packages/client/ui-cli-account/src/client/index.ts @@ -1,62 +1,21 @@ /** - * CLI account surfaces for CLI app plugins, browser half. `ctx.cliAccounts` shows a plugin's account section, title tag, - * activation prompt, and notices on its bundle's Plugins page, following the plugin's Host account Remote. + * CLI account surfaces, browser half: follows the accounts CLI app plugins register on the Host and shows each one's + * section, title tag, activation prompt, and notices on its bundle's Plugins page. The surfaces read the shared copy from + * this package's dictionary and each plugin's text from the Host. */ import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-api-remotes/client' -import type {} from '@deepseek-ai/dsh-client-ui-layout/client' -import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' -import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' -import { CliAccountActivationEntry, CliAccountBadgeEntry, CliAccountSectionEntry, CliAccountToastEntry } from './components.tsx' -import { CliAccountConnection } from './connection.ts' -import type { AnyCliAccountView, CliAccountFace, CliAccountRegistration, CliAccounts } from './types.ts' +import cliAccountsRemote from '@deepseek-ai/dsh-client-ui-cli-account/remote' +import { mountCliAccounts } from './mount.ts' -export type { - AnyCliAccountView, CliAccountAction, CliAccountConfirmation, CliAccountDisplay, CliAccountFailure, CliAccountKey, - CliAccountNamespace, CliAccountNote, CliAccountNotice, CliAccountPage, CliAccountPhase, CliAccountRegistration, CliAccounts, - CliAccountSnapshot, CliOperationKindOf, -} from './types.ts' - -declare module '@deepseek-ai/cordis' { - interface Context { - /** CLI app plugin account surfaces on the Plugins page. */ - cliAccounts: CliAccounts - } -} - -/** Services the Host stream and the slot registrations need. */ -export const inject = ['remote', 'slots'] - -function register(ctx: Context, account: CliAccountRegistration): () => void { - const { packageName, locale } = account - const dispose = ctx.effect(function* () { - const connection = new CliAccountConnection(ctx, { ...account, name: `${packageName} account` }) - yield async () => { await connection.dispose() } - const face: CliAccountFace = { - hooks: { cliAccount: connection.state }, - packageName, page: connection.page, present: account.present, notices: account.notices, dismissNotice: connection.dismissNotice, - } - yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ - name: 'plugins.bundle.config', key: packageName, locale, inject: () => face, - }, CliAccountSectionEntry)) - yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ - name: 'plugins.bundle.activation', key: packageName, locale, inject: () => face, - }, CliAccountActivationEntry)) - yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ - name: 'plugins.detail.badge', id: `${packageName}.account`, locale, inject: () => face, - }, CliAccountBadgeEntry)) - yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ - name: 'shell.overlay', id: `${packageName}.account-toast`, locale, inject: () => face, - }, CliAccountToastEntry)) - }, `cliAccounts.register(${packageName})`) - return () => void dispose() -} +export { inject } from './mount.ts' +export type { CliAccountKey } from './locales.ts' +export type { CliAccountFace, CliAccountNotice, CliAccountSnapshot } from './types.ts' /** - * Provide the account registry; each registration lives until its disposer runs or this plugin unloads. + * Show the registered CLI accounts on the Plugins page. * @param ctx - the browser plugin context. + * @returns a disposer that withdraws the surfaces and the stream, then the Remote. */ -export function apply(ctx: Context): void { - const accounts: CliAccounts = { register: account => register(ctx, account) } - ctx.provide('cliAccounts', accounts) +export async function apply(ctx: Context): Promise<() => Promise> { + return mountCliAccounts(ctx, cliAccountsRemote) } diff --git a/packages/client/ui-cli-account/src/client/locales.ts b/packages/client/ui-cli-account/src/client/locales.ts new file mode 100644 index 0000000000..abd59a0314 --- /dev/null +++ b/packages/client/ui-cli-account/src/client/locales.ts @@ -0,0 +1,118 @@ +/** Locale-owned copy the CLI account surfaces share across plugins; each plugin's own text arrives from the Host. */ +import type {} from '@deepseek-ai/dsh-client-ui-slots' + +/** Dictionary namespace of the shared account copy. */ +export const NS = 'cliAccount' + +/** Chinese dictionary and key source. */ +export const zh = { + close: '关闭', + 'action.cancel': '取消', + 'action.retry': '重试', + 'activation.later': '稍后', + 'failure.details': '排障信息:{details}', + 'notice.action-failed': '操作未完成,请重试', + 'badge.stopped': '未运行', + 'status.stopped': '账号服务未运行', + 'detail.stopped': '暂时无法读取账号状态,可以重试。', +} + +/** Every key the shared account surfaces translate. */ +export type CliAccountKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + close: 'Close', + 'action.cancel': 'Cancel', + 'action.retry': 'Retry', + 'activation.later': 'Later', + 'failure.details': 'Diagnostic: {details}', + 'notice.action-failed': 'The action did not finish. Try again.', + 'badge.stopped': 'Not running', + 'status.stopped': 'Account service not running', + 'detail.stopped': 'The account status cannot be read right now. Retry to reconnect.', +} + +/** Japanese dictionary. */ +export const ja: Record = { + close: '閉じる', + 'action.cancel': 'キャンセル', + 'action.retry': '再試行', + 'activation.later': '後で', + 'failure.details': '診断情報:{details}', + 'notice.action-failed': '操作が完了しませんでした。もう一度お試しください。', + 'badge.stopped': '未稼働', + 'status.stopped': 'アカウントサービスが稼働していません', + 'detail.stopped': 'アカウントの状態を現在読み取れません。再試行して再接続してください。', +} + +/** Spanish dictionary. */ +export const es: Record = { + close: 'Cerrar', + 'action.cancel': 'Cancelar', + 'action.retry': 'Reintentar', + 'activation.later': 'Más tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'La acción no se completó. Inténtelo de nuevo.', + 'badge.stopped': 'No está en ejecución', + 'status.stopped': 'El servicio de cuentas no está en ejecución', + 'detail.stopped': 'No se puede leer el estado de la cuenta en este momento. Reintente para volver a conectar.', +} + +/** French dictionary. */ +export const fr: Record = { + close: 'Fermer', + 'action.cancel': 'Annuler', + 'action.retry': 'Réessayer', + 'activation.later': 'Plus tard', + 'failure.details': 'Diagnostic : {details}', + 'notice.action-failed': 'L’action n’a pas abouti. Réessayez.', + 'badge.stopped': 'Ne fonctionne pas', + 'status.stopped': 'Le service de comptes ne fonctionne pas', + 'detail.stopped': 'L’état du compte ne peut pas être lu pour le moment. Réessayez pour vous reconnecter.', +} + +/** German dictionary. */ +export const de: Record = { + close: 'Schließen', + 'action.cancel': 'Abbrechen', + 'action.retry': 'Erneut versuchen', + 'activation.later': 'Später', + 'failure.details': 'Diagnose: {details}', + 'notice.action-failed': 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', + 'badge.stopped': 'Läuft nicht', + 'status.stopped': 'Kontodienst läuft nicht', + 'detail.stopped': 'Der Kontostatus kann gerade nicht gelesen werden. Versuchen Sie es erneut, um die Verbindung wiederherzustellen.', +} + +/** Russian dictionary. */ +export const ru: Record = { + close: 'Закрыть', + 'action.cancel': 'Отмена', + 'action.retry': 'Повторить', + 'activation.later': 'Позже', + 'failure.details': 'Диагностика: {details}', + 'notice.action-failed': 'Действие не завершено. Повторите попытку.', + 'badge.stopped': 'Не работает', + 'status.stopped': 'Служба аккаунтов не работает', + 'detail.stopped': 'Сейчас не удаётся прочитать состояние аккаунта. Повторите попытку, чтобы переподключиться.', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + close: 'Fechar', + 'action.cancel': 'Cancelar', + 'action.retry': 'Tentar novamente', + 'activation.later': 'Mais tarde', + 'failure.details': 'Diagnóstico: {details}', + 'notice.action-failed': 'A ação não foi concluída. Tente novamente.', + 'badge.stopped': 'Não está em execução', + 'status.stopped': 'O serviço de contas não está em execução', + 'detail.stopped': 'Não é possível ler o estado da conta agora. Tente novamente para reconectar.', +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface LocaleNamespaceMap { + cliAccount: CliAccountKey + } +} diff --git a/packages/client/ui-cli-account/src/client/mount.ts b/packages/client/ui-cli-account/src/client/mount.ts new file mode 100644 index 0000000000..ace3ad7af8 --- /dev/null +++ b/packages/client/ui-cli-account/src/client/mount.ts @@ -0,0 +1,77 @@ +/** Mount the `cliAccounts` Remote and show the surfaces of each account the Host registers, for one plugin lifetime. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-layout/client' +import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type {} from '@deepseek-ai/dsh-client-ui-cli-account/remote' +import type { TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' +import { CliAccountActivationEntry, CliAccountBadgeEntry, CliAccountSectionEntry, CliAccountToastEntry } from './components.tsx' +import { CliAccountsConnection } from './connection.ts' +import { de, en, es, fr, ja, NS, pt, ru, zh } from './locales.ts' +import type { CliAccountFace, CliAccountSnapshot } from './types.ts' + +/** Services the Remote mount and the slot registrations need. */ +export const inject = ['remote', 'slots', 'locale'] + +function registerAccount( + ctx: Context, connection: CliAccountsConnection, packageName: string, store: SnapshotStore, +): () => void { + const face: CliAccountFace = { + hooks: { cliAccount: store }, packageName, resolveText: text => ctx.locale.resolveText(text), ...connection.actions(packageName), + } + const dispose = ctx.effect(function* () { + yield ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({ + name: 'plugins.bundle.config', key: packageName, locale: NS, inject: () => face, + }, CliAccountSectionEntry)) + yield ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({ + name: 'plugins.bundle.activation', key: packageName, locale: NS, inject: () => face, + }, CliAccountActivationEntry)) + yield ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({ + name: 'plugins.detail.badge', id: `${packageName}.account`, locale: NS, inject: () => face, + }, CliAccountBadgeEntry)) + yield ctx.slots.inject('shell.overlay', () => ctx.slots.register({ + name: 'shell.overlay', id: `${packageName}.account-toast`, locale: NS, inject: () => face, + }, CliAccountToastEntry)) + }, `cliAccounts: ${packageName}`) + return () => void dispose() +} + +function showAccounts(ctx: Context): void { + ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'cli-account: dictionaries') + const connection = new CliAccountsConnection(ctx, ctx.remote.cliAccounts) + ctx.effect(() => async () => { await connection.dispose() }, 'cli-account: connection') + ctx.effect(() => { + const shown = new Map void>() + const sync = (): void => { + const accounts = connection.accounts.getSnapshot() + for (const [name, withdraw] of shown) { + if (accounts.has(name)) continue + withdraw() + shown.delete(name) + } + for (const [name, store] of accounts) if (!shown.has(name)) shown.set(name, registerAccount(ctx, connection, name, store)) + } + sync() + const stop = connection.accounts.subscribe(sync) + return () => { + stop() + for (const withdraw of shown.values()) withdraw() + } + }, 'cli-account: surfaces') +} + +/** + * Mount the `cliAccounts` Remote, then show the registered accounts for the same plugin lifetime. + * @param ctx - the browser plugin context. + * @param contribution - the generated `cliAccounts` Remote definitions the built entry supplies. + * @returns a disposer that withdraws the surfaces and the stream before the Remote. + */ +export async function mountCliAccounts(ctx: Context, contribution: TypertRemoteContribution): Promise<() => Promise> { + const unmount = await ctx.remote.$mount(contribution) + const ui = ctx.inject(['remote.cliAccounts', 'slots', 'locale'], showAccounts) + try { await ui } catch (error) { await ui.dispose(); await unmount(); throw error } + return async () => { await ui.dispose(); await unmount() } +} diff --git a/packages/client/ui-cli-account/src/client/types.ts b/packages/client/ui-cli-account/src/client/types.ts index 587a352d08..84d88e58a9 100644 --- a/packages/client/ui-cli-account/src/client/types.ts +++ b/packages/client/ui-cli-account/src/client/types.ts @@ -1,158 +1,34 @@ -/** Registration, display, and dictionary types a CLI app plugin uses to show its account on the Plugins page. */ -import type { CliAccountView, CliCommandFailure, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' -import type { HostObservable, LocaleNamespaceMap } from '@deepseek-ai/dsh-client-ui-slots' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' - -/** Any plugin's Host account view; each plugin supplies its own account, operation, and failure types. */ -export type AnyCliAccountView = CliAccountView - -/** The operation kinds a plugin's view reports results for. */ -export type CliOperationKindOf = NonNullable['kind'] - -/** What the page shows about a plugin's account; each plugin maps its own account states onto these phases. */ -export type CliAccountPhase = 'checking' | 'connecting' | 'connected' | 'disconnected' | 'unavailable' | 'stopped' - -/** Dictionary keys the shared surfaces read from every CLI plugin's namespace. */ -export type CliAccountKey = - | 'section.title' | 'hint' | 'close' | 'action.cancel' | 'action.connect' - | 'activation.title' | 'activation.body' | 'activation.later' - | 'failure.details' | 'failure.exitCode' | 'notice.action-failed' - | `badge.${Exclude}` - | `status.${Exclude}` - -type LocaleNamespace = Extract - -/** Locale namespaces whose dictionary translates every {@link CliAccountKey}. */ -export type CliAccountNamespace = { - [N in LocaleNamespace]: [CliAccountKey] extends [LocaleNamespaceMap[N]] ? N : never -}[LocaleNamespace] +/** Browser-side state and face of the accounts the Plugins page shows. */ +import type { CliAccountCommand, CliAccountEntry } from '@deepseek-ai/dsh-cli-account/types' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' /** A transient outcome the page reports outside its own lifetime; `seq` distinguishes repeats. */ -export type CliAccountNotice = - | { readonly seq: number; readonly kind: 'succeeded'; readonly operation: Kind } +export type CliAccountNotice = + | { readonly seq: number; readonly kind: 'succeeded'; readonly text: LocalizedText } | { readonly seq: number; readonly kind: 'action-failed' } -/** The page's whole view: the Host's account view plus this browser's stream state, pending action, and notice. */ -export interface CliAccountSnapshot { - /** The Host's view; undefined until the stream reports one. */ - readonly view: View | undefined +/** One account as this browser shows it: the Host's entry plus the stream state, pending action, and notice. */ +export interface CliAccountSnapshot { + readonly entry: CliAccountEntry /** Whether the Host stream is delivering. */ readonly linked: boolean - /** Whether the Host stream failed for good, as when the plugin's Host component is not running; `retry` reopens it. */ + /** Whether the Host stream failed for good; `retry` reopens it. */ readonly stopped: boolean - /** Whether an action this page started has not answered. */ + /** Whether an action this browser started for the account has not answered. */ readonly busy: boolean - readonly notice: CliAccountNotice> | undefined + readonly notice: CliAccountNotice | undefined } -/** The page actions a plugin's buttons call. */ -export interface CliAccountPage { - /** - * Start an operation through the plugin's Remote; a click while another action is pending is ignored. The page then - * follows the returned operation in place of any earlier one; a rejected start leaves it following none and reports - * the `action-failed` notice. - */ - readonly start: (call: () => Promise>) => void - /** Cancel the current operation when the Host marks it cancellable. */ - readonly cancel: () => void - /** Open the current operation's authorization link again, over HTTPS only. */ - readonly openAuthorization: () => void - /** Reopen the Host stream after it stopped; ignored while it runs or while a reopen is pending. */ - readonly retry: () => void -} - -/** The question an action asks before it runs. */ -export interface CliAccountConfirmation { - readonly title: string - readonly body: string - /** The confirm button's label. */ - readonly label: string -} - -/** One button in the section; the section disables it while an action is pending or the Host stream is down. */ -export interface CliAccountAction { - readonly label: string - readonly onClick: () => void - /** Defaults to an outline button. */ - readonly variant?: 'primary' | 'ghost' - /** Ask first, for an action that changes the account outside DSH, such as signing out of a CLI the terminal shares. */ - readonly confirm?: CliAccountConfirmation -} - -/** One extra row under the status line, such as the linked app, with an optional button. */ -export interface CliAccountNote { - readonly text: string - readonly action?: CliAccountAction -} - -/** A failed operation as the section reports it. */ -export interface CliAccountFailure { - /** The plugin's recovery guidance. */ - readonly text: string - /** The Host's classified command, shown as a diagnostic after the guidance. */ - readonly command?: CliCommandFailure | undefined - /** The plugin's allowlisted classification fields, appended in order; undefined entries are skipped. */ - readonly details?: readonly (string | undefined)[] -} - -/** What the section shows; the plugin translates every string. */ -export interface CliAccountDisplay { - readonly phase: CliAccountPhase - /** The status label; defaults to the `status.*` copy for the phase, with `connecting` labelled as checking. */ - readonly status?: string | undefined - /** The first `primary` action that asks no confirmation also answers Connect in the activation prompt. */ - readonly actions?: readonly CliAccountAction[] - readonly detail?: string | undefined - readonly notes?: readonly CliAccountNote[] - readonly failure?: CliAccountFailure | undefined -} - -/** One CLI app plugin's account: its bundle page, dictionary, Remote operations, and presentation. */ -export interface CliAccountRegistration { - /** npm package whose bundle page carries the section and tag. */ - readonly packageName: string - /** The plugin's dictionary namespace, which supplies the {@link CliAccountKey} copy. */ - readonly locale: CliAccountNamespace - /** Open one generation of the plugin's `follow` stream. */ - readonly follow: (signal: AbortSignal) => AsyncIterable - /** Cancel one operation through the plugin's Remote. */ - readonly cancel: (id: CliOperationId) => Promise> - /** - * The translated notice each operation kind reports when an operation this browser started succeeds; unlisted kinds - * report none. - */ - readonly notices: Readonly, () => string>>> - /** - * Derive what the section shows. The surfaces call it while rendering, so it reads nothing else that changes outside - * React; translating through `ctx.locale.bind` follows the active language. - */ - readonly present: (snapshot: CliAccountSnapshot, page: CliAccountPage) => CliAccountDisplay -} - -/** The `ctx.cliAccounts` registry. */ -export interface CliAccounts { - /** - * Show one account's section, title tag, activation prompt, and notices on the Plugins page. - * @param account - the bundle package, dictionary namespace, Remote operations, and presentation. - * @returns an idempotent disposer that removes the surfaces and closes the Host stream. - * @throws when another registration already occupies the package's bundle slots. - */ - register(account: CliAccountRegistration): () => void -} - -/** The face every surface entry of one registration injects. */ +/** The face every surface entry of one account injects. */ export interface CliAccountFace { - hooks: { cliAccount: HostObservable> } + hooks: { cliAccount: HostObservable } readonly packageName: string - readonly page: CliAccountPage - readonly notices: Readonly string>>> + /** Pick the active language's entry of the plugin's text. */ + readonly resolveText: (text: LocalizedText) => string + /** Carry out a section button's command. */ + readonly run: (command: CliAccountCommand) => void + /** Reopen the Host stream after it stopped. */ + readonly retry: () => void readonly dismissNotice: () => void - /** - * The registration's `present`. Method syntax lets the presenter typed by the plugin's own view stand in for one typed - * by any view. - * @param snapshot - the page snapshot the surface rendered from. - * @param page - the page actions. - * @returns the section's display. - */ - present(snapshot: CliAccountSnapshot, page: CliAccountPage): CliAccountDisplay } diff --git a/packages/client/ui-cli-account/src/index.ts b/packages/client/ui-cli-account/src/index.ts index 33a423c201..46d984063a 100644 --- a/packages/client/ui-cli-account/src/index.ts +++ b/packages/client/ui-cli-account/src/index.ts @@ -1,9 +1,154 @@ /** - * CLI account surfaces plugin, Node half. Pure UI plugin: the empty apply - * exists so the plugin appears in the host cordis.yml / Loader; the browser - * half ships via exports["./client"], discovered through the package.json - * dsh.client declaration. + * CLI account surfaces, Host half. CLI app plugins register their accounts with `ctx.cliAccounts`; the Plugins page + * follows every registered account through the `cliAccounts` Remote and starts or cancels operations through it. + * @module @deepseek-ai/dsh-client-ui-cli-account */ -/** Host plugin body — no host-side behavior for this surface plugin. */ -export function apply(): void {} +import type { Context } from '@deepseek-ai/cordis' +import type { + AnyCliAccountView, CliAccountEntry, CliAccountRegistration, CliAccountsView, CliOperationId, +} from '@deepseek-ai/dsh-cli-account/types' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' + +declare module '@deepseek-ai/cordis' { + interface Context { + /** CLI app plugin accounts on the Plugins page. */ + cliAccounts: CliAccounts + } +} + +interface Registered { + readonly entry: () => CliAccountEntry + readonly refresh: () => void + readonly start: (operation: string) => CliOperationId + readonly cancel: (id: CliOperationId) => Promise +} + +function registeredOf(registration: CliAccountRegistration): Registered { + const { packageName, source, operations, copy, present } = registration + return { + entry: () => { + const view = source.snapshot() + const { operation, result } = view + const notice = result?.outcome === 'succeeded' ? operations.find(candidate => candidate.kind === result.kind)?.notice : undefined + return { + packageName, copy, display: present(view), + ...operation === undefined ? {} : { + operation: { + id: operation.id, ...operation.authorizationUrl === undefined ? {} : { authorizationUrl: operation.authorizationUrl }, + }, + }, + ...result === undefined ? {} : { result: { id: result.id, ...notice === undefined ? {} : { notice } } }, + } + }, + refresh: () => { source.refresh() }, + start: (operation) => { + const kind = operations.find(candidate => candidate.kind === operation)?.kind + if (kind === undefined) throw new Error(`cliAccounts: ${packageName} has no page operation ${operation}`) + return source.start(kind) + }, + cancel: id => source.cancel(id), + } +} + +/** Holds the registered accounts and serves them to the Plugins page. */ +export default class CliAccounts extends TypertRemoteService { + private readonly accounts = new Map() + private readonly listeners = new Set<() => void>() + private readonly lifetime = new AbortController() + private subscribers = 0 + + /** @param ctx - the Host context the registry serves the page from. */ + constructor(ctx: Context) { + super(ctx, 'cliAccounts') + ctx.effect(() => () => { this.lifetime.abort(new Error('cliAccounts: registry disposed')) }) + } + + /** + * Show one account on the Plugins page for as long as the returned disposer has not run. + * @param registration - the bundle package, the account source, the page operations, and the presentation. + * @returns an idempotent disposer that withdraws the account. + * @throws when another account already uses the package. + */ + register(registration: CliAccountRegistration): () => void { + const { packageName } = registration + if (this.accounts.has(packageName)) throw new Error(`cliAccounts: ${packageName} is already registered`) + this.accounts.set(packageName, registeredOf(registration)) + const stop = registration.source.observe(() => { this.changed() }) + // A page that already follows the accounts checks a newly registered one, as it checks each account it subscribes to. + if (this.subscribers > 0) registration.source.refresh() + this.changed() + let active = true + return () => { + if (!active) return + active = false + stop() + this.accounts.delete(packageName) + this.changed() + } + } + + /** + * Follow every registered account; each new subscriber starts a check of each account that runs no operation. + * @param signal - the Client's observation lifetime; disposal also ends the stream. + * @returns the current accounts, then each changed set, coalescing changes that arrive before the next read. + */ + @Remote({ mode: 'stream' }) + async *watch(signal: AbortSignal): AsyncIterable { + const combined = AbortSignal.any([signal, this.lifetime.signal]) + let wake = Promise.withResolvers() + let changed = true + const notify = (): void => { changed = true; wake.resolve() } + this.listeners.add(notify) + combined.addEventListener('abort', notify, { once: true }) + this.subscribers += 1 + try { + for (const account of this.accounts.values()) account.refresh() + for (;;) { + if (!changed) await wake.promise + if (combined.aborted) break + wake = Promise.withResolvers() + changed = false + yield { accounts: [...this.accounts.values()].map(account => account.entry()) } + } + } finally { + this.subscribers -= 1 + this.listeners.delete(notify) + combined.removeEventListener('abort', notify) + } + } + + /** + * Start one of the operations the account registered as page actions. + * @param packageName - the account's bundle package. + * @param operation - the operation kind. + * @returns the operation identity. + * @throws for an unknown package or operation, while another operation runs, or after the account's disposal. + */ + @Remote + start(packageName: string, operation: string): CliOperationId { + return this.account(packageName).start(operation) + } + + /** + * Cancel one operation while its phase is cancellable, and wait for it to settle. + * @param packageName - the account's bundle package. + * @param id - the operation to cancel; a finished one or a phase that is not cancellable is ignored. + * @returns after the operation settles, or at once when nothing is cancelled. + * @throws for an unknown package. + */ + @Remote + cancel(packageName: string, id: CliOperationId): Promise { + return this.account(packageName).cancel(id) + } + + private account(packageName: string): Registered { + const account = this.accounts.get(packageName) + if (account === undefined) throw new Error(`cliAccounts: ${packageName} is not registered`) + return account + } + + private changed(): void { + for (const notify of this.listeners) notify() + } +} diff --git a/packages/client/ui-cli-account/tests/components.client.spec.tsx b/packages/client/ui-cli-account/tests/components.client.spec.tsx index 3bf1863e9c..6e9ad8bab9 100644 --- a/packages/client/ui-cli-account/tests/components.client.spec.tsx +++ b/packages/client/ui-cli-account/tests/components.client.spec.tsx @@ -1,231 +1,205 @@ // @vitest-environment jsdom -/** The section, tag, activation prompt, confirmation, and notice render a plugin's display with the copy it translates. */ +/** The surfaces render the plugin's display from the Host with the kit's shared copy, and turn buttons into commands. */ import type { ComponentProps } from 'react' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import type { CliAccountDisplay, CliAccountEntry } from '@deepseek-ai/dsh-cli-account/types' +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' import { afterEach, expect, it, vi } from 'vitest' import { CliAccountActivation, CliAccountActivationEntry, CliAccountBadge, CliAccountBadgeEntry, CliAccountSection, CliAccountSectionEntry, - CliAccountToast, CliAccountToastEntry, type CliAccountBadgeSubject, type CliAccountSectionProps, + CliAccountToast, CliAccountToastEntry, type CliAccountBadgeSubject, } from '../src/client/components.tsx' -import type { - AnyCliAccountView, CliAccountDisplay, CliAccountKey, CliAccountPage, CliAccountPhase, CliAccountSnapshot, -} from '../src/client/types.ts' +import { zh } from '../src/client/locales.ts' +import type { CliAccountSnapshot } from '../src/client/types.ts' afterEach(cleanup) const PACKAGE = '@acme/fixture' - -const copy: Record = { - 'section.title': 'Fixture account', - hint: 'Shared with the terminal.', - close: 'Close', - 'action.cancel': 'Cancel', - 'action.connect': 'Connect', - 'activation.title': 'Connect Fixture', - 'activation.body': 'The plugin is on.', - 'activation.later': 'Later', - 'failure.details': 'Diagnostic: {details}', - 'failure.exitCode': 'exit {code}', - 'notice.action-failed': 'Try again', - 'badge.connecting': 'Tag connecting', - 'badge.connected': 'Tag connected', - 'badge.disconnected': 'Tag disconnected', - 'badge.unavailable': 'Tag unavailable', - 'badge.stopped': 'Tag stopped', - 'status.checking': 'Checking', - 'status.connected': 'Connected', - 'status.disconnected': 'Not connected', - 'status.unavailable': 'Cannot confirm', - 'status.stopped': 'Not running', -} -const t = makeTranslate(copy) +const t = makeTranslate(zh) +const resolveText = (text: LocalizedText): string => typeof text === 'string' ? text : text.zh ?? text.en const button = (name: string) => screen.getByRole('button', { name }) -function section(props: Partial = {}) { - return +const DISCONNECTED: CliAccountDisplay = { + phase: 'disconnected', status: { en: 'Not connected', zh: '未连接' }, badge: '未连接', + buttons: [{ label: '连接演示', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [], } -it('labels each phase from the shared copy unless the plugin passes a step', () => { - const { container, rerender } = render(section()) - expect(screen.getByText('Fixture account')).toBeTruthy() - expect(screen.getByText('Not connected')).toBeTruthy() - expect(screen.getByText('Shared with the terminal.')).toBeTruthy() - expect(container.querySelector('[data-cli-account="disconnected"][data-cli-account-package="@acme/fixture"]')).toBeTruthy() - rerender(section({ phase: 'connecting' })) - expect(screen.getByText('Checking')).toBeTruthy() - rerender(section({ phase: 'connecting', status: 'Step 1' })) - expect(screen.getByText('Step 1')).toBeTruthy() -}) - -it('renders the plugin buttons, detail, and notes, and disables buttons while acting or offline', () => { - const connect = vi.fn() - const replace = vi.fn() - const props: Partial = { - actions: [{ label: 'Link', onClick: connect, variant: 'primary' }, { label: 'Retry', onClick: vi.fn() }], - detail: 'Link an app first.', - notes: [{ text: 'App: cli_a', action: { label: 'Change', onClick: replace, variant: 'ghost' } }, { text: 'Plain note' }], +function entry(display: CliAccountDisplay = DISCONNECTED): CliAccountEntry { + return { + packageName: PACKAGE, display, + copy: { title: { en: 'Fixture account', zh: '演示账号' }, hint: '与终端共用。', activation: { title: '连接演示', body: '插件已开启。', connect: '连接演示' } }, } - const { rerender } = render(section(props)) - expect(screen.getByText('Link an app first.')).toBeTruthy() - expect(screen.getByText('Plain note')).toBeTruthy() - fireEvent.click(button('Link')) - fireEvent.click(button('Change')) - expect(connect).toHaveBeenCalledOnce() - expect(replace).toHaveBeenCalledOnce() +} +function snapshot(change: Partial = {}, display?: CliAccountDisplay): CliAccountSnapshot { + return { entry: entry(display), linked: true, stopped: false, busy: false, notice: undefined, ...change } +} + +function section(change: Partial = {}, display?: CliAccountDisplay) { + const onCommand = vi.fn() + const onRetry = vi.fn() + const view = render( + , + ) + return { ...view, onCommand, onRetry } +} + +it('shows the plugin title, status, detail, notes, and hint, and runs each button as its command', () => { + const display: CliAccountDisplay = { + ...DISCONNECTED, detail: '先关联一个应用。', + notes: [{ text: '应用:cli_a', button: { label: '更换', command: { kind: 'start', operation: 'link-app' }, variant: 'ghost' } }, { text: '普通说明' }], + } + const { container, onCommand } = section({}, display) + expect(screen.getByText('演示账号')).toBeTruthy() + expect(screen.getByText('未连接')).toBeTruthy() + expect(screen.getByText('先关联一个应用。')).toBeTruthy() + expect(screen.getByText('普通说明')).toBeTruthy() + expect(screen.getByText('与终端共用。')).toBeTruthy() + expect(container.querySelector('[data-cli-account="disconnected"][data-cli-account-package="@acme/fixture"]')).toBeTruthy() + fireEvent.click(button('连接演示')) + fireEvent.click(button('更换')) + expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'connect' }], [{ kind: 'start', operation: 'link-app' }]]) +}) + +it('disables the buttons while an action is pending or the Host stream is down', () => { const disabled = (): boolean[] => screen.getAllByRole('button').map(element => (element as HTMLButtonElement).disabled) - rerender(section({ ...props, busy: true })) - expect(disabled()).toEqual([true, true, true]) - rerender(section({ ...props, linked: false })) - expect(disabled()).toEqual([true, true, true]) - rerender(section({ ...props, linked: false, phase: 'stopped' })) - expect(disabled()).toEqual([false, false, false]) + const { rerender } = section({ busy: true }) + expect(disabled()).toEqual([true]) + rerender( + , + ) + expect(disabled()).toEqual([true]) }) -it('asks before an action that changes the account outside DSH and runs it only after the user accepts', () => { - const signOut = vi.fn() - const replace = vi.fn() - render(section({ - phase: 'connected', - actions: [{ label: 'Sign out', onClick: signOut, confirm: { title: 'Sign out?', body: 'This signs out the terminal too.', label: 'Sign out now' } }], - notes: [{ text: 'App: cli_a', action: { label: 'Change', onClick: replace, confirm: { title: 'Change app?', body: 'Link another app.', label: 'Change app' } } }], - })) - fireEvent.click(button('Sign out')) - expect(screen.getByRole('dialog', { name: 'Sign out?' })).toBeTruthy() - expect(screen.getByText('This signs out the terminal too.')).toBeTruthy() - fireEvent.click(button('Cancel')) +it('asks before a button that changes the account outside DSH and runs it only after the user accepts', () => { + const display: CliAccountDisplay = { + phase: 'connected', status: '已连接', notes: [], + buttons: [{ label: '退出登录', command: { kind: 'start', operation: 'sign-out' }, confirm: { title: '退出演示?', body: '终端也会退出。', label: '确认退出' } }], + } + const { onCommand } = section({}, display) + fireEvent.click(button('退出登录')) + expect(screen.getByRole('dialog', { name: '退出演示?' })).toBeTruthy() + expect(screen.getByText('终端也会退出。')).toBeTruthy() + fireEvent.click(button(zh['action.cancel'])) expect(screen.queryByRole('dialog')).toBeNull() - expect(signOut).not.toHaveBeenCalled() - fireEvent.click(button('Sign out')) - fireEvent.click(button('Sign out now')) + fireEvent.click(button('退出登录')) + fireEvent.click(button('确认退出')) expect(screen.queryByRole('dialog')).toBeNull() - expect(signOut).toHaveBeenCalledOnce() - fireEvent.click(button('Change')) - fireEvent.click(button('Change app')) - expect(replace).toHaveBeenCalledOnce() + expect(onCommand.mock.calls).toEqual([[{ kind: 'start', operation: 'sign-out' }]]) }) -it.each<[string, CliAccountSectionProps['failure'], string]>([ - ['the failed command, exit code, and plugin details', { text: 'Failed.', command: { command: 'login', exitCode: 3 }, details: ['internal', undefined, 'sdk_error'] }, 'Failed. Diagnostic: login · exit 3 · internal · sdk_error'], - ['a command that produced no exit', { text: 'Failed.', command: { command: 'status', exitCode: null } }, 'Failed. Diagnostic: status'], - ['a failure without a command', { text: 'Failed.', command: undefined }, 'Failed.'], +it.each<[string, CliAccountDisplay['failure'], string]>([ + ['the guidance, then its diagnostic items', { text: '失败。', details: ['login', 'exit 3', 'internal'] }, '失败。 排障信息:login · exit 3 · internal'], + ['the guidance alone without diagnostic items', { text: '失败。' }, '失败。'], + ['the guidance alone for an empty diagnostic list', { text: '失败。', details: [] }, '失败。'], ])('reports %s', (_name, failure, expected) => { - render(section({ failure })) + section({}, { ...DISCONNECTED, ...failure === undefined ? {} : { failure } }) expect(screen.getByRole('alert').textContent).toBe(expected) }) -it('tags only the enabled bundle with a settled phase', () => { +it('explains a stopped stream with the shared copy and reopens it even while offline', () => { + const { container, onRetry } = section({ stopped: true, linked: false }, { ...DISCONNECTED, failure: { text: '失败。' }, notes: [{ text: '说明' }] }) + expect(screen.getByText(zh['status.stopped'])).toBeTruthy() + expect(screen.getByText(zh['detail.stopped'])).toBeTruthy() + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.queryByText('说明')).toBeNull() + expect(container.querySelector('[data-cli-account="stopped"]')).toBeTruthy() + fireEvent.click(button(zh['action.retry'])) + expect(onRetry).toHaveBeenCalledOnce() +}) + +it('tags only the enabled bundle of the package once its text settles', () => { const pkg = (name: string, enabled = true) => ({ name, enabled }) - const badge = (subject: CliAccountBadgeSubject, phase: CliAccountPhase = 'connected') => - - const { rerender } = render(badge({ kind: 'bundle', pkg: pkg(PACKAGE) })) - expect(screen.getByText('Tag connected')).toBeTruthy() - rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, 'unavailable')) - expect(screen.getByText('Tag unavailable')).toBeTruthy() - rerender(badge({ kind: 'row', pkg: pkg(PACKAGE) })) - expect(screen.getByText('Tag connected')).toBeTruthy() - const hidden: CliAccountBadgeSubject[] = [ - { kind: 'bundle', pkg: pkg(PACKAGE, false) }, - { kind: 'bundle', pkg: pkg('@acme/other') }, - { kind: 'item' }, - ] + const badge = (subject: CliAccountBadgeSubject, text: string | undefined) => + + const { rerender } = render(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, '已连接')) + expect(screen.getByText('已连接')).toBeTruthy() + rerender(badge({ kind: 'row', pkg: pkg(PACKAGE) }, '已连接')) + expect(screen.getByText('已连接')).toBeTruthy() + const hidden: CliAccountBadgeSubject[] = [{ kind: 'bundle', pkg: pkg(PACKAGE, false) }, { kind: 'bundle', pkg: pkg('@acme/other') }, { kind: 'item' }] for (const subject of hidden) { - rerender(badge(subject)) + rerender(badge(subject, '已连接')) expect(document.body.textContent).toBe('') } - rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, 'checking')) + rerender(badge({ kind: 'bundle', pkg: pkg(PACKAGE) }, undefined)) expect(document.body.textContent).toBe('') }) it('prompts to connect only while disconnected and steps aside once the phase settles elsewhere', () => { const onDismiss = vi.fn() const onConnect = vi.fn() - const prompt = (phase: CliAccountPhase) => + const prompt = (phase: 'checking' | 'disconnected' | 'connected') => + const { rerender } = render(prompt('checking')) expect(screen.queryByRole('dialog')).toBeNull() expect(onDismiss).not.toHaveBeenCalled() rerender(prompt('disconnected')) - expect(screen.getByRole('dialog', { name: 'Connect Fixture' })).toBeTruthy() - expect(screen.getByText('The plugin is on.')).toBeTruthy() - fireEvent.click(button('Connect')) + expect(screen.getByRole('dialog', { name: '连接演示' })).toBeTruthy() + expect(screen.getByText('插件已开启。')).toBeTruthy() + fireEvent.click(button('立即连接')) expect(onConnect).toHaveBeenCalledOnce() - fireEvent.click(button('Later')) + fireEvent.click(button(zh['activation.later'])) expect(onDismiss).toHaveBeenCalledOnce() rerender(prompt('connected')) expect(onDismiss).toHaveBeenCalledTimes(2) }) -it('shows the latest notice with the plugin copy or the shared failure copy', () => { +it('shows the latest notice with the plugin text or the shared failure copy', () => { const onDone = vi.fn() - const notices = { connect: () => 'Fixture connected' } - const toast = (notice: Parameters[0]['notice']) => - + const toast = (notice: CliAccountSnapshot['notice']) => const { rerender } = render(toast(undefined)) expect(document.body.textContent).toBe('') - rerender(toast({ seq: 1, kind: 'succeeded', operation: 'connect' })) - expect(screen.getByText('Fixture connected')).toBeTruthy() + rerender(toast({ seq: 1, kind: 'succeeded', text: { en: 'Connected', zh: '演示已连接' } })) + expect(screen.getByText('演示已连接')).toBeTruthy() rerender(toast({ seq: 2, kind: 'action-failed' })) - expect(screen.getByText('Try again')).toBeTruthy() - rerender(toast({ seq: 3, kind: 'succeeded', operation: 'check' })) - expect(document.body.textContent).toBe('') + expect(screen.getByText(zh['notice.action-failed'])).toBeTruthy() }) -function face(snapshot: Partial>, display: CliAccountDisplay) { - const current: CliAccountSnapshot = { - view: undefined, linked: true, stopped: false, busy: false, notice: undefined, ...snapshot, - } - const page: CliAccountPage = { start: vi.fn(), cancel: vi.fn(), openAuthorization: vi.fn(), retry: vi.fn() } - const present = vi.fn((_snapshot: CliAccountSnapshot, _page: CliAccountPage) => display) +function face(change: Partial = {}, display?: CliAccountDisplay) { + const current = snapshot(change, display) return { - useCliAccount: (selector: (value: CliAccountSnapshot) => R): R => selector(current), - packageName: PACKAGE, page, present, notices: { connect: () => 'Fixture connected' }, dismissNotice: vi.fn(), t, + useCliAccount: (selector: (value: CliAccountSnapshot) => R): R => selector(current), + packageName: PACKAGE, resolveText, run: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), t, } } -it('renders the section from the registration presenter with the page state', () => { - const props = face({ busy: true }, { phase: 'connected', detail: 'Signed in as Ada.', actions: [{ label: 'Check', onClick: vi.fn() }] }) +it('renders the section entry from the account face and runs its commands', () => { + const props = face({ busy: false }) render() - expect(props.present).toHaveBeenCalledWith(expect.objectContaining({ busy: true }), props.page) - expect(screen.getByText('Signed in as Ada.')).toBeTruthy() - expect((button('Check') as HTMLButtonElement).disabled).toBe(true) + fireEvent.click(button('连接演示')) + expect(props.run).toHaveBeenCalledWith({ kind: 'start', operation: 'connect' }) }) -it('tags the bundle with the presenter phase', () => { - const props = face({}, { phase: 'unavailable' }) +it('tags the bundle with the Host text, or with the shared copy once the stream stopped', () => { const subject = { kind: 'bundle', pkg: { name: PACKAGE, installed: true, availability: 'profile', official: false, enabled: true, rows: [] } } as const - render(} />) - expect(screen.getByText('Tag unavailable')).toBeTruthy() + const tag = (props: ReturnType) => + } /> + const { rerender } = render(tag(face())) + expect(screen.getByText('未连接')).toBeTruthy() + rerender(tag(face({ stopped: true }))) + expect(screen.getByText(zh['badge.stopped'])).toBeTruthy() + rerender(tag(face({}, { phase: 'checking', status: '检查中', buttons: [], notes: [] }))) + expect(document.body.textContent).toBe('') }) -it('connects from the prompt through the first primary action that asks nothing', () => { - const ask = vi.fn() - const connect = vi.fn() +it('connects from the prompt through the operation the display names, or only opens the page', () => { const onOpenDetails = vi.fn() - const props = face({}, { - phase: 'disconnected', - actions: [ - { label: 'Retry', onClick: vi.fn() }, - { label: 'Reset', onClick: ask, variant: 'primary', confirm: { title: 'Reset?', body: 'Resets the CLI.', label: 'Reset' } }, - { label: 'Link app', onClick: connect, variant: 'primary' }, - ], - }) - const prompt = (face: typeof props) => - } /> - const { rerender } = render(prompt(props)) - fireEvent.click(button('Connect')) + const prompt = (props: ReturnType) => + } /> + const named = face({}, { ...DISCONNECTED, connect: { kind: 'start', operation: 'link-app' } }) + const { rerender } = render(prompt(named)) + fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledOnce() - expect(connect).toHaveBeenCalledOnce() - expect(ask).not.toHaveBeenCalled() - - const bare = face({}, { phase: 'disconnected' }) + expect(named.run.mock.calls).toEqual([[{ kind: 'start', operation: 'link-app' }]]) + const bare = face() rerender(prompt(bare)) - fireEvent.click(button('Connect')) + fireEvent.click(button('连接演示')) expect(onOpenDetails).toHaveBeenCalledTimes(2) + expect(bare.run).not.toHaveBeenCalled() }) -it('shows the registration notice', () => { - const props = face({ notice: { seq: 1, kind: 'succeeded', operation: 'connect' } }, { phase: 'connected' }) - render() - expect(screen.getByText('Fixture connected')).toBeTruthy() +it('shows the account notice through the toast entry', () => { + render() + expect(screen.getByText('演示已连接')).toBeTruthy() }) diff --git a/packages/client/ui-cli-account/tests/connection.client.spec.ts b/packages/client/ui-cli-account/tests/connection.client.spec.ts index dcc452cabc..81e4dc49b3 100644 --- a/packages/client/ui-cli-account/tests/connection.client.spec.ts +++ b/packages/client/ui-cli-account/tests/connection.client.spec.ts @@ -1,30 +1,30 @@ // @vitest-environment jsdom -/** The connection mirror follows a plugin's Host view and drives its account operations through the plugin's Remote. */ +/** The connection follows every registered account through one Host stream and keeps each account's browser state apart. */ import { Context } from '@deepseek-ai/cordis' import type { RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client' -import type { CliAccountView, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' +import type { CliAccountEntry, CliAccountsView, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { expect, it, onTestFinished, vi } from 'vitest' -import { CliAccountConnection } from '../src/client/connection.ts' - -type View = CliAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect' | 'leave', 'authorizing' | 'leaving'> +import { CliAccountsConnection } from '../src/client/connection.ts' const OP = 'op-1' as CliOperationId -const OUT: View = { account: { state: 'out' } } +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' +const COPY = { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } } +const ok = (value: T): RemoteResult => ({ ok: true, value }) +const failed = (): RemoteResult => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never -type Operation = NonNullable - -function operation( - kind: Operation['kind'], phase: Operation['phase'], options: { url?: string; cancellable?: boolean; id?: CliOperationId } = {}, -): Operation { - const link = options.url === undefined ? {} : { authorizationUrl: options.url } - return { id: options.id ?? OP, kind, phase, cancellable: options.cancellable ?? false, ...link } +function entry(packageName: string, extra: Partial = {}): CliAccountEntry { + return { packageName, copy: COPY, display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, ...extra } } +const waiting = (url?: string, id = OP): Partial => + ({ operation: { id, ...url === undefined ? {} : { authorizationUrl: url } } }) + function fixture() { - const queue: View[] = [] + const queue: CliAccountsView[] = [] let wake: (() => void) | undefined, closed = false, failure: Error | undefined, accepted = 0 - let options!: RemoteStreamOptions + let options!: RemoteStreamOptions const open = () => ({ async *[Symbol.asyncIterator]() { for (;;) { @@ -39,10 +39,11 @@ function fixture() { dispose: vi.fn(async () => { closed = true; wake?.() }), }) const streams: Array> = [] - const ok = (value: T): RemoteResult => ({ ok: true, value }) - const follow = vi.fn() - const cancel = vi.fn(async (_id: CliOperationId) => ok(undefined)) - const start = vi.fn(async () => ok(OP)) + const remote = { + watch: vi.fn(), + start: vi.fn(async (_packageName: string, _operation: string) => ok(OP)), + cancel: vi.fn(async (_packageName: string, _id: CliOperationId): Promise> => ok(undefined)), + } const ctx = new Context() ctx.provide('remote', { $stream: (value: typeof options) => { @@ -54,21 +55,17 @@ function fixture() { }, }) const windowOpen = vi.spyOn(window, 'open').mockReturnValue(null) - const connection = new CliAccountConnection(ctx, { - name: 'Fixture connection', follow, cancel, notices: { connect: () => 'Connected', leave: () => 'Left' }, - }) + const connection = new CliAccountsConnection(ctx, remote) onTestFinished(async () => { await connection.dispose(); windowOpen.mockRestore(); await ctx.fiber.dispose() }) return { - connection, follow, cancel, start, open: windowOpen, streams, options: () => options, - snapshot: () => connection.state.getSnapshot(), + connection, remote, open: windowOpen, streams, options: () => options, get stream() { return streams.at(-1)! }, - deliver(view: View) { - queue.push(view) - wake?.() - }, - async publish(view: View) { + snapshot: (packageName = FIXTURE) => connection.accounts.getSnapshot().get(packageName)?.getSnapshot(), + act: (packageName = FIXTURE) => connection.actions(packageName), + deliver(view: CliAccountsView) { queue.push(view); wake?.() }, + async publish(...entries: CliAccountEntry[]) { const target = accepted + 1 - this.deliver(view) + this.deliver({ accounts: entries }) await vi.waitFor(() => { expect(accepted).toBe(target) }) }, failOnClose(error: Error) { failure = error }, @@ -76,210 +73,171 @@ function fixture() { } } -const settle = async (b: ReturnType) => { await vi.waitFor(() => { expect(b.snapshot().busy).toBe(false) }) } +const settle = async (b: ReturnType, packageName = FIXTURE) => { + await vi.waitFor(() => { expect(b.snapshot(packageName)?.busy).toBe(false) }) +} // Every fixture step settles through microtasks, so one macrotask lets a pending reopen or start finish. const drain = () => new Promise((resolve) => { setTimeout(resolve, 0) }) -const SECOND = 'op-2' as CliOperationId -it('mirrors the Host view through the plugin stream', async () => { +it('mirrors the registered accounts through the watch stream', async () => { const b = fixture() const signal = new AbortController().signal void b.options().open(signal) - expect(b.follow).toHaveBeenCalledWith(signal) - expect(b.options().name).toBe('Fixture connection') - expect(b.options().ended(true).message).toBe('Fixture connection stream ended') - await b.publish(OUT) - expect(b.snapshot()).toMatchObject({ view: OUT, linked: true, stopped: false, busy: false }) + expect(b.remote.watch).toHaveBeenCalledWith(signal) + expect(b.options().ended(true).message).toBe('CLI accounts stream ended') + await b.publish(entry(FIXTURE), entry(OTHER)) + const published = b.connection.accounts.getSnapshot() + expect([...published.keys()]).toEqual([FIXTURE, OTHER]) + expect(b.snapshot()).toMatchObject({ entry: entry(FIXTURE), linked: true, stopped: false, busy: false, notice: undefined }) b.options().carrierFailed?.(new Error('lost')) - expect(b.snapshot().linked).toBe(false) + expect(b.snapshot()?.linked).toBe(false) + expect(b.snapshot(OTHER)?.linked).toBe(false) + + await b.publish(entry(OTHER), entry(FIXTURE)) + expect(b.connection.accounts.getSnapshot()).toBe(published) + await b.publish(entry(OTHER)) + expect([...b.connection.accounts.getSnapshot().keys()]).toEqual([OTHER]) + expect(b.snapshot()).toBeUndefined() + b.act().run({ kind: 'open' }) + b.act().dismissNotice() + expect(b.remote.start).not.toHaveBeenCalled() }) -it('opens each new link of an operation this browser started once and reports mapped successes', async () => { +it('opens each new link of an operation this browser started once and reports the Host notice of its success', async () => { const b = fixture() - await b.publish(OUT) - b.connection.page.start(b.start) + await b.publish(entry(FIXTURE), entry(OTHER)) + b.act().run({ kind: 'start', operation: 'connect' }) await settle(b) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/a', cancellable: true }) }) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/a', cancellable: true }) }) + expect(b.remote.start).toHaveBeenCalledWith(FIXTURE, 'connect') + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER, waiting('https://example.com/other'))) + await b.publish(entry(FIXTURE, waiting('https://example.com/a')), entry(OTHER)) expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) - b.connection.page.openAuthorization() + b.act().run({ kind: 'open' }) expect(b.open).toHaveBeenCalledTimes(2) - await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'succeeded', operation: 'connect' }) - await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.snapshot().notice?.seq).toBe(1) - b.connection.dismissNotice() - expect(b.snapshot().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Connected' } }), entry(OTHER)) + expect(b.snapshot()?.notice).toEqual({ seq: 1, kind: 'succeeded', text: 'Connected' }) + expect(b.snapshot(OTHER)?.notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Connected' } }), entry(OTHER)) + expect(b.snapshot()?.notice?.seq).toBe(1) + b.act().dismissNotice() + expect(b.snapshot()?.notice).toBeUndefined() }) -it('reports no notice for an unmapped kind or an unsuccessful outcome', async () => { +it('reports nothing for a result without a notice or for another operation', async () => { const b = fixture() - b.connection.start(b.start) + await b.publish(entry(FIXTURE)) + b.act().run({ kind: 'start', operation: 'check' }) await settle(b) - await b.publish({ ...OUT, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) - b.connection.start(async () => ({ ok: true, value: SECOND })) - await settle(b) - await b.publish({ ...OUT, result: { id: SECOND, kind: 'connect', outcome: 'failed', failure: { command: 'login', exitCode: 1 } } }) - expect(b.snapshot().notice).toBeUndefined() + await b.publish(entry(FIXTURE, { result: { id: 'other' as CliOperationId, notice: 'Other' } })) + await b.publish(entry(FIXTURE, { result: { id: OP } })) + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Late' } })) + expect(b.snapshot()?.notice).toBeUndefined() }) it('opens a link reported before the start answered, never a foreign operation, and only over HTTPS', async () => { const b = fixture() const answer = Promise.withResolvers>() - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/other', id: 'other' as CliOperationId }) }) - b.connection.start(() => answer.promise) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/device' }) }) + await b.publish(entry(FIXTURE, waiting('https://example.com/other', 'other' as CliOperationId))) + b.remote.start.mockReturnValueOnce(answer.promise) + b.act().run({ kind: 'start', operation: 'connect' }) + await b.publish(entry(FIXTURE, waiting('https://example.com/device'))) expect(b.open).not.toHaveBeenCalled() - answer.resolve({ ok: true, value: OP }) + answer.resolve(ok(OP)) await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('https://example.com/device', '_blank', 'noopener,noreferrer') }) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'http://example.com/device' }) }) - b.connection.page.openAuthorization() - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'not a url' }) }) - b.connection.page.openAuthorization() + await b.publish(entry(FIXTURE, waiting('http://example.com/device'))) + b.act().run({ kind: 'open' }) + await b.publish(entry(FIXTURE, waiting('not a url'))) + b.act().run({ kind: 'open' }) expect(b.open).toHaveBeenCalledOnce() }) -it('opens a link again when a later operation this browser started offers the same link', async () => { +it('follows no operation after a rejected start and reports the failed action once', async () => { const b = fixture() - const device = 'https://example.com/device' - b.connection.start(b.start) + await b.publish(entry(FIXTURE)) + b.act().run({ kind: 'start', operation: 'connect' }) await settle(b) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: device, cancellable: true }) }) - await b.publish({ ...OUT, result: { id: OP, kind: 'connect', outcome: 'cancelled' } }) - b.connection.start(async () => ({ ok: true, value: SECOND })) + b.remote.start.mockResolvedValueOnce(failed()) + b.act().run({ kind: 'start', operation: 'connect' }) await settle(b) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: device, id: SECOND }) }) - expect(b.open.mock.calls).toEqual([[device, '_blank', 'noopener,noreferrer'], [device, '_blank', 'noopener,noreferrer']]) -}) - -it('keeps following its operation when another operation\'s result arrives after the start', async () => { - const b = fixture() - b.connection.start(b.start) - await settle(b) - await b.publish({ ...OUT, result: { id: 'other' as CliOperationId, kind: 'connect', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toBeUndefined() - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/device' }) }) - await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.open).toHaveBeenCalledOnce() - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'succeeded', operation: 'connect' }) -}) - -it('follows no operation after a rejected start', async () => { - const b = fixture() - b.connection.start(b.start) - await settle(b) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/a' }) }) - b.connection.start(async () => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never) - await settle(b) - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/b' }) }) - await b.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.open.mock.calls).toEqual([['https://example.com/a', '_blank', 'noopener,noreferrer']]) - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'action-failed' }) -}) - -it('cancels only an operation the Host marks cancellable', async () => { - const b = fixture() - b.connection.page.cancel() - await b.publish({ ...OUT, operation: operation('leave', 'leaving') }) - b.connection.page.cancel() - b.connection.page.openAuthorization() - expect(b.cancel).not.toHaveBeenCalled() - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { cancellable: true }) }) - b.connection.page.cancel() - await settle(b) - expect(b.cancel).toHaveBeenCalledWith(OP) + expect(b.snapshot()?.notice).toEqual({ seq: 1, kind: 'action-failed' }) + await b.publish(entry(FIXTURE, waiting('https://example.com/b'))) + await b.publish(entry(FIXTURE, { result: { id: OP, notice: 'Connected' } })) expect(b.open).not.toHaveBeenCalled() + expect(b.snapshot()?.notice).toEqual({ seq: 1, kind: 'action-failed' }) }) -it('reports a failed action once and ignores overlapping clicks', async () => { +it('asks the Host to cancel the operation in progress, and ignores clicks while one action is pending', async () => { const b = fixture() - await b.publish(OUT) - const second = vi.fn(async () => ({ ok: true as const, value: OP })) - b.connection.start(async () => ({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) as never) - b.connection.start(second) - await vi.waitFor(() => { expect(b.snapshot().notice?.kind).toBe('action-failed') }) - expect(second).not.toHaveBeenCalled() + await b.publish(entry(FIXTURE)) + b.act().run({ kind: 'cancel' }) + expect(b.remote.cancel).not.toHaveBeenCalled() + await b.publish(entry(FIXTURE, waiting())) + const answer = Promise.withResolvers>() + b.remote.cancel.mockReturnValueOnce(answer.promise) + b.act().run({ kind: 'cancel' }) + b.act().run({ kind: 'start', operation: 'connect' }) + expect(b.snapshot()?.busy).toBe(true) + answer.resolve(ok(undefined)) + await settle(b) + expect(b.remote.cancel).toHaveBeenCalledExactlyOnceWith(FIXTURE, OP) + expect(b.remote.start).not.toHaveBeenCalled() }) -it('reports nothing after disposal and marks the page stopped when the stream fails', async () => { +it('reports nothing after disposal and marks every account stopped when the stream fails', async () => { const b = fixture() - await b.publish(OUT) + await b.publish(entry(FIXTURE)) const answer = Promise.withResolvers>() - b.connection.start(() => answer.promise) + b.remote.start.mockReturnValueOnce(answer.promise) + b.act().run({ kind: 'start', operation: 'connect' }) b.failOnClose(new Error('closed')) await b.connection.dispose() - answer.resolve({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + answer.resolve(failed()) await settle(b) expect(b.stream.dispose).toHaveBeenCalled() - expect(b.snapshot()).toMatchObject({ linked: true, notice: undefined }) + expect(b.snapshot()).toMatchObject({ linked: true, stopped: false, notice: undefined }) const c = fixture() - await c.publish(OUT) + await c.publish(entry(FIXTURE), entry(OTHER)) c.fail(new Error('invalid frame')) await vi.waitFor(() => { expect(c.snapshot()).toMatchObject({ linked: false, stopped: true }) }) + expect(c.snapshot(OTHER)).toMatchObject({ linked: false, stopped: true }) }) -it('opens no link for a start that answers after disposal', async () => { +it('opens no link for a start that answers after disposal, and ignores a view yielded after disposal', async () => { const b = fixture() + await b.publish(entry(FIXTURE)) const answer = Promise.withResolvers>() - b.connection.start(() => answer.promise) - await b.publish({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/device' }) }) + b.remote.start.mockReturnValueOnce(answer.promise) + b.act().run({ kind: 'start', operation: 'connect' }) + await b.publish(entry(FIXTURE, waiting('https://example.com/device'))) + b.deliver({ accounts: [entry(FIXTURE, waiting('https://example.com/late'))] }) await b.connection.dispose() - answer.resolve({ ok: true, value: OP }) - await settle(b) + answer.resolve(ok(OP)) + await drain() expect(b.open).not.toHaveBeenCalled() + expect(b.snapshot()?.entry).toEqual(entry(FIXTURE, waiting('https://example.com/device'))) }) -it('ignores a Host view the stream yields after disposal', async () => { +it('reopens a stopped stream once for repeated retries, ignores retry while it runs, and opens none after disposal', async () => { const b = fixture() - await b.publish(OUT) - b.connection.start(b.start) - await settle(b) - b.deliver({ ...OUT, operation: operation('connect', 'authorizing', { url: 'https://example.com/late' }) }) - await b.connection.dispose() - expect(b.open).not.toHaveBeenCalled() - expect(b.snapshot().view).toEqual(OUT) -}) - -it('reopens a stopped Host stream on retry and ignores retry while the stream runs', async () => { - const b = fixture() - b.connection.page.retry() - await b.publish(OUT) + b.act().retry() + await b.publish(entry(FIXTURE)) expect(b.streams).toHaveLength(1) b.fail(new Error('gone')) - await vi.waitFor(() => { expect(b.snapshot().stopped).toBe(true) }) - b.connection.page.retry() + await vi.waitFor(() => { expect(b.snapshot()?.stopped).toBe(true) }) + b.act().retry() + b.act().retry() await vi.waitFor(() => { expect(b.streams).toHaveLength(2) }) - expect(b.snapshot()).toMatchObject({ view: undefined, stopped: false }) - await b.publish(OUT) - expect(b.snapshot()).toMatchObject({ view: OUT, linked: true }) + expect(b.snapshot()?.stopped).toBe(false) + await b.publish(entry(FIXTURE)) + expect(b.snapshot()).toMatchObject({ linked: true, stopped: false }) - await b.connection.dispose() - b.connection.page.retry() - expect(b.streams).toHaveLength(2) -}) - -it('opens no stream for a retry that disposal overtakes', async () => { - const b = fixture() - await b.publish(OUT) - b.fail(new Error('gone')) - await vi.waitFor(() => { expect(b.snapshot().stopped).toBe(true) }) - b.connection.page.retry() + b.fail(new Error('gone again')) + await vi.waitFor(() => { expect(b.snapshot()?.stopped).toBe(true) }) + b.act().retry() await b.connection.dispose() await drain() - expect(b.streams).toHaveLength(1) -}) - -it('reopens one stream for repeated retries and closes that stream on disposal', async () => { - const b = fixture() - await b.publish(OUT) - b.fail(new Error('gone')) - await vi.waitFor(() => { expect(b.snapshot().stopped).toBe(true) }) - b.connection.page.retry() - b.connection.page.retry() - await drain() expect(b.streams).toHaveLength(2) - await b.connection.dispose() - expect(b.stream.dispose).toHaveBeenCalled() + b.act().retry() + expect(b.streams).toHaveLength(2) }) diff --git a/packages/client/ui-cli-account/tests/mount.client.spec.ts b/packages/client/ui-cli-account/tests/mount.client.spec.ts new file mode 100644 index 0000000000..c82d3d0213 --- /dev/null +++ b/packages/client/ui-cli-account/tests/mount.client.spec.ts @@ -0,0 +1,147 @@ +/** + * The browser plugin mounts the `cliAccounts` Remote and shows each account the Host registers, withdrawing its surfaces + * with the account or the plugin. + */ +import assert from 'node:assert/strict' +import { Context, Service } from '@deepseek-ai/cordis' +import type { CliAccountEntry, CliAccountsView, CliOperationId } from '@deepseek-ai/dsh-cli-account/types' +import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' +import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { RemoteResult, TypertRemoteContribution } from '@deepseek-ai/dsh-typert-protocol' +import { expect, it, onTestFinished, vi } from 'vitest' +import { CliAccountActivationEntry, CliAccountBadgeEntry, CliAccountSectionEntry, CliAccountToastEntry } from '../src/client/components.tsx' +import { NS } from '../src/client/locales.ts' +import { inject, mountCliAccounts } from '../src/client/mount.ts' +import type { CliAccountFace } from '../src/client/types.ts' + +const contribution: TypertRemoteContribution = { package: '@deepseek-ai/dsh-client-ui-cli-account', descriptors: [] } +const FIXTURE = '@acme/fixture' +const OTHER = '@acme/other' + +const SLOTS = [ + ['plugins.bundle.config', CliAccountSectionEntry], + ['plugins.bundle.activation', CliAccountActivationEntry], + ['plugins.detail.badge', CliAccountBadgeEntry], + ['shell.overlay', CliAccountToastEntry], +] as const + +function isFace(value: Record): asserts value is Record & CliAccountFace { + assert(typeof value.packageName === 'string' && typeof value.resolveText === 'function' && typeof value.run === 'function') + assert(typeof value.hooks === 'object' && value.hooks !== null) +} + +/** Read the face a slot entry injects. */ +function faceOf(item: { readonly inject?: (() => Record) | undefined }): CliAccountFace { + const face = item.inject!() + isFace(face) + return face +} + +function entry(packageName: string): CliAccountEntry { + return { + packageName, + copy: { title: 'Fixture account', hint: 'Shared.', activation: { title: 'Connect', body: 'On.', connect: 'Connect' } }, + display: { phase: 'disconnected', status: 'Not connected', buttons: [], notes: [] }, + } +} + +async function bench() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + const queue: CliAccountsView[] = [] + let wake: (() => void) | undefined, closed = false, accepted = 0 + const closeStream = vi.fn(async () => { closed = true; wake?.() }) + const unmount = vi.fn(async () => {}) + const start = vi.fn(async (_packageName: string, _operation: string): Promise> => + ({ ok: true, value: 'op-1' as CliOperationId })) + class Remote extends Service { + constructor() { super(ctx, 'remote') } + async $mount(received: TypertRemoteContribution) { + expect(received).toBe(contribution) + return unmount + } + $stream() { + return { + async *[Symbol.asyncIterator]() { + for (;;) { + const next = queue.shift() + if (next !== undefined) { yield { value: next, accept: () => { accepted++ } }; continue } + if (closed) return + await new Promise((resolve) => { wake = resolve }) + } + }, + dispose: closeStream, + } + } + } + new Remote() + ctx.provide('remote.cliAccounts', { watch: vi.fn(), start, cancel: vi.fn() }) + const locale = new LocaleRuntime(ctx) + ctx.provide('locale', locale) + await ctx.plugin(SlotRegistry) + ctx.slots.register({ name: 'root', children: { + 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, + 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, + 'plugins.detail.badge': { kind: 'list', scope: 'root' }, + 'shell.overlay': { kind: 'list', scope: 'root' }, + } } as never, () => null) + const owners = () => SLOTS.flatMap(([slot]) => ctx.slots.entries(slot).map(item => faceOf(item).packageName)) + return { + ctx, locale, start, closeStream, unmount, owners, + mount: () => ctx.plugin({ inject: [...inject], apply: scope => mountCliAccounts(scope, contribution) }), + async publish(...entries: CliAccountEntry[]) { + const target = accepted + 1 + queue.push({ accounts: entries }) + wake?.() + await vi.waitFor(() => { expect(accepted).toBe(target) }) + }, + } +} + +it('shows each registered account with one face under the kit dictionary and withdraws the surfaces of an account the Host drops', async () => { + const b = await bench() + await b.mount() + expect(b.locale.bind(NS)('action.retry')).toBe('Retry') + expect(b.owners()).toEqual([]) + await b.publish(entry(FIXTURE), entry(OTHER)) + const faces = SLOTS.map(([slot, component]) => { + const found = b.ctx.slots.entries(slot).find(item => faceOf(item).packageName === FIXTURE) + expect(found).toMatchObject({ locale: NS, component }) + return faceOf(found!) + }) + expect(new Set(faces.map(face => face.hooks.cliAccount)).size).toBe(1) + expect(faces[0]!.hooks.cliAccount.getSnapshot().entry).toEqual(entry(FIXTURE)) + expect(faces[0]!.resolveText({ en: 'Connected', zh: '已连接' })).toBe('Connected') + expect(b.ctx.slots.entries('plugins.bundle.config').map(item => item.options.key)).toEqual([FIXTURE, OTHER]) + expect(b.ctx.slots.entries('plugins.bundle.activation').map(item => item.options.key)).toEqual([FIXTURE, OTHER]) + expect(b.ctx.slots.entries('plugins.detail.badge').map(item => item.options.id)).toEqual([`${FIXTURE}.account`, `${OTHER}.account`]) + expect(b.ctx.slots.entries('shell.overlay').map(item => item.options.id)).toEqual([`${FIXTURE}.account-toast`, `${OTHER}.account-toast`]) + faces[0]!.run({ kind: 'start', operation: 'connect' }) + await vi.waitFor(() => { expect(b.start).toHaveBeenCalledWith(FIXTURE, 'connect') }) + + await b.publish(entry(OTHER)) + expect(b.owners()).toEqual([OTHER, OTHER, OTHER, OTHER]) + await b.publish(entry(OTHER), entry(FIXTURE)) + expect(b.owners().filter(owner => owner === FIXTURE)).toHaveLength(4) +}) + +it('withdraws every surface, the dictionaries, and the stream before the Remote when the plugin unloads', async () => { + const b = await bench() + const fiber = b.mount() + await fiber + await b.publish(entry(FIXTURE), entry(OTHER)) + expect(b.owners()).toHaveLength(8) + await fiber.dispose() + expect(b.owners()).toEqual([]) + expect(b.locale.bind(NS)('action.retry')).toBe('action.retry') + expect(b.closeStream).toHaveBeenCalledOnce() + expect(b.unmount).toHaveBeenCalledOnce() + expect(b.closeStream.mock.invocationCallOrder[0]).toBeLessThan(b.unmount.mock.invocationCallOrder[0]!) +}) + +it('withdraws the Remote when the surfaces fail to mount', async () => { + const b = await bench() + vi.spyOn(b.locale, 'register').mockImplementation(() => { throw new Error('registration failed') }) + await expect(mountCliAccounts(b.ctx, contribution)).rejects.toThrow('registration failed') + expect(b.unmount).toHaveBeenCalledOnce() +}) diff --git a/packages/client/ui-cli-account/tests/registration.client.spec.ts b/packages/client/ui-cli-account/tests/registration.client.spec.ts deleted file mode 100644 index b8c803ac44..0000000000 --- a/packages/client/ui-cli-account/tests/registration.client.spec.ts +++ /dev/null @@ -1,105 +0,0 @@ -/** The registry shows an account's four surfaces under the plugin's dictionary and withdraws them with its disposer or this plugin. */ -import { Context, Service } from '@deepseek-ai/cordis' -import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' -import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' -import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' -import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import { expect, it, onTestFinished, vi } from 'vitest' -import { CliAccountActivationEntry, CliAccountBadgeEntry, CliAccountSectionEntry, CliAccountToastEntry } from '../src/client/components.tsx' -import { apply, inject } from '../src/client/index.ts' -import type { CliAccountKey, CliAccountRegistration } from '../src/client/types.ts' -import { apply as nodeApply } from '../src/index.ts' - -declare module '@deepseek-ai/dsh-client-ui-slots' { - interface LocaleNamespaceMap { - 'fixture-account': CliAccountKey | 'notice.connected' - } -} - -type View = CliAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> - -const SLOTS = [ - ['plugins.bundle.config', CliAccountSectionEntry], - ['plugins.bundle.activation', CliAccountActivationEntry], - ['plugins.detail.badge', CliAccountBadgeEntry], - ['shell.overlay', CliAccountToastEntry], -] as const - -function account(packageName: string): CliAccountRegistration { - return { - packageName, locale: 'fixture-account', - follow: () => ({ async *[Symbol.asyncIterator]() { /* the plugin reports nothing in this composition */ } }), - cancel: async (): Promise> => ({ ok: true, value: undefined }), - notices: { connect: () => 'Connected' }, - present: () => ({ phase: 'checking' }), - } -} - -async function bench() { - const ctx = new Context() - onTestFinished(async () => { await ctx.fiber.dispose() }) - const closed = vi.fn(async () => {}) - class Remote extends Service { - constructor() { super(ctx, 'remote') } - $stream() { - return { async *[Symbol.asyncIterator]() { /* the plugin reports nothing in this composition */ }, dispose: closed } - } - } - new Remote() - ctx.provide('locale', new LocaleRuntime(ctx)) - await ctx.plugin(SlotRegistry) - ctx.slots.register({ name: 'root', children: { - 'plugins.bundle.activation': { kind: 'keyed', scope: 'root' }, - 'plugins.bundle.config': { kind: 'keyed', scope: 'root' }, - 'plugins.detail.badge': { kind: 'list', scope: 'root' }, - 'shell.overlay': { kind: 'list', scope: 'root' }, - } } as never, () => null) - const fiber = ctx.plugin({ inject: [...inject], apply }) - await fiber - const count = () => SLOTS.reduce((total, [slot]) => total + ctx.slots.entries(slot).length, 0) - return { ctx, fiber, closed, count } -} - -it('registers the four surfaces with one shared face and removes them with the disposer', async () => { - const b = await bench() - const registration = account('@acme/fixture') - const dispose = b.ctx.cliAccounts.register(registration) - const faces = SLOTS.map(([slot, component]) => { - const [entry] = b.ctx.slots.entries(slot) - expect(entry).toMatchObject({ locale: 'fixture-account', component }) - return entry!.inject!() - }) - expect(new Set(faces.map(face => face.hooks)).size).toBe(1) - expect(faces[0]).toMatchObject({ packageName: '@acme/fixture', present: registration.present, notices: registration.notices }) - expect(b.ctx.slots.entries('plugins.bundle.config')[0]!.options.key).toBe('@acme/fixture') - expect(b.ctx.slots.entries('plugins.bundle.activation')[0]!.options.key).toBe('@acme/fixture') - expect(b.ctx.slots.entries('plugins.detail.badge')[0]!.options.id).toBe('@acme/fixture.account') - expect(b.ctx.slots.entries('shell.overlay')[0]!.options.id).toBe('@acme/fixture.account-toast') - dispose() - await vi.waitFor(() => { expect(b.closed).toHaveBeenCalledOnce() }) - expect(b.count()).toBe(0) - dispose() - expect(b.closed).toHaveBeenCalledOnce() -}) - -it('withdraws every account when this plugin unloads', async () => { - const b = await bench() - b.ctx.cliAccounts.register(account('@acme/fixture')) - b.ctx.cliAccounts.register(account('@acme/other')) - expect(b.count()).toBe(8) - await b.fiber.dispose() - expect(b.count()).toBe(0) - expect(b.closed).toHaveBeenCalledTimes(2) -}) - -it('rolls back a registration whose package another account already shows', async () => { - const b = await bench() - b.ctx.cliAccounts.register(account('@acme/fixture')) - expect(() => b.ctx.cliAccounts.register(account('@acme/fixture'))).toThrow() - await vi.waitFor(() => { expect(b.closed).toHaveBeenCalledOnce() }) - expect(b.count()).toBe(4) -}) - -it('keeps the Node half inert', () => { - expect(() => { nodeApply() }).not.toThrow() -}) diff --git a/packages/client/ui-cli-account/tests/registry.host.spec.ts b/packages/client/ui-cli-account/tests/registry.host.spec.ts new file mode 100644 index 0000000000..acfa986505 --- /dev/null +++ b/packages/client/ui-cli-account/tests/registry.host.spec.ts @@ -0,0 +1,149 @@ +/** The registry serves every registered account to the Plugins page and routes page operations to the account that owns them. */ +import { Context } from '@deepseek-ai/cordis' +import type { + CliAccountDisplay, CliAccountRegistration, CliAccountSource, CliAccountsView, CliAccountView, CliOperationId, +} from '@deepseek-ai/dsh-cli-account/types' +import { expect, it, onTestFinished, vi } from 'vitest' +import CliAccounts from '../src/index.ts' + +type View = CliAccountView<{ readonly state: 'out' | 'in' }, 'check' | 'connect', 'authorizing'> + +const OP = 'op-1' as CliOperationId +const COPY = { + title: { en: 'Fixture account', zh: '演示账号' }, + hint: 'Shared with the terminal.', + activation: { title: 'Connect Fixture', body: 'The plugin is on.', connect: 'Connect' }, +} + +function source(initial: View = { account: { state: 'out' } }) { + let view = initial + const listeners = new Set<() => void>() + const fake = { + snapshot: () => view, + observe: vi.fn((listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }), + refresh: vi.fn(), + start: vi.fn((_kind: 'check' | 'connect') => OP), + cancel: vi.fn(async (_id: CliOperationId) => {}), + } satisfies CliAccountSource + return { fake, listeners, publish: (next: View) => { view = next; for (const listener of listeners) listener() } } +} + +function display(view: View): CliAccountDisplay { + return view.account.state === 'in' + ? { phase: 'connected', status: 'Connected', badge: 'Connected', buttons: [], notes: [] } + : { phase: 'disconnected', status: 'Not connected', buttons: [{ label: 'Connect', command: { kind: 'start', operation: 'connect' }, variant: 'primary' }], notes: [] } +} + +function registration(packageName: string, account = source()): CliAccountRegistration { + return { + packageName, source: account.fake, copy: COPY, present: display, + operations: [{ kind: 'check' }, { kind: 'connect', notice: { en: 'Fixture connected', zh: '演示已连接' } }], + } +} + +async function registry() { + const ctx = new Context() + onTestFinished(async () => { await ctx.fiber.dispose() }) + await ctx.plugin(CliAccounts) + return ctx +} + +/** Read the stream until a view satisfies the predicate. */ +async function until(stream: AsyncIterator, predicate: (view: CliAccountsView) => boolean): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('stream ended') + if (predicate(next.value)) return next.value + } +} + +it('publishes each account with its copy, display, operation, and result, and checks it for each new subscriber', async () => { + const ctx = await registry() + const account = source() + const withdraw = ctx.cliAccounts.register(registration('@acme/fixture', account)) + expect(account.fake.refresh).not.toHaveBeenCalled() + const controller = new AbortController() + const stream = ctx.cliAccounts.watch(controller.signal)[Symbol.asyncIterator]() + const first = await until(stream, () => true) + expect(account.fake.refresh).toHaveBeenCalledOnce() + expect(first.accounts).toEqual([{ packageName: '@acme/fixture', copy: COPY, display: display({ account: { state: 'out' } }) }]) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: 'https://example.com/a' } }) + const waiting = await until(stream, view => view.accounts[0]?.operation !== undefined) + expect(waiting.accounts[0]?.operation).toEqual({ id: OP, authorizationUrl: 'https://example.com/a' }) + + account.publish({ account: { state: 'out' }, operation: { id: OP, kind: 'connect', phase: 'checking', cancellable: false } }) + const checking = await until(stream, (view) => { + const operation = view.accounts[0]?.operation + return operation !== undefined && operation.authorizationUrl === undefined + }) + expect(checking.accounts[0]?.operation).toEqual({ id: OP }) + + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) + const connected = await until(stream, view => view.accounts[0]?.result !== undefined) + expect(connected.accounts[0]).toMatchObject({ + display: { phase: 'connected' }, result: { id: OP, notice: { en: 'Fixture connected', zh: '演示已连接' } }, + }) + + // Only a success reports a notice, and only for an operation that registered one. + account.publish({ account: { state: 'out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'disconnected')).accounts[0]?.result).toEqual({ id: OP }) + account.publish({ account: { state: 'in' }, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect((await until(stream, view => view.accounts[0]?.display.phase === 'connected')).accounts[0]?.result).toEqual({ id: OP }) + + withdraw() + expect((await until(stream, view => view.accounts.length === 0)).accounts).toEqual([]) + withdraw() + expect(account.listeners.size).toBe(0) + controller.abort() + expect((await stream.next()).done).toBe(true) +}) + +it('checks an account registered while the page follows, and none registered while nobody follows', async () => { + const ctx = await registry() + const idle = source() + ctx.cliAccounts.register(registration('@acme/idle', idle)) + const controller = new AbortController() + const stream = ctx.cliAccounts.watch(controller.signal)[Symbol.asyncIterator]() + await until(stream, view => view.accounts.length === 1) + const late = source() + ctx.cliAccounts.register(registration('@acme/late', late)) + expect(late.fake.refresh).toHaveBeenCalledOnce() + expect((await until(stream, view => view.accounts.length === 2)).accounts.map(entry => entry.packageName)).toEqual(['@acme/idle', '@acme/late']) + controller.abort() + await stream.next() + const after = source() + ctx.cliAccounts.register(registration('@acme/after', after)) + expect(after.fake.refresh).not.toHaveBeenCalled() +}) + +it('starts only the operations an account registered and cancels through its source', async () => { + const ctx = await registry() + const account = source() + ctx.cliAccounts.register(registration('@acme/fixture', account)) + expect(ctx.cliAccounts.start('@acme/fixture', 'connect')).toBe(OP) + expect(account.fake.start).toHaveBeenCalledWith('connect') + expect(() => ctx.cliAccounts.start('@acme/fixture', 'sign-out')).toThrow('@acme/fixture has no page operation sign-out') + expect(() => ctx.cliAccounts.start('@acme/other', 'connect')).toThrow('@acme/other is not registered') + await ctx.cliAccounts.cancel('@acme/fixture', OP) + expect(account.fake.cancel).toHaveBeenCalledWith(OP) + expect(() => ctx.cliAccounts.cancel('@acme/other', OP)).toThrow('@acme/other is not registered') +}) + +it('refuses a second account for a package', async () => { + const ctx = await registry() + ctx.cliAccounts.register(registration('@acme/fixture')) + expect(() => ctx.cliAccounts.register(registration('@acme/fixture'))).toThrow('@acme/fixture is already registered') +}) + +it('ends every stream when the registry unloads', async () => { + const ctx = new Context() + const fiber = ctx.plugin(CliAccounts) + await fiber + const stream = ctx.cliAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + await until(stream, () => true) + const pending = stream.next() + await fiber.dispose() + expect((await pending).done).toBe(true) + await ctx.fiber.dispose() +}) diff --git a/packages/client/ui-cli-account/tsconfig.client.json b/packages/client/ui-cli-account/tsconfig.client.json new file mode 100644 index 0000000000..9448434617 --- /dev/null +++ b/packages/client/ui-cli-account/tsconfig.client.json @@ -0,0 +1,53 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.client.tsbuildinfo" + }, + "include": [ + "src/client", + "src/css-modules.d.ts" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../api/gateway/tsconfig.client.json" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../../connector/cli-account" + }, + { + "path": "../store" + }, + { + "path": "../ui-layout" + }, + { + "path": "../ui-plugin-manager/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-renderer" + }, + { + "path": "../ui-slots" + }, + { + "path": "../../typert/protocol" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../../util/package-manifest" + } + ] +} diff --git a/packages/experimental/agent-team-profile/tsconfig.json b/packages/client/ui-cli-account/tsconfig.host.json similarity index 50% rename from packages/experimental/agent-team-profile/tsconfig.json rename to packages/client/ui-cli-account/tsconfig.host.json index c1eaa3f96e..71c14eeeb4 100644 --- a/packages/experimental/agent-team-profile/tsconfig.json +++ b/packages/client/ui-cli-account/tsconfig.host.json @@ -2,20 +2,21 @@ "extends": "../../../tsconfig.base.json", "compilerOptions": { "rootDir": "src", - "outDir": "lib/types" + "outDir": "lib/types", + "tsBuildInfoFile": "lib/tsconfig.host.tsbuildinfo" }, - "include": [ - "src" + "files": [ + "src/index.ts" ], "references": [ { "path": "../../../vendor/cordis" }, { - "path": "../agent-team" + "path": "../../connector/cli-account" }, { - "path": "../tool-agent-team" + "path": "../../typert/protocol" } ] } diff --git a/packages/client/ui-cli-account/tsconfig.json b/packages/client/ui-cli-account/tsconfig.json index 141247afaf..2eca820546 100644 --- a/packages/client/ui-cli-account/tsconfig.json +++ b/packages/client/ui-cli-account/tsconfig.json @@ -1,45 +1,11 @@ { - "extends": "../../../tsconfig.base.client.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], + "files": [], "references": [ { - "path": "../../../vendor/cordis" + "path": "./tsconfig.host.json" }, { - "path": "../../api/gateway/tsconfig.client.json" - }, - { - "path": "../../api/remotes/tsconfig.client.json" - }, - { - "path": "../../connector/cli-account" - }, - { - "path": "../store" - }, - { - "path": "../ui-layout" - }, - { - "path": "../ui-plugin-manager/tsconfig.client.json" - }, - { - "path": "../ui-primitives" - }, - { - "path": "../ui-renderer" - }, - { - "path": "../ui-slots" - }, - { - "path": "../../typert/protocol" + "path": "./tsconfig.client.json" } ] } diff --git a/packages/client/ui-cli-account/tsdown.config.ts b/packages/client/ui-cli-account/tsdown.config.ts index 7aa03cebc1..620261533c 100644 --- a/packages/client/ui-cli-account/tsdown.config.ts +++ b/packages/client/ui-cli-account/tsdown.config.ts @@ -1,3 +1,3 @@ import { clientBundle } from '../tsdown.client.ts' -export default clientBundle(import.meta.dirname, ['lib/types/index.js']) +export default clientBundle(import.meta.dirname, ['lib/types/index.js'], { hostPhase: true }) diff --git a/packages/client/ui-commands/src/client/presentation.ts b/packages/client/ui-commands/src/client/presentation.ts index f5abacd2a4..95204d468e 100644 --- a/packages/client/ui-commands/src/client/presentation.ts +++ b/packages/client/ui-commands/src/client/presentation.ts @@ -2,7 +2,8 @@ import type { ComponentType } from 'react' import type { InputTriggerCandidate } from '@deepseek-ai/dsh-client-ui-input-trigger/client' import { - IconCompactOutlineRegular, IconDownloadOutlineRegular, IconGoalOutlineRegular, IconPaperPlaneOutlineRegular, IconPlanOutlineRegular, + IconCompactOutlineRegular, IconDownloadOutlineRegular, + IconGoalOutlineRegular, IconPaperPlaneOutlineRegular, IconPlanOutlineRegular, PermissionIconFullAccessRegular, } from '@deepseek-ai/dsh-client-ui-primitives' import type { IconProps } from '@deepseek-ai/dsh-client-ui-primitives' diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 0f945d3708..6c078adbe3 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: cc4dafd1aae02468 zh: be6b67724b7ac4a3 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 9b596b668979544a - zh: 159f24dfc8715c92 + en: 3fa2fb91ad383c05 + zh: 1e1edd7f9a830377 /deepseek-ai-dsh-client-ui-conversation/temporary-composer-entries: en: 59cd63057dfb6eeb zh: b2e2c86e810b7bb8 @@ -33,8 +33,8 @@ en: 9f4e0da7c8addf88 zh: 1a33d9981af75643 /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work: - en: 38d243630d0e4c38 - zh: a58cdc35b664020b + en: 1413851e9d622bd3 + zh: 84502501f8ce599b /deepseek-ai-dsh-client-ui-conversation/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 2002f10c1b..cc60deae1c 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -80,7 +80,7 @@ The context meter follows the [statistics-control radius](../../../docs/ui-radiu The composer uses the shared [text-input focus policy](../ui-primitives/README.md#use-this-package) on mount, Session switching, and unlock. Identified phones and tablets require tapping the input; desktop devices retain automatic focus. On these mobile devices, a submission that empties the focused draft moves focus to the non-text composer card, dismissing the keyboard while retaining its navigation position. Rejected submissions, retained newer draft text, and another control already holding focus preserve focus. The [Lexical patch](../../../patches/lexical@0.49.0.patch) keeps caret scrolling in the same coordinate system as DOM geometry when a mobile keyboard pans the page. -The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a panel kept inside the viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. +The context-occupancy button shows a ring and percentage below the input card, after the Session statistics. Clicking it opens the token breakdown in a panel kept inside the viewport, including when no statistics are shown; the button stays hidden until context usage and capacity are available. Outside the Hero, that row keeps one reading's height while it is empty, so statistics and context usage arriving later do not change the composer's height; the Hero shows no empty row. With Coding Tools off, the shell hides only Trajectory; other plugin-contributed Views remain available. The View tab bar is hidden when fewer than two Views are available. Turning Coding Tools off while Trajectory is active returns to Chat; stored View preferences and recorded Session data remain intact. Turning it on makes Trajectory available again. View owners receive the available roster so their navigation actions can follow the same visibility. @@ -100,13 +100,13 @@ Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and c The package occupies the root-scoped `main` key `conversation`. Its `main.conversation` shell keeps the resident `conversation.header` outside the optional-Session `conversation.content` Component Factory. The header hosts root-scoped navigation without a selected Session; titles, actions, and View tabs remain in its strict Session child. The Factory owns the shared body and Composer, reads the current Session through its standard Hook, and exposes strict-Session `views` plus root-scoped `widthControls` local positions. Its default adapter renders the existing `conversation.session` entry, while the main occurrence selects the width handles; an embedded occurrence can replace `views` and omit those handles without rendering the main Header. The shared body and Composer register the queue and Todo docks. The Todo dock uses the shared panel elevation above the composer; its rows use the shared idle, ongoing, and done markers for pending, in-progress, and completed items. `ctx.uiSession.provide()` materializes the Conversation and input sources from the same Session binding and supplies `inputActions` as a stable standard prop. -A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident header keeps a 40px window strip on macOS desktop that it owns as its drag row, and no empty vertical space on Web, Windows, or Linux. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. When the title and actions do not fit, the title area clips them and fades its trailing edge before the utilities, which stay fully visible and clickable; overlays in the title and actions slots portal to stay outside that clip. +A blank Session retains the header's leading and corner controls, including the right-sidebar opener, while hiding its title, actions, utilities, and View tabs. Selecting a Workspace creates the Session needed by these controls; the first message is not required. Without a selected Session, the strict header is absent; the resident header keeps the blank-Session 40px row on every platform, so the Hero input card sits at the same height before and after a Workspace is bound; on macOS desktop that row is also the window drag row. Sidebar entries retain their own data and execution prerequisites. A started Session header uses one row when fewer than two Views are available; the tab row reserves space only while rendered. When the title and actions do not fit, the title area clips them and fades its trailing edge before the utilities, which stay fully visible and clickable; overlays in the title and actions slots portal to stay outside that clip. View selection is deterministic: a registered persisted selection wins, otherwise registered `chat` wins, otherwise no View renders. It never chooses the first registered View. Shell phase combines Session lifecycle with the active-target set; no target-specific snapshot is read by the shell. The shell reads the persisted View preference before rendering when a Session first binds or a cached Session becomes current, activates the registered preferred View or Chat fallback, and activates later tab or focus selections before committing them to the store. A blank Session still omits the `conversation.view` slot; no unselected target is activated. -Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer intentionally owns its full footer band, which is not a resize target; an already-captured drag lifts its indicator until release ([handle styles](src/client/skeleton/ConversationRoot.module.css)). +Active transcripts in the main occurrence expose content-width drag handles in their uncovered side gutters; embedded occurrences omit them. A View that paints into a gutter raises only its concrete painted element above the handle; transparent full-width wrappers stay below so they do not claim empty gutter. This requires the path between that element and the Conversation body to remain outside an intermediate stacking context; the shipped Chromium behavior is pinned by the browser scenario. Chat applies the rule to table elements, while its column-bounded tool cards need no raise. Wheel motion over a handle still scrolls the transcript, while Ctrl+wheel remains a browser zoom gesture. The sticky composer owns its full footer band, which is not a resize target; a captured drag continues under the band and under gutter tables, which cover its indicator. In an active transcript the composer rests at the scrollport floor even when no View fills the column, keeps one stacking rank in every state, above transcript sticky headers and the back-to-bottom control, so menus it opens upward cover that control, and never serves as a scroll-anchoring target. It keeps its own compositor layer whatever lies beneath it, which makes it the containing block for fixed-position descendants: contributions to `conversation.composer`, `conversation.composer.bar`, `conversation.composer.dock`, `conversation.input.dock`, and the other `conversation.input.*` slots must portal fixed overlays to the document body, for example with `Tooltip` or `Menu` `portal` or `createPortal` ([handle and composer styles](src/client/skeleton/ConversationRoot.module.css)). The width-handle indicator follows the pointer only during a captured drag; ordinary hover leaves its position unchanged. @@ -124,7 +124,7 @@ A default send waits for the Host: Enter captures the draft text, its reference Queued submission echoes show “Sending…” beside disabled edit, remove, and steer buttons; a collapsed dock keeps the sending status in its header. A matching Host queue row replaces the echo and enables each action according to its normal text-content and running-state requirements. Prompt acknowledgement alone does not enable queue actions. A refused or failed submission publishes no echo and leaves the draft in the composer with an error notice. A refusal from the Agent admission stage (`session/prompt-rejected`) shows its own text, unless `presented` says the refusing plugin explains it in its own interface, in which case the composer adds no notice. -Disabled Send and Stop buttons suppress their tooltips, including a Stop button that becomes a disabled Send button when the turn ends. While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. While a message waits for the Host, the seat shows its progress, and a separate Stop stays beside it. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label. Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions and accept pasted or dropped images, but expose no File row; if their parent is offline, Send and the composer gestures lock while QueueDock controls for the live inbox remain available ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../subagent/subagent/README.md)). +Disabled Send and Stop buttons suppress their tooltips, including a Stop button that becomes a disabled Send button when the turn ends. While a normal composer is running, its primary pointer action remains Stop when the draft is empty or input is unavailable. Actionable text or attachments switch the same seat to Send; clearing or successfully submitting the draft restores Stop. While a message waits for the Host, the seat shows its progress, and a separate Stop stays beside it. The busy-Enter setting selects the Queue or Steer delivery for ordinary Sessions and continuable children, and the running Send button delivers through the same mode plain Enter resolves to; while it is enabled (no upload pending) over a plain message draft its label names that mode (Queue message or Steer message), so the setting governs Enter and the button together while Cmd/Ctrl+Enter still uses the other mode, and idle sessions, empty drafts, and `/` command lines keep the plain Send label. Their QueueDock rows share Edit, Remove, and Steer, and an empty draft shares the steer-all chord. One-shot children remain read-only. Plan mode and active goals do not change attachment intake. Continuable children keep separate Send and Stop actions and accept pasted or dropped images, but expose no File row; creator availability does not disable input, and Host admission failures use the ordinary prompt error feedback ([decisions](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md), [inbox controls](../../subagent/subagent/README.md)). File chips and editable skill references share a whole-reference hover background and follow the composer's line height and text baseline. The first click delegates preview opening to the registered reference source immediately, including the first click of a double-click sequence. Subsequent clicks retain native text selection; an existing noncollapsed selection suppresses pointer preview activation. Previewing does not change the draft, its clipboard projection, or submission. @@ -201,6 +201,7 @@ None; Conversation assembly and browser input state do not alter provider-side p - **Only registered targets can render** — the shell deliberately has no implicit fallback target beyond the registered `chat` preference. - **Factory occurrences inherit their render-position Session** — `conversation.content` does not accept an independently addressed Session; that requires a separate Session-provider capability. +- **Composer backdrop blur is verified only in Chromium** — with `will-change: transform` on the docked composer, descendant `backdrop-filter` still samples the transcript in Chromium; WebKit behavior has not been verified. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index b1d1c5fbd3..75aa7b7fbe 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -80,7 +80,7 @@ Queue 预览启用空白折叠和文档边缘 trim,保留 emoji,并使用 CS composer 在挂载、切换 Session 和解除锁定时使用共享的[文字输入框聚焦策略](../ui-primitives/README.zh.md#use-this-package)。识别出的手机和平板需要点击输入框;桌面设备保留自动聚焦。在这些移动设备上,提交清空正在聚焦的草稿后,焦点移到不接受文字输入的 composer 卡片,收起键盘并保留键盘导航位置。被拒绝的提交、保留的新草稿文字,以及已经聚焦的其他控件均保留原有焦点。移动端键盘平移页面时,[Lexical 补丁](../../../patches/lexical@0.49.0.patch)让光标滚动计算与 DOM 几何使用同一坐标系。 -上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在视口内的面板查看 token 构成,没有统计项时面板也不会越界;上下文用量和容量尚不可用时,按钮保持隐藏。 +上下文占用按钮在输入卡片下方、会话统计右侧显示圆环和百分比。点击按钮可在视口内的面板查看 token 构成,没有统计项时面板也不会越界;上下文用量和容量尚不可用时,按钮保持隐藏。Hero 之外,这一行为空时仍保留一项读数的高度,因此会话统计和上下文用量稍后到达不会改变 composer 的高度;Hero 不显示空行。 关闭代码工作工具时,外壳仅隐藏 Trajectory;其他插件贡献的 View 仍然可用。可用 View 少于两个时隐藏 View 标签栏。在 Trajectory 激活时关闭代码工作工具会返回 Chat;已保存的 View 偏好和 Session 记录保持不变。开启后,Trajectory 恢复可用。View 所有者接收可用列表,使导航操作跟随相同的可见性。 @@ -100,13 +100,13 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 本包占据 root 作用域 `main` 中的 `conversation` key。其 `main.conversation` 外壳将常驻的 `conversation.header` 放在可选 Session 的 `conversation.content` Component Factory 外。未选中 Session 时,头部仍承载根作用域导航;标题、操作和 View 标签保留在严格 Session 子组件中。Factory 拥有共享正文与 Composer,通过其标准 Hook 读取当前 Session,并公开 strict-Session `views` 与 root-scoped `widthControls` 两个局部位置。默认 adapter 渲染现有 `conversation.session` entry,主 occurrence 选择宽度拖拽条;嵌入式 occurrence 可以替换 `views`、省略拖拽条,且不渲染主 Header。共享正文与 Composer 注册 queue dock 和 Todo dock。Todo dock 在 composer 上方使用共享面板 elevation;其中的行分别以共享 idle、ongoing 与 done 标记表示待处理、进行中与已完成。`ctx.uiSession.provide()` 从同一个 Session binding 物化 Conversation 与 input source,并将 `inputActions` 作为稳定标准 prop 提供。 -blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻 header 在 macOS 桌面保留 40px 的窗口顶条,由它自己作为拖拽行持有,在 Web、Windows 或 Linux 上不预留空白高度。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。标题与 actions 放不下时,标题区域会裁剪它们,并在 utilities 之前渐隐其末端;utilities 始终完整可见且可点击;标题与 actions slot 中的浮层通过 portal 渲染,不受该裁剪影响。 +blank Session 保留 header 的 leading 与 corner 控件,包括右侧栏展开入口,同时隐藏标题、actions、utilities 和 View tabs。选择 Workspace 会创建这些控件所需的 Session,无需先发送消息。没有选中 Session 时,strict header 不挂载;常驻 header 在所有平台都保留与 blank Session 相同的 40px 行,因此绑定 Workspace 前后 Hero 输入卡片的高度位置不变;在 macOS 桌面上,这一行同时是窗口拖拽行。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。标题与 actions 放不下时,标题区域会裁剪它们,并在 utilities 之前渐隐其末端;utilities 始终完整可见且可点击;标题与 actions slot 中的浮层通过 portal 渲染,不受该裁剪影响。 View 选择规则固定:有效且已注册的持久化选择优先,其次是已注册的 `chat`,否则不渲染 View;绝不选择第一个已注册 View。Shell phase 只组合 Session lifecycle 与 active-target set,不读取任何 target-specific 快照。 Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染前读取持久化 View 偏好,激活已注册的偏好 View 或 Chat fallback,并在后续 tab 或 focus 选择写入 store 前先激活对应 target。blank Session 仍不渲染 `conversation.view` slot;未选中的 target 不会激活。 -主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 刻意拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会将指示线提高到松开为止([拖动手柄样式](src/client/skeleton/ConversationRoot.module.css))。 +主 occurrence 的活跃 transcript 只在未被内容覆盖的两侧沟槽中提供正文宽度拖拽条;嵌入式 occurrence 省略这些拖拽条。View 如果绘制进沟槽,只将具体的可见元素提到拖拽条上方;透明的全宽包装层保持在下方,不会占用空白沟槽。该规则要求此元素与 Conversation body 之间不能引入中间堆叠上下文;浏览器场景固定了交付 Chromium 的行为。Chat 将该规则用于表格元素,其限定在阅读列内的工具卡片无需提高层级。指针位于拖拽条上时,滚轮仍会滚动 transcript,Ctrl+滚轮则保留为浏览器缩放手势。粘滞 composer 拥有完整的底部区带,该区域不是宽度调整目标;已捕获的拖拽会在该区带和沟槽中的表格下方继续,此时指示线被它们遮住。在活跃 transcript 中,即使没有 View 撑满整列,composer 也停在滚动区底部;它在所有状态下保持同一层级,高于 transcript 的吸顶标题与“回到底部”按钮,因此它向上打开的菜单会盖住该按钮;它也从不作为滚动锚定目标。无论下方是什么内容,它都保持自己的合成层,因此成为 fixed 定位后代的包含块:向 `conversation.composer`、`conversation.composer.bar`、`conversation.composer.dock`、`conversation.input.dock` 以及其他 `conversation.input.*` slot 贡献的内容,必须把 fixed 浮层 portal 到 document body,例如使用 `Tooltip` 或 `Menu` 的 `portal`,或 `createPortal`([拖动手柄与 composer 样式](src/client/skeleton/ConversationRoot.module.css))。 宽度拖拽条的指示线只在已捕获指针的拖拽期间跟随指针,普通悬停不改变其位置。 @@ -124,7 +124,7 @@ Session 首次绑定或缓存的 Session 成为 current 时,shell 会在渲染 排队提交的本地回显在禁用的编辑、删除、插话按钮旁显示“发送中…”;折叠后的队列在标题栏保留发送状态。匹配的 Host 队列行替换回显后,各操作按原有的纯文本内容和运行状态要求启用。仅收到提示词确认不会启用队列操作。被拒绝或失败的提交不会公开回显,草稿留在 composer 中并显示错误提示。Agent 接纳阶段的拒绝(`session/prompt-rejected`)显示它自带的文字;若 `presented` 表明拒绝它的插件会在自己的界面里说明,composer 不再提示。 -Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切换成禁用 Send 的按钮也遵循此规则。普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。消息等待 Host 接收期间,该位置显示发送进度,旁边另有独立的 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,允许粘贴或拖入图片,但不提供「文件」菜单项;parent 离线时,Send 与 composer 手势锁定,但在线 inbox 的 QueueDock 控制仍可使用([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../subagent/subagent/README.zh.md))。 +Send 和 Stop 按钮禁用时不显示提示气泡,轮次结束后由 Stop 切换成禁用 Send 的按钮也遵循此规则。普通 composer 运行时,如果草稿为空或输入不可用,主指针操作保持为 Stop。可提交的文字或附件会把同一位置切换为 Send;清空或成功提交草稿后恢复 Stop。消息等待 Host 接收期间,该位置显示发送进度,旁边另有独立的 Stop。繁忙态 Enter 设置为普通 Session 与可继续 child 选择 Queue 或 Steer 投递,运行中的 Send 按钮按 plain Enter 解析出的同一模式投递;当它在普通消息草稿上可用(没有待上传文件)时,其标签以该模式命名(排队发送或插话发送),因此该设置同时约束 Enter 与按钮,而 Cmd/Ctrl+Enter 仍使用另一模式;空闲会话、空草稿与 `/` 命令行保留普通的 Send 标签。它们的 QueueDock 行共享 Edit、Remove 与 Steer,空草稿也共享 steer-all 组合键。One-shot child 继续只读。Plan Mode 与 active goal 不改变附件入口。可继续 child 保留独立的 Send 与 Stop 操作,允许粘贴或拖入图片,但不提供「文件」菜单项;创建者的在线状态不禁用输入,Host 接收失败使用普通提示词错误反馈([决策](../../../.agents/notes/archived/bug-fix/2026-08-20-running-draft-primary-send.md)、[inbox 控制](../../subagent/subagent/README.zh.md))。 文件标签和可编辑的 skill 引用共用覆盖整个引用的悬停背景,并跟随输入框的行高与文字基线。首次点击立即由已注册的引用来源负责打开预览,包括双击序列的第一次点击。后续点击保留原生文本选择行为;已有非折叠选区时,指针点击不打开预览。预览不改变草稿、剪贴板文本或提交内容。 @@ -201,6 +201,7 @@ selector 必须是 owner currency 的纯函数。非 null 返回值作为 `match - **只有已注册 target 可以渲染**——除已注册的 `chat` 偏好外,shell 刻意不提供隐式 fallback target。 - **Factory occurrence 继承渲染位置的 Session**——`conversation.content` 不接受独立寻址的 Session;该能力需要单独的 Session provider。 +- **composer 内的毛玻璃只在 Chromium 中验证过**——docked composer 设置 `will-change: transform` 后,Chromium 中后代的 `backdrop-filter` 仍会采样背后的 transcript;WebKit 中的表现尚未验证。 diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index 369f562a7b..0c438e0f4c 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -276,7 +276,10 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { 'conversation.session.header.views.actions': { kind: 'list'; scope: 'root'; owner: ConversationViewActionsOwnerProps } /** Registered Conversation target Views, rendered one at a time. */ 'conversation.view': { kind: 'list'; scope: 'session'; owner: ConvViewOwnerProps } - /** Selector-routed replacements for the current Session's resident composer. */ + /** + * Selector-routed replacements for the current Session's resident composer; fixed overlays must + * portal to the document body because the docked composer contains them. + */ 'conversation.composer': { kind: 'chain'; scope: 'session'; owner: ComposerChainProps } /** Workspace picker shown by the blank-session Hero. */ 'conversation.hero.workspace': { kind: 'single'; scope: 'root'; owner: EmptyWorkspaceOwnerProps } @@ -286,34 +289,66 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { 'conversation.hero.agentPreset': { kind: 'single'; scope: 'session-maybe'; owner: HeroAgentPresetOwnerProps } /** Compact options right-aligned in the New Session row after the workspace and preset controls; rendered only with a Session. */ 'conversation.hero.options': { kind: 'list'; scope: 'session' } - /** Full-width entries above the composer card. */ + /** + * Full-width entries above the composer card; fixed overlays must portal to the document body + * because the docked composer contains them. + */ 'conversation.input.dock': { kind: 'list'; scope: 'session'; owner: InputZone } - /** Floating entries rendered inside the resident composer card. */ + /** + * Floating entries rendered inside the resident composer card; fixed overlays must portal to + * the document body because the docked composer contains them. + */ 'conversation.input.overlay': { kind: 'list'; scope: 'session' } - /** Ambient entries below the composer card. */ + /** + * Ambient entries below the composer card; fixed overlays must portal to the document body + * because the docked composer contains them. + */ 'conversation.composer.dock': { kind: 'list'; scope: 'session' } - /** Compact controls at the left of the composer tool row. */ + /** + * Compact controls at the left of the composer tool row; fixed overlays must portal to the + * document body because the docked composer contains them. + */ 'conversation.input.left': { kind: 'list'; scope: 'session' } - /** Compact controls before the composer submit action. */ + /** + * Compact controls before the composer submit action; fixed overlays must portal to the + * document body because the docked composer contains them. + */ 'conversation.input.right': { kind: 'list'; scope: 'session' } - /** Compact action after the model selector; it can expand across the toolbar while retaining the editor and submit action. */ + /** + * Compact action after the model selector; it can expand across the toolbar while retaining the + * editor and submit action, and fixed overlays must portal to the document body because the + * docked composer contains them. + */ 'conversation.input.activity': { kind: 'single'; scope: 'session'; owner: InputActivityOwnerProps } - /** Resident composer body, including the no-Session inert state. */ + /** + * Resident composer body, including the no-Session inert state; fixed overlays must portal to + * the document body because the docked composer contains them. + */ 'conversation.composer.bar': { kind: 'single'; scope: 'session-maybe'; owner: ComposerBarOwnerProps } - /** Optional draft-attachment rail and drop target. */ + /** + * Optional draft-attachment rail and drop target; fixed overlays must portal to the document + * body because the docked composer contains them. + */ 'conversation.input.attachments': { kind: 'single' scope: 'session-maybe' owner: ComposerAttachmentsOwnerProps } - /** Plan control inside the composer tool row. */ + /** + * Plan control inside the composer tool row; fixed overlays must portal to the document body + * because the docked composer contains them. + */ 'conversation.input.plan': { kind: 'single'; scope: 'session'; owner: InputControlOwnerProps } - /** Current-session permission control inside the composer tool row. */ + /** + * Current-session permission control inside the composer tool row; fixed overlays must portal + * to the document body because the docked composer contains them. + */ 'conversation.input.permission': { kind: 'single'; scope: 'session'; owner: InputControlOwnerProps } /** * Model selector inside the composer tool row. When expanded controls cannot * share a line, the row sets --dsh-composer-model-text-display to none and * --dsh-composer-model-icon-display to block for an occupant's compact display. + * Fixed overlays must portal to the document body because the docked composer contains them. */ 'conversation.input.model': { kind: 'single'; scope: 'session'; owner: InputControlOwnerProps } } diff --git a/packages/client/ui-conversation/src/client/input/hub.ts b/packages/client/ui-conversation/src/client/input/hub.ts index 02897a18c6..9ed94a567b 100644 --- a/packages/client/ui-conversation/src/client/input/hub.ts +++ b/packages/client/ui-conversation/src/client/input/hub.ts @@ -130,7 +130,7 @@ export class InputHub implements SessionInputResolver { quoteInsertionAllowed: () => { const state = session.getSnapshot() return !state.removed && (state.subagent === null - || (state.subagent.address.mode === 'continuable' && state.subagent.parentAvailable === true)) + || state.subagent.address.mode === 'continuable') && this.conversation().blocks.storeFor(session.sessionId).getSnapshot() === undefined }, steerQueue: () => { void this.steerQueue(session, shell) }, diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index dca76eb57f..d89b2e91c4 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -20,7 +20,6 @@ export const zh = { 'placeholder.plan': PLAN_NEXT_ACTION_ZH, 'placeholder.default': '发消息或创建任务, / 调用指令, @ 文件或对话', 'placeholder.unavailable': '会话不可用', - 'placeholder.parentOffline': '父会话已离线,无法继续发送;仍可停止当前运行', 'placeholder.hero': '描述你想要构建的内容, / 调用指令, @ 文件或对话', 'placeholder.workspace': '选择一个工作区开始', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter 插话发送全部排队消息', @@ -93,10 +92,12 @@ export const zh = { 'tool.title.getGoal': '查看目标', 'tool.title.updateGoal': '更新目标', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': '创建定时任务', - 'tool.title.listSchedules': '查看定时任务', - 'tool.title.deleteSchedule': '删除定时任务', - 'tool.title.updateSchedule': '修改定时任务', + 'tool.title.createSchedule': '创建自动化任务', + 'tool.title.listSchedules': '查看自动化任务', + 'tool.title.viewSchedule': '查看自动化任务详情', + 'tool.title.editSchedule': '编辑自动化任务', + 'tool.title.deleteSchedule': '删除自动化任务', + 'tool.title.updateSchedule': '修改自动化任务', 'detail.state': '状态', 'detail.todo.completed': '已完成', 'detail.todo.in_progress': '进行中', @@ -132,12 +133,16 @@ export const zh = { 'detail.schedule.frequency': '重复', 'detail.schedule.scheduled': '等待触发', 'detail.schedule.overdue': '已到期,等待会话恢复', - 'detail.schedule.empty': '没有定时任务', + 'detail.schedule.active': '已开启', + 'detail.schedule.paused': '已暂停', + 'detail.schedule.ended': '已结束', + 'detail.schedule.empty': '没有自动化任务', 'detail.schedule.deleted': '已删除', - 'detail.schedule.count': '{count} 个定时任务', + 'detail.schedule.count': '{count} 个自动化任务', 'detail.schedule.daily': '每天 {time}({zone})', 'detail.schedule.weekly': '每周 {days} {time}({zone})', 'detail.schedule.cron': 'Cron {expression}({zone})', + 'detail.schedule.custom': '自定义', 'detail.weekday.1': '周一', 'detail.weekday.2': '周二', 'detail.weekday.3': '周三', @@ -158,6 +163,7 @@ export const zh = { 'tool.title.traceSession': '追踪会话', 'tool.title.listModels': '查看可用模型', 'tool.title.subagent': '创建子智能体', + 'tool.title.subagentFork': '派生子智能体', 'tool.title.listAgents': '查看子智能体', 'tool.title.sendMessage': '发送消息', 'tool.title.interruptAgent': '中断智能体', @@ -179,7 +185,7 @@ export const zh = { 'tool.title.getTeamTask': '读取团队任务', 'tool.title.updateTeamTask': '更新团队任务', 'tool.title.listTeamTasks': '查看团队任务', - 'tool.title.waitAgent': '等待子智能体', + 'tool.title.waitAgent': '等待消息…', 'detail.recordedResult': '调用结果', 'detail.empty': '暂无结果', 'detail.none': '无', @@ -236,11 +242,12 @@ export const zh = { 'detail.field.agents': '启动智能体数', 'detail.field.result': '结果', 'detail.field.parent': '父级', - 'detail.field.depth': '层级', 'detail.field.exitCode': '退出码', 'detail.field.signal': '信号', 'detail.field.previousStatus': '中断前状态', 'detail.field.agent': '智能体 ID', + 'detail.field.agentName': '智能体名称', + 'detail.field.agentDescription': '智能体任务描述', 'detail.field.job': '任务 ID', 'detail.field.task': '任务内容', 'detail.field.processGroup': '进程组', @@ -264,9 +271,9 @@ export const zh = { 'detail.receipt.closed': '已关闭', 'detail.receipt.closing': '关闭中', 'detail.wait.noProgress': '没有正在运行的子智能体', - 'detail.wait.title': '子智能体状态', - 'detail.wait.timeout': '等待超时', - 'detail.wait.changed': '检测到变化', + 'detail.wait.title': '等待结果', + 'detail.wait.timeout': '等待已超时', + 'detail.wait.ended': '等待已结束', 'detail.agent.reply': '智能体回复', 'detail.models.title': '可用模型', 'detail.output.lines': '第 {begin}–{end} 行,共 {total} 行', @@ -322,6 +329,7 @@ export const zh = { 'tool.title.bash': '运行命令', 'tool.title.write': '写入', 'tool.title.edit': '编辑', + 'tool.title.applyPatch': '应用补丁', 'tool.title.code': '代码', 'tool.title.generic': '工具调用', 'tool.title.inspect': '查询 Cordis 环境', @@ -403,7 +411,6 @@ export const en = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Message or run a task, / commands, @ files or sessions', 'placeholder.unavailable': 'Session unavailable', - 'placeholder.parentOffline': 'Parent session offline; sending is unavailable but you can still stop the run', 'placeholder.hero': 'Describe what you want to build, / commands, @ files or sessions', 'placeholder.workspace': 'Choose a workspace to start', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter steers all queued messages', @@ -476,10 +483,12 @@ export const en = { 'tool.title.getGoal': 'View goal', 'tool.title.updateGoal': 'Update goal', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Create reminder', - 'tool.title.listSchedules': 'List reminders', - 'tool.title.deleteSchedule': 'Delete reminder', - 'tool.title.updateSchedule': 'Update reminder', + 'tool.title.createSchedule': 'Create automation task', + 'tool.title.listSchedules': 'List automation tasks', + 'tool.title.viewSchedule': 'View automation task', + 'tool.title.editSchedule': 'Edit automation task', + 'tool.title.deleteSchedule': 'Delete automation task', + 'tool.title.updateSchedule': 'Update automation task', 'detail.state': 'Status', 'detail.todo.completed': 'Completed', 'detail.todo.in_progress': 'In progress', @@ -515,12 +524,16 @@ export const en = { 'detail.schedule.frequency': 'Repeat', 'detail.schedule.scheduled': 'Scheduled', 'detail.schedule.overdue': 'Overdue, awaiting session resume', - 'detail.schedule.empty': 'No reminders', + 'detail.schedule.active': 'Enabled', + 'detail.schedule.paused': 'Paused', + 'detail.schedule.ended': 'Ended', + 'detail.schedule.empty': 'No automation tasks', 'detail.schedule.deleted': 'Deleted', - 'detail.schedule.count': '{count} reminders', + 'detail.schedule.count': '{count} automation tasks', 'detail.schedule.daily': 'Every day at {time} ({zone})', 'detail.schedule.weekly': 'Weekly on {days} at {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'Custom', 'detail.weekday.1': 'Mon', 'detail.weekday.2': 'Tue', 'detail.weekday.3': 'Wed', @@ -541,6 +554,7 @@ export const en = { 'tool.title.traceSession': 'Trace session', 'tool.title.listModels': 'List models', 'tool.title.subagent': 'Create subagent', + 'tool.title.subagentFork': 'Fork subagent', 'tool.title.listAgents': 'List subagents', 'tool.title.sendMessage': 'Send message', 'tool.title.interruptAgent': 'Interrupt agent', @@ -562,7 +576,7 @@ export const en = { 'tool.title.getTeamTask': 'Read team task', 'tool.title.updateTeamTask': 'Update team task', 'tool.title.listTeamTasks': 'List team tasks', - 'tool.title.waitAgent': 'Wait for subagent', + 'tool.title.waitAgent': 'Waiting for messages…', 'detail.recordedResult': 'Recorded result', 'detail.empty': 'No results', 'detail.none': 'None', @@ -619,11 +633,12 @@ export const en = { 'detail.field.agents': 'Agents started', 'detail.field.result': 'Result', 'detail.field.parent': 'Parent', - 'detail.field.depth': 'Depth', 'detail.field.exitCode': 'Exit code', 'detail.field.signal': 'Signal', 'detail.field.previousStatus': 'Previous status', 'detail.field.agent': 'Agent ID', + 'detail.field.agentName': 'Agent name', + 'detail.field.agentDescription': 'Agent task description', 'detail.field.job': 'Job ID', 'detail.field.task': 'Task', 'detail.field.processGroup': 'Process group', @@ -647,9 +662,9 @@ export const en = { 'detail.receipt.closed': 'Closed', 'detail.receipt.closing': 'Closing', 'detail.wait.noProgress': 'No active subagents', - 'detail.wait.title': 'Subagent activity', + 'detail.wait.title': 'Wait result', 'detail.wait.timeout': 'Wait timed out', - 'detail.wait.changed': 'Change detected', + 'detail.wait.ended': 'Wait ended', 'detail.agent.reply': 'Agent response', 'detail.models.title': 'Available models', 'detail.output.lines': 'Lines {begin}–{end} of {total}', @@ -705,6 +720,7 @@ export const en = { 'tool.title.bash': 'Bash', 'tool.title.write': 'Write', 'tool.title.edit': 'Edit', + 'tool.title.applyPatch': 'Apply patch', 'tool.title.code': 'Code', 'tool.title.generic': 'Tool call', 'tool.title.inspect': 'Query Cordis environment', @@ -785,7 +801,6 @@ export const ja = { 'placeholder.plan': '計画を生成するにはタスクを説明してください', 'placeholder.default': 'メッセージを送信するかタスクを実行、/ コマンド、@ ファイルやセッション', 'placeholder.unavailable': 'セッションを利用できません', - 'placeholder.parentOffline': '親セッションがオフラインです。送信はできませんが、実行は停止できます', 'placeholder.hero': '作りたいものを説明してください。/ コマンド、@ ファイルやセッション', 'placeholder.workspace': '開始するワークスペースを選択', 'placeholder.steerQueue': 'Cmd/Ctrl+Enterでキュー内のすべてのメッセージを実行中の指示に追加', @@ -858,10 +873,12 @@ export const ja = { 'tool.title.getGoal': '目標を表示', 'tool.title.updateGoal': '目標を更新', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'リマインダーを作成', - 'tool.title.listSchedules': 'リマインダーを一覧表示', - 'tool.title.deleteSchedule': 'リマインダーを削除', - 'tool.title.updateSchedule': 'リマインダーを更新', + 'tool.title.createSchedule': '自動化タスクを作成', + 'tool.title.viewSchedule': '自動化タスクを表示', + 'tool.title.editSchedule': '自動化タスクを編集', + 'tool.title.listSchedules': '自動化タスクを一覧表示', + 'tool.title.deleteSchedule': '自動化タスクを削除', + 'tool.title.updateSchedule': '自動化タスクを更新', 'detail.state': 'ステータス', 'detail.todo.completed': '完了', 'detail.todo.in_progress': '進行中', @@ -895,14 +912,18 @@ export const ja = { 'detail.schedule.every': '{interval} ごと', 'detail.schedule.when': 'スケジュール設定', 'detail.schedule.frequency': '繰り返し', + 'detail.schedule.active': '有効', + 'detail.schedule.paused': '一時停止中', + 'detail.schedule.ended': '終了', 'detail.schedule.scheduled': 'スケジュール済み', 'detail.schedule.overdue': '期限超過、セッション再開待ち', - 'detail.schedule.empty': 'リマインダーなし', + 'detail.schedule.empty': '自動化タスクなし', 'detail.schedule.deleted': '削除済み', - 'detail.schedule.count': '{count}件のリマインダー', + 'detail.schedule.count': '{count}件の自動化タスク', 'detail.schedule.daily': '毎日 {time} ({zone})', 'detail.schedule.weekly': '毎週 {days} の {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'カスタム', 'detail.weekday.1': '月', 'detail.weekday.2': '火', 'detail.weekday.3': '水', @@ -923,6 +944,7 @@ export const ja = { 'tool.title.traceSession': 'セッションをトレース', 'tool.title.listModels': 'モデルを一覧表示', 'tool.title.subagent': 'サブエージェントを作成', + 'tool.title.subagentFork': 'サブエージェントを作成(コンテキストを継承)', 'tool.title.listAgents': 'サブエージェントを一覧表示', 'tool.title.sendMessage': 'メッセージを送信', 'tool.title.interruptAgent': 'エージェントを中断', @@ -944,7 +966,7 @@ export const ja = { 'tool.title.getTeamTask': 'チームタスクを読み取り', 'tool.title.updateTeamTask': 'チームタスクを更新', 'tool.title.listTeamTasks': 'チームタスクを一覧表示', - 'tool.title.waitAgent': 'サブエージェントを待機', + 'tool.title.waitAgent': 'メッセージを待機中…', 'detail.recordedResult': '記録された結果', 'detail.empty': '結果なし', 'detail.none': 'なし', @@ -1001,11 +1023,12 @@ export const ja = { 'detail.field.agents': '起動したエージェント', 'detail.field.result': '結果', 'detail.field.parent': '親', - 'detail.field.depth': '深さ', 'detail.field.exitCode': '終了コード', 'detail.field.signal': 'シグナル', 'detail.field.previousStatus': '以前のステータス', 'detail.field.agent': 'エージェント ID', + 'detail.field.agentName': 'エージェント名', + 'detail.field.agentDescription': 'エージェントのタスク説明', 'detail.field.job': 'ジョブ ID', 'detail.field.task': 'タスク', 'detail.field.processGroup': 'プロセスグループ', @@ -1031,7 +1054,7 @@ export const ja = { 'detail.wait.noProgress': 'アクティブなサブエージェントなし', 'detail.wait.title': 'サブエージェントのアクティビティ', 'detail.wait.timeout': '待機がタイムアウトしました', - 'detail.wait.changed': '変更を検出', + 'detail.wait.ended': '待機が終了しました', 'detail.agent.reply': 'エージェントの応答', 'detail.models.title': '利用可能なモデル', 'detail.output.lines': '{total} 行中 {begin}–{end} 行', @@ -1087,6 +1110,7 @@ export const ja = { 'tool.title.bash': 'Bash', 'tool.title.write': '書き込み', 'tool.title.edit': '編集', + 'tool.title.applyPatch': 'パッチを適用', 'tool.title.code': 'コード', 'tool.title.generic': 'ツール呼び出し', 'tool.title.inspect': 'Cordis 環境を照会', @@ -1165,7 +1189,6 @@ export const es = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Envía mensajes o ejecuta una tarea, / comandos, @ archivos o sesiones', 'placeholder.unavailable': 'Sesión no disponible', - 'placeholder.parentOffline': 'Sesión para padres sin conexión; El envío no está disponible pero aún puedes detener la ejecución.', 'placeholder.hero': 'Describe lo que quieres construir, / comandos, @ archivos o sesiones', 'placeholder.workspace': 'Elija un espacio de trabajo para comenzar', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter dirige todos los mensajes en cola', @@ -1238,10 +1261,10 @@ export const es = { 'tool.title.getGoal': 'Ver objetivo', 'tool.title.updateGoal': 'Actualizar objetivo', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Crear recordatorio', - 'tool.title.listSchedules': 'Recordatorios de lista', - 'tool.title.deleteSchedule': 'Eliminar recordatorio', - 'tool.title.updateSchedule': 'Recordatorio de actualización', + 'tool.title.createSchedule': 'Crear tarea de automatización', + 'tool.title.listSchedules': 'Listar tareas de automatización', + 'tool.title.deleteSchedule': 'Eliminar tarea de automatización', + 'tool.title.updateSchedule': 'Actualizar tarea de automatización', 'detail.state': 'Estado', 'detail.todo.completed': 'Completado', 'detail.todo.in_progress': 'En progreso', @@ -1277,12 +1300,13 @@ export const es = { 'detail.schedule.frequency': 'repetir', 'detail.schedule.scheduled': 'Programado', 'detail.schedule.overdue': 'Atrasado, a la espera de reanudar la sesión.', - 'detail.schedule.empty': 'Sin recordatorios', + 'detail.schedule.empty': 'Sin tareas de automatización', 'detail.schedule.deleted': 'Eliminado', - 'detail.schedule.count': 'Recordatorios de {count}', + 'detail.schedule.count': '{count} tareas de automatización', 'detail.schedule.daily': 'Todos los días en {time} ({zone})', 'detail.schedule.weekly': 'Semanalmente en {days} en {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'Personalizado', 'detail.weekday.1': 'lun', 'detail.weekday.2': 'mar', 'detail.weekday.3': 'mié', @@ -1303,6 +1327,7 @@ export const es = { 'tool.title.traceSession': 'Sesión de seguimiento', 'tool.title.listModels': 'Listar modelos', 'tool.title.subagent': 'Crear subagente', + 'tool.title.subagentFork': 'Crear subagente (heredar contexto)', 'tool.title.listAgents': 'Listar subagentes', 'tool.title.sendMessage': 'Enviar mensaje', 'tool.title.interruptAgent': 'agente de interrupción', @@ -1324,7 +1349,7 @@ export const es = { 'tool.title.getTeamTask': 'Leer tarea de equipo', 'tool.title.updateTeamTask': 'Actualizar tarea de equipo', 'tool.title.listTeamTasks': 'Listar tareas del equipo', - 'tool.title.waitAgent': 'Espere al subagente', + 'tool.title.waitAgent': 'Esperando mensajes…', 'detail.recordedResult': 'Resultado registrado', 'detail.empty': 'Sin resultados', 'detail.none': 'Ninguno', @@ -1381,11 +1406,12 @@ export const es = { 'detail.field.agents': 'Los agentes comenzaron', 'detail.field.result': 'Resultado', 'detail.field.parent': 'Padre', - 'detail.field.depth': 'Profundidad', 'detail.field.exitCode': 'código de salida', 'detail.field.signal': 'señal', 'detail.field.previousStatus': 'Estado anterior', 'detail.field.agent': 'ID del agente', + 'detail.field.agentName': 'Nombre del agente', + 'detail.field.agentDescription': 'Descripción de la tarea del agente', 'detail.field.job': 'ID de trabajo', 'detail.field.task': 'Tarea', 'detail.field.processGroup': 'grupo de procesos', @@ -1411,7 +1437,7 @@ export const es = { 'detail.wait.noProgress': 'No hay subagentes activos', 'detail.wait.title': 'Actividad del subagente', 'detail.wait.timeout': 'Se agotó el tiempo de espera', - 'detail.wait.changed': 'Cambio detectado', + 'detail.wait.ended': 'Espera finalizada', 'detail.agent.reply': 'Respuesta del agente', 'detail.models.title': 'Modelos disponibles', 'detail.output.lines': 'Líneas {begin}–{end} de {total}', @@ -1467,6 +1493,7 @@ export const es = { 'tool.title.bash': 'golpe', 'tool.title.write': 'escribir', 'tool.title.edit': 'Editar', + 'tool.title.applyPatch': 'Aplicar parche', 'tool.title.code': 'Código', 'tool.title.generic': 'llamada de herramienta', 'tool.title.inspect': 'Consulta entorno Cordis', @@ -1532,6 +1559,11 @@ export const es = { // aligned with these English values. 'terminal.sendInput': '(enviar entrada)', 'terminal.session': 'Terminal {sessionId}', + 'tool.title.viewSchedule': 'Ver tarea de automatización', + 'tool.title.editSchedule': 'Editar tarea de automatización', + 'detail.schedule.active': 'Habilitado', + 'detail.schedule.paused': 'Pausada', + 'detail.schedule.ended': 'Finalizada', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -1547,7 +1579,6 @@ export const fr = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Envoyez un message ou exécutez une tâche, des commandes /, des fichiers @ ou des sessions', 'placeholder.unavailable': 'Séance indisponible', - 'placeholder.parentOffline': "Session parent hors ligne ; l'envoi n'est pas disponible mais vous pouvez toujours arrêter l'exécution", 'placeholder.hero': 'Décrivez ce que vous souhaitez construire, / commandes, @ fichiers ou sessions', 'placeholder.workspace': 'Choisissez un espace de travail pour commencer', 'placeholder.steerQueue': "Cmd/Ctrl+Entrée dirige tous les messages en file d'attente", @@ -1620,10 +1651,10 @@ export const fr = { 'tool.title.getGoal': "Afficher l'objectif", 'tool.title.updateGoal': 'Objectif de mise à jour', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Créer un rappel', - 'tool.title.listSchedules': 'Liste des rappels', - 'tool.title.deleteSchedule': 'Supprimer le rappel', - 'tool.title.updateSchedule': 'Rappel de mise à jour', + 'tool.title.createSchedule': 'Créer une tâche d\'automatisation', + 'tool.title.listSchedules': 'Lister les tâches d\'automatisation', + 'tool.title.deleteSchedule': 'Supprimer la tâche d\'automatisation', + 'tool.title.updateSchedule': 'Mettre à jour la tâche d\'automatisation', 'detail.state': 'Statut', 'detail.todo.completed': 'Terminé', 'detail.todo.in_progress': 'En cours', @@ -1659,12 +1690,13 @@ export const fr = { 'detail.schedule.frequency': 'Répéter', 'detail.schedule.scheduled': 'Programmé', 'detail.schedule.overdue': 'En retard, en attente de reprise de la session', - 'detail.schedule.empty': 'Aucun rappel', + 'detail.schedule.empty': 'Aucune tâche d\'automatisation', 'detail.schedule.deleted': 'Supprimé', - 'detail.schedule.count': 'Rappels {count}', + 'detail.schedule.count': '{count} tâches d\'automatisation', 'detail.schedule.daily': 'Tous les jours à {time} ({zone})', 'detail.schedule.weekly': 'Hebdomadaire sur {days} à {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'Personnalisé', 'detail.weekday.1': 'lundi', 'detail.weekday.2': 'mar.', 'detail.weekday.3': 'mer', @@ -1685,6 +1717,7 @@ export const fr = { 'tool.title.traceSession': 'Session de traçage', 'tool.title.listModels': 'Liste des modèles', 'tool.title.subagent': 'Créer un sous-agent', + 'tool.title.subagentFork': 'Créer un sous-agent (hériter du contexte)', 'tool.title.listAgents': 'Liste des sous-agents', 'tool.title.sendMessage': 'Envoyer le message', 'tool.title.interruptAgent': "Agent d'interruption", @@ -1706,7 +1739,7 @@ export const fr = { 'tool.title.getTeamTask': "Lire la tâche d'équipe", 'tool.title.updateTeamTask': "Mettre à jour la tâche de l'équipe", 'tool.title.listTeamTasks': "Répertorier les tâches de l'équipe", - 'tool.title.waitAgent': 'Attendez le sous-agent', + 'tool.title.waitAgent': 'En attente de messages…', 'detail.recordedResult': 'Résultat enregistré', 'detail.empty': 'Aucun résultat', 'detail.none': 'Aucun', @@ -1763,11 +1796,12 @@ export const fr = { 'detail.field.agents': 'Les agents ont commencé', 'detail.field.result': 'Résultat', 'detail.field.parent': 'Parent', - 'detail.field.depth': 'Profondeur', 'detail.field.exitCode': 'Code de sortie', 'detail.field.signal': 'Signal', 'detail.field.previousStatus': 'Statut précédent', 'detail.field.agent': "ID d'agent", + 'detail.field.agentName': 'Nom de l’agent', + 'detail.field.agentDescription': 'Description de la tâche de l’agent', 'detail.field.job': 'ID de travail', 'detail.field.task': 'Tâche', 'detail.field.processGroup': 'Groupe de processus', @@ -1793,7 +1827,7 @@ export const fr = { 'detail.wait.noProgress': 'Aucun sous-agent actif', 'detail.wait.title': 'Activité du sous-agent', 'detail.wait.timeout': "Le délai d'attente a expiré", - 'detail.wait.changed': 'Changement détecté', + 'detail.wait.ended': 'Attente terminée', 'detail.agent.reply': "Réponse de l'agent", 'detail.models.title': 'Modèles disponibles', 'detail.output.lines': 'Lignes {begin}–{end} de {total}', @@ -1849,6 +1883,7 @@ export const fr = { 'tool.title.bash': 'Frapper', 'tool.title.write': 'Écrire', 'tool.title.edit': 'Modifier', + 'tool.title.applyPatch': 'Appliquer le patch', 'tool.title.code': 'Coder', 'tool.title.generic': "Appel d'outil", 'tool.title.inspect': "Interroger l'environnement Cordis", @@ -1914,6 +1949,11 @@ export const fr = { // aligned with these English values. 'terminal.sendInput': '(envoyer une entrée)', 'terminal.session': 'Borne {sessionId}', + 'tool.title.viewSchedule': 'Voir la tâche d\'automatisation', + 'tool.title.editSchedule': 'Modifier la tâche d\'automatisation', + 'detail.schedule.active': 'Activé', + 'detail.schedule.paused': 'Suspendue', + 'detail.schedule.ended': 'Terminée', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -1929,7 +1969,6 @@ export const de = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Senden Sie eine Nachricht oder führen Sie eine Aufgabe, /-Befehle, @-Dateien oder Sitzungen aus', 'placeholder.unavailable': 'Sitzung nicht verfügbar', - 'placeholder.parentOffline': 'Elternsitzung offline; Das Senden ist nicht möglich, aber Sie können den Lauf trotzdem stoppen', 'placeholder.hero': 'Beschreiben Sie, was Sie erstellen möchten: /-Befehle, @-Dateien oder Sitzungen', 'placeholder.workspace': 'Wählen Sie einen Arbeitsbereich zum Starten aus', 'placeholder.steerQueue': 'Cmd/Strg+Enter steuert alle Nachrichten in der Warteschlange', @@ -2002,10 +2041,10 @@ export const de = { 'tool.title.getGoal': 'Ziel ansehen', 'tool.title.updateGoal': 'Ziel aktualisieren', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Erinnerung erstellen', - 'tool.title.listSchedules': 'Listen Sie Erinnerungen auf', - 'tool.title.deleteSchedule': 'Erinnerung löschen', - 'tool.title.updateSchedule': 'Update-Erinnerung', + 'tool.title.createSchedule': 'Automatisierungsaufgabe erstellen', + 'tool.title.listSchedules': 'Automatisierungsaufgaben auflisten', + 'tool.title.deleteSchedule': 'Automatisierungsaufgabe löschen', + 'tool.title.updateSchedule': 'Automatisierungsaufgabe aktualisieren', 'detail.state': 'Status', 'detail.todo.completed': 'Abgeschlossen', 'detail.todo.in_progress': 'In Bearbeitung', @@ -2041,12 +2080,13 @@ export const de = { 'detail.schedule.frequency': 'Wiederholen', 'detail.schedule.scheduled': 'Geplant', 'detail.schedule.overdue': 'Überfällig, ich warte auf die Fortsetzung der Sitzung', - 'detail.schedule.empty': 'Keine Erinnerungen', + 'detail.schedule.empty': 'Keine Automatisierungsaufgaben', 'detail.schedule.deleted': 'Gelöscht', - 'detail.schedule.count': '{count} Erinnerungen', + 'detail.schedule.count': '{count} Automatisierungsaufgaben', 'detail.schedule.daily': 'Täglich um {time} ({zone})', 'detail.schedule.weekly': 'Wöchentlich auf {days} um {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'Benutzerdefiniert', 'detail.weekday.1': 'Mo', 'detail.weekday.2': 'Di', 'detail.weekday.3': 'Mi', @@ -2067,6 +2107,7 @@ export const de = { 'tool.title.traceSession': 'Trace-Sitzung', 'tool.title.listModels': 'Modelle auflisten', 'tool.title.subagent': 'Subagent erstellen', + 'tool.title.subagentFork': 'Subagent erstellen (Kontext übernehmen)', 'tool.title.listAgents': 'Subagenten auflisten', 'tool.title.sendMessage': 'Nachricht senden', 'tool.title.interruptAgent': 'Interrupt-Agent', @@ -2088,7 +2129,7 @@ export const de = { 'tool.title.getTeamTask': 'Teamaufgabe lesen', 'tool.title.updateTeamTask': 'Teamaufgabe aktualisieren', 'tool.title.listTeamTasks': 'Teamaufgaben auflisten', - 'tool.title.waitAgent': 'Warten Sie auf den Subagenten', + 'tool.title.waitAgent': 'Warten auf Nachrichten…', 'detail.recordedResult': 'Aufgezeichnetes Ergebnis', 'detail.empty': 'Keine Ergebnisse', 'detail.none': 'Keine', @@ -2145,11 +2186,12 @@ export const de = { 'detail.field.agents': 'Agenten begannen', 'detail.field.result': 'Ergebnis', 'detail.field.parent': 'Eltern', - 'detail.field.depth': 'Tiefe', 'detail.field.exitCode': 'Exit-Code', 'detail.field.signal': 'Signal', 'detail.field.previousStatus': 'Vorheriger Stand', 'detail.field.agent': 'Agenten-ID', + 'detail.field.agentName': 'Agentenname', + 'detail.field.agentDescription': 'Aufgabenbeschreibung des Agenten', 'detail.field.job': 'Job-ID', 'detail.field.task': 'Aufgabe', 'detail.field.processGroup': 'Prozessgruppe', @@ -2175,7 +2217,7 @@ export const de = { 'detail.wait.noProgress': 'Keine aktiven Subagenten', 'detail.wait.title': 'Aktivität des Subagenten', 'detail.wait.timeout': 'Wartezeit abgelaufen', - 'detail.wait.changed': 'Änderung erkannt', + 'detail.wait.ended': 'Warten beendet', 'detail.agent.reply': 'Antwort des Agenten', 'detail.models.title': 'Verfügbare Modelle', 'detail.output.lines': 'Linien {begin}–{end} von {total}', @@ -2231,6 +2273,7 @@ export const de = { 'tool.title.bash': 'Bash', 'tool.title.write': 'Schreiben', 'tool.title.edit': 'Bearbeiten', + 'tool.title.applyPatch': 'Patch anwenden', 'tool.title.code': 'Code', 'tool.title.generic': 'Werkzeugaufruf', 'tool.title.inspect': 'Fragen Sie die Cordis-Umgebung ab', @@ -2296,6 +2339,11 @@ export const de = { // aligned with these English values. 'terminal.sendInput': '(Eingabe senden)', 'terminal.session': 'Terminal {sessionId}', + 'tool.title.viewSchedule': 'Automatisierungsaufgabe anzeigen', + 'tool.title.editSchedule': 'Automatisierungsaufgabe bearbeiten', + 'detail.schedule.active': 'Aktiviert', + 'detail.schedule.paused': 'Pausiert', + 'detail.schedule.ended': 'Beendet', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -2311,7 +2359,6 @@ export const ru = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Отправьте сообщение или запустите задачу, /команды, @файлы или сеансы', 'placeholder.unavailable': 'Сеанс недоступен', - 'placeholder.parentOffline': 'Родительская сессия в автономном режиме; отправка недоступна, но вы все равно можете остановить запуск', 'placeholder.hero': 'Опишите, что вы хотите построить: /команды, @файлы или сеансы.', 'placeholder.workspace': 'Выберите рабочее пространство для начала', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter управляет всеми сообщениями в очереди.', @@ -2384,10 +2431,10 @@ export const ru = { 'tool.title.getGoal': 'Посмотреть цель', 'tool.title.updateGoal': 'Обновить цель', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Создать напоминание', - 'tool.title.listSchedules': 'Список напоминаний', - 'tool.title.deleteSchedule': 'Удалить напоминание', - 'tool.title.updateSchedule': 'Обновить напоминание', + 'tool.title.createSchedule': 'Создать задачу автоматизации', + 'tool.title.listSchedules': 'Показать задачи автоматизации', + 'tool.title.deleteSchedule': 'Удалить задачу автоматизации', + 'tool.title.updateSchedule': 'Обновить задачу автоматизации', 'detail.state': 'Статус', 'detail.todo.completed': 'Завершено', 'detail.todo.in_progress': 'В процессе', @@ -2423,12 +2470,13 @@ export const ru = { 'detail.schedule.frequency': 'Повторить', 'detail.schedule.scheduled': 'Запланировано', 'detail.schedule.overdue': 'Просрочено, ждём возобновления сеанса', - 'detail.schedule.empty': 'Нет напоминаний', + 'detail.schedule.empty': 'Нет задач автоматизации', 'detail.schedule.deleted': 'Удалено', - 'detail.schedule.count': '{count} напоминания', + 'detail.schedule.count': '{count} задачи автоматизации', 'detail.schedule.daily': 'Каждый день в {time} ({zone})', 'detail.schedule.weekly': 'Еженедельно на {days} по адресу {time} ({zone})', 'detail.schedule.cron': 'Крон {expression} ({zone})', + 'detail.schedule.custom': 'Произвольно', 'detail.weekday.1': 'Пн.', 'detail.weekday.2': 'Вт', 'detail.weekday.3': 'ср.', @@ -2449,6 +2497,7 @@ export const ru = { 'tool.title.traceSession': 'Трассировка сеанса', 'tool.title.listModels': 'Список моделей', 'tool.title.subagent': 'Создать субагент', + 'tool.title.subagentFork': 'Создать субагент (наследовать контекст)', 'tool.title.listAgents': 'Список субагентов', 'tool.title.sendMessage': 'Отправить сообщение', 'tool.title.interruptAgent': 'Агент прерываний', @@ -2470,7 +2519,7 @@ export const ru = { 'tool.title.getTeamTask': 'Прочитать командное задание', 'tool.title.updateTeamTask': 'Обновить групповую задачу', 'tool.title.listTeamTasks': 'Перечислить командные задачи', - 'tool.title.waitAgent': 'Подождите субагента', + 'tool.title.waitAgent': 'Ожидание сообщений…', 'detail.recordedResult': 'Записанный результат', 'detail.empty': 'Нет результатов', 'detail.none': 'Нет', @@ -2527,11 +2576,12 @@ export const ru = { 'detail.field.agents': 'Агенты запущены', 'detail.field.result': 'Результат', 'detail.field.parent': 'Родитель', - 'detail.field.depth': 'Глубина', 'detail.field.exitCode': 'Код выхода', 'detail.field.signal': 'Сигнал', 'detail.field.previousStatus': 'Предыдущий статус', 'detail.field.agent': 'Идентификатор агента', + 'detail.field.agentName': 'Имя агента', + 'detail.field.agentDescription': 'Описание задачи агента', 'detail.field.job': 'Идентификатор вакансии', 'detail.field.task': 'Задача', 'detail.field.processGroup': 'Группа процессов', @@ -2557,7 +2607,7 @@ export const ru = { 'detail.wait.noProgress': 'Нет активных субагентов', 'detail.wait.title': 'Субагентская деятельность', 'detail.wait.timeout': 'Время ожидания истекло', - 'detail.wait.changed': 'Обнаружено изменение', + 'detail.wait.ended': 'Ожидание завершено', 'detail.agent.reply': 'Ответ агента', 'detail.models.title': 'Доступные модели', 'detail.output.lines': 'Линии {begin} – {end} из {total}', @@ -2613,6 +2663,7 @@ export const ru = { 'tool.title.bash': 'Баш', 'tool.title.write': 'Написать', 'tool.title.edit': 'Редактировать', + 'tool.title.applyPatch': 'Применить патч', 'tool.title.code': 'Код', 'tool.title.generic': 'Вызов инструмента', 'tool.title.inspect': 'Запрос среды Cordis', @@ -2678,6 +2729,11 @@ export const ru = { // aligned with these English values. 'terminal.sendInput': '(отправить ввод)', 'terminal.session': 'Терминал {sessionId}', + 'tool.title.viewSchedule': 'Посмотреть задачу автоматизации', + 'tool.title.editSchedule': 'Изменить задачу автоматизации', + 'detail.schedule.active': 'Включено', + 'detail.schedule.paused': 'Приостановлена', + 'detail.schedule.ended': 'Завершена', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -2693,7 +2749,6 @@ export const pt = { 'placeholder.plan': PLAN_NEXT_ACTION_EN, 'placeholder.default': 'Envie mensagens ou execute uma tarefa, / comandos, @ arquivos ou sessões', 'placeholder.unavailable': 'Sessão indisponível', - 'placeholder.parentOffline': 'Sessão pai offline; o envio não está disponível, mas você ainda pode interromper a execução', 'placeholder.hero': 'Descreva o que você deseja construir, / comandos, @ arquivos ou sessões', 'placeholder.workspace': 'Escolha um espaço de trabalho para começar', 'placeholder.steerQueue': 'Cmd/Ctrl+Enter direciona todas as mensagens na fila', @@ -2766,10 +2821,10 @@ export const pt = { 'tool.title.getGoal': 'Ver meta', 'tool.title.updateGoal': 'Atualizar meta', 'tool.preparing.content': '{kilobytes}KB', - 'tool.title.createSchedule': 'Criar lembrete', - 'tool.title.listSchedules': 'Listar lembretes', - 'tool.title.deleteSchedule': 'Excluir lembrete', - 'tool.title.updateSchedule': 'Lembrete de atualização', + 'tool.title.createSchedule': 'Criar tarefa de automação', + 'tool.title.listSchedules': 'Listar tarefas de automação', + 'tool.title.deleteSchedule': 'Excluir tarefa de automação', + 'tool.title.updateSchedule': 'Atualizar tarefa de automação', 'detail.state': 'Estado', 'detail.todo.completed': 'Concluído', 'detail.todo.in_progress': 'Em andamento', @@ -2805,12 +2860,13 @@ export const pt = { 'detail.schedule.frequency': 'Repetir', 'detail.schedule.scheduled': 'Agendado', 'detail.schedule.overdue': 'Atrasado, aguardando retomada da sessão', - 'detail.schedule.empty': 'Sem lembretes', + 'detail.schedule.empty': 'Sem tarefas de automação', 'detail.schedule.deleted': 'Excluído', - 'detail.schedule.count': '{count} lembretes', + 'detail.schedule.count': '{count} tarefas de automação', 'detail.schedule.daily': 'Todos os dias às {time} ({zone})', 'detail.schedule.weekly': 'Semanalmente em {days} às {time} ({zone})', 'detail.schedule.cron': 'Cron {expression} ({zone})', + 'detail.schedule.custom': 'Personalizado', 'detail.weekday.1': 'segunda-feira', 'detail.weekday.2': 'Terça', 'detail.weekday.3': 'Quarta', @@ -2831,6 +2887,7 @@ export const pt = { 'tool.title.traceSession': 'Sessão de rastreamento', 'tool.title.listModels': 'Listar modelos', 'tool.title.subagent': 'Criar subagente', + 'tool.title.subagentFork': 'Criar subagente (herdar contexto)', 'tool.title.listAgents': 'Listar subagentes', 'tool.title.sendMessage': 'Enviar mensagem', 'tool.title.interruptAgent': 'Agente de interrupção', @@ -2852,7 +2909,7 @@ export const pt = { 'tool.title.getTeamTask': 'Ler tarefa da equipe', 'tool.title.updateTeamTask': 'Atualizar tarefa da equipe', 'tool.title.listTeamTasks': 'Listar tarefas da equipe', - 'tool.title.waitAgent': 'Aguarde o subagente', + 'tool.title.waitAgent': 'Aguardando mensagens…', 'detail.recordedResult': 'Resultado registrado', 'detail.empty': 'Nenhum resultado', 'detail.none': 'Nenhum', @@ -2909,11 +2966,12 @@ export const pt = { 'detail.field.agents': 'Agentes iniciados', 'detail.field.result': 'Resultado', 'detail.field.parent': 'Pai', - 'detail.field.depth': 'Profundidade', 'detail.field.exitCode': 'Código de saída', 'detail.field.signal': 'Sinal', 'detail.field.previousStatus': 'Estado anterior', 'detail.field.agent': 'ID do agente', + 'detail.field.agentName': 'Nome do agente', + 'detail.field.agentDescription': 'Descrição da tarefa do agente', 'detail.field.job': 'ID do trabalho', 'detail.field.task': 'Tarefa', 'detail.field.processGroup': 'Grupo de processos', @@ -2939,7 +2997,7 @@ export const pt = { 'detail.wait.noProgress': 'Nenhum subagente ativo', 'detail.wait.title': 'Atividade do subagente', 'detail.wait.timeout': 'A espera expirou', - 'detail.wait.changed': 'Alteração detectada', + 'detail.wait.ended': 'Espera encerrada', 'detail.agent.reply': 'Resposta do agente', 'detail.models.title': 'Modelos disponíveis', 'detail.output.lines': 'Linhas {begin}–{end} de {total}', @@ -2995,6 +3053,7 @@ export const pt = { 'tool.title.bash': 'Bash', 'tool.title.write': 'Escreva', 'tool.title.edit': 'Editar', + 'tool.title.applyPatch': 'Aplicar patch', 'tool.title.code': 'Código', 'tool.title.generic': 'Chamada de ferramenta', 'tool.title.inspect': 'Consultar ambiente Cordis', @@ -3060,4 +3119,9 @@ export const pt = { // aligned with these English values. 'terminal.sendInput': '(enviar entrada)', 'terminal.session': 'Terminal {sessionId}', + 'tool.title.viewSchedule': 'Ver tarefa de automação', + 'tool.title.editSchedule': 'Editar tarefa de automação', + 'detail.schedule.active': 'Habilitado', + 'detail.schedule.paused': 'Pausada', + 'detail.schedule.ended': 'Concluída', } satisfies Record diff --git a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css index 9590df492a..a563c66d1b 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css +++ b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.module.css @@ -65,6 +65,12 @@ line-height: 20px; color: var(--dsw-alias-label-secondary); cursor: default; + max-width: var(--dsh-anchored-max-width, none); + max-height: var(--dsh-anchored-max-height, none); + overflow-x: hidden; + overflow-y: auto; + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } .header { diff --git a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.tsx b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.tsx index 4af5274b8a..85698e1ccb 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ContextMeter.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ContextMeter.tsx @@ -107,7 +107,7 @@ export function ContextMeter({ useProjection, t }: ContextMeterProps) { return ( - + + + + + {liveRows.length > 0 && } {open ? createPortal( - + { changeOpen(true) }} + onFocusCapture={() => { changeOpen(true) }} + >
      {liveRows.length > 0 ? diff --git a/packages/client/ui-jobs/src/client/locales.ts b/packages/client/ui-jobs/src/client/locales.ts index 700009d9a5..c968a08b5d 100644 --- a/packages/client/ui-jobs/src/client/locales.ts +++ b/packages/client/ui-jobs/src/client/locales.ts @@ -5,8 +5,6 @@ export const NS = 'job' /** Simplified Chinese dictionary (the key-set source of truth). */ export const zh = { - 'count.live.one': '{count} 个后台任务运行中', - 'count.live.other': '{count} 个后台任务运行中', 'count.idle.one': '{count} 个后台任务', 'count.idle.other': '{count} 个后台任务', 'list.aria': '后台任务', @@ -49,8 +47,6 @@ export const zh = { /** English dictionary, key-identical to the Chinese source of truth. */ export const en: Record = { - 'count.live.one': '{count} background job running', - 'count.live.other': '{count} background jobs running', 'count.idle.one': '{count} background job', 'count.idle.other': '{count} background jobs', 'list.aria': 'Background jobs', @@ -96,8 +92,6 @@ export type JobKey = keyof typeof zh /** Japanese copy, checked against the English keys. */ export const ja = { - 'count.live.one': 'バックグラウンドジョブ {count} 件が実行中', - 'count.live.other': 'バックグラウンドジョブ {count} 件が実行中', 'count.idle.one': 'バックグラウンドジョブ {count} 件', 'count.idle.other': 'バックグラウンドジョブ {count} 件', 'list.aria': 'バックグラウンドジョブ', @@ -140,8 +134,6 @@ export const ja = { /** Spanish dictionary, checked against the English keys. */ export const es = { - 'count.live.one': 'Tareas en segundo plano en ejecución: {count}', - 'count.live.other': 'Tareas en segundo plano en ejecución: {count}', 'count.idle.one': 'Tareas en segundo plano: {count}', 'count.idle.other': 'Tareas en segundo plano: {count}', 'list.aria': 'Trabajos en segundo plano', @@ -184,8 +176,6 @@ export const es = { /** French dictionary, checked against the English keys. */ export const fr = { - 'count.live.one': 'Tâches en arrière-plan en cours : {count}', - 'count.live.other': 'Tâches en arrière-plan en cours : {count}', 'count.idle.one': 'Tâches en arrière-plan : {count}', 'count.idle.other': 'Tâches en arrière-plan : {count}', 'list.aria': 'Travaux en arrière-plan', @@ -228,8 +218,6 @@ export const fr = { /** German dictionary, checked against the English keys. */ export const de = { - 'count.live.one': 'Laufende Hintergrundaufgaben: {count}', - 'count.live.other': 'Laufende Hintergrundaufgaben: {count}', 'count.idle.one': 'Hintergrundaufgaben: {count}', 'count.idle.other': 'Hintergrundaufgaben: {count}', 'list.aria': 'Hintergrundjobs', @@ -272,8 +260,6 @@ export const de = { /** Russian dictionary, checked against the English keys. */ export const ru = { - 'count.live.one': 'Фоновые задачи выполняются: {count}', - 'count.live.other': 'Фоновые задачи выполняются: {count}', 'count.idle.one': 'Фоновые задачи: {count}', 'count.idle.other': 'Фоновые задачи: {count}', 'list.aria': 'Фоновые задания', @@ -316,8 +302,6 @@ export const ru = { /** Portuguese dictionary, checked against the English keys. */ export const pt = { - 'count.live.one': 'Tarefas em segundo plano em execução: {count}', - 'count.live.other': 'Tarefas em segundo plano em execução: {count}', 'count.idle.one': 'Tarefas em segundo plano: {count}', 'count.idle.other': 'Tarefas em segundo plano: {count}', 'list.aria': 'Trabalhos em segundo plano', diff --git a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx index 4dcf892f87..c8ee1a0e6a 100644 --- a/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx +++ b/packages/client/ui-jobs/tests/job-list-action.client.spec.tsx @@ -1,11 +1,31 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it, vi } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react' import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' import type { JobsSnapshot, JobView, ObservedJob } from '@deepseek-ai/dsh-api-job-controller/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { JobListAction, type JobListActionProps } from '../src/client/JobListAction.tsx' -import { zh, ru } from '../src/client/locales.ts' +import { zh, en, ja, es, fr, de, ru, pt } from '../src/client/locales.ts' + +beforeEach(() => { + class TooltipObserver implements ResizeObserver { + constructor(private readonly callback: ResizeObserverCallback) {} + observe(target: Element): void { + const size = { inlineSize: 160, blockSize: 30 } + this.callback([{ + target, borderBoxSize: [size], contentBoxSize: [size], devicePixelContentBoxSize: [size], contentRect: new DOMRect(), + }], this) + } + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', TooltipObserver) + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) +}) + +beforeEach(() => { + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) +}) afterEach(() => { cleanup() @@ -53,6 +73,28 @@ function openList(): void { fireEvent.click(screen.getAllByRole('button')[0]!) } +describe('JobListAction count copy', () => { + it.each([ + [zh, '1 个后台任务', '2 个后台任务'], + [en, '1 background job', '2 background jobs'], + [ja, 'バックグラウンドジョブ 1 件', 'バックグラウンドジョブ 2 件'], + [es, 'Tareas en segundo plano: 1', 'Tareas en segundo plano: 2'], + [fr, 'Tâches en arrière-plan : 1', 'Tâches en arrière-plan : 2'], + [de, 'Hintergrundaufgaben: 1', 'Hintergrundaufgaben: 2'], + [ru, 'Фоновые задачи: 1', 'Фоновые задачи: 2'], + [pt, 'Tarefas em segundo plano: 1', 'Tarefas em segundo plano: 2'], + ] as const)('uses neutral count copy for live and settled jobs in locale %#', (dictionary, one, two) => { + const translate: JobListActionProps['t'] = makeTranslate(dictionary) + const settled = job({ id: 'settled' as JobView['id'], status: 'completed', finishedAt: 1_700_000_003_000 }) + const { rerender } = render() + expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() + rerender() + expect(screen.getByRole('button', { name: one, description: dictionary['section.live'] })).toBeDefined() + rerender() + expect(screen.getByRole('button', { name: two, description: '' })).toBeDefined() + }) +}) + describe('JobListAction visibility', () => { it('renders nothing while the session sees no jobs', () => { const { container } = render() @@ -74,7 +116,24 @@ describe('JobListAction visibility', () => { outputJob(), job({ id: 'subagent-1' as JobView['id'], kind: 'subagent', label: 'explore' }), ])} />) - expect(screen.getByRole('button', { name: '2 个后台任务运行中' })).toBeDefined() + expect(screen.getByRole('button', { name: '2 个后台任务' })).toBeDefined() + }) + + it('retains the compact Layers icon through running, stopping, and idle states without a root chevron', () => { + const { rerender } = render() + const trigger = screen.getByRole('button') + expect(trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]')).not.toBeNull() + expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() + expect(trigger.querySelector('[data-icon="dsw-icon-chevron-down-outline-regular"]')).toBeNull() + rerender() + expect(screen.getByRole('button')).toBe(trigger) + expect(trigger.querySelector('[data-state="ongoing"]')).not.toBeNull() + rerender() + expect(screen.getByRole('button')).toBe(trigger) + expect(trigger.querySelector('[data-state="ongoing"]')).toBeNull() + const icon = trigger.querySelector('[data-icon="dsw-icon-layers-outline-regular"]') + expect(icon?.getAttribute('width')).toBe('14') + expect(trigger.querySelectorAll('svg')).toHaveLength(1) }) it('falls back to the total when nothing is live', () => { @@ -85,6 +144,281 @@ describe('JobListAction visibility', () => { }) }) +describe('JobListAction hover', () => { + function pointer(target: Element, type: 'pointerover' | 'pointerout', pointerType = 'mouse'): void { + // jsdom lacks PointerEvent; preserve its pointer type on the native event. + const event = new MouseEvent(type, { bubbles: true }) + Object.defineProperty(event, 'pointerType', { value: pointerType }) + fireEvent(target, event) + } + + function advance(ms: number): void { + act(() => { vi.advanceTimersByTime(ms) }) + } + + function hoverOpen(): HTMLElement { + const trigger = screen.getByRole('button', { name: '1 个后台任务' }) + pointer(trigger, 'pointerover') + advance(149) + expect(screen.queryByRole('list')).toBeNull() + advance(1) + expect(trigger.getAttribute('aria-expanded')).toBe('true') + return trigger + } + + it('keeps the compact trigger click-only and shows its count tooltip after 500ms', () => { + vi.useFakeTimers() + render() + const trigger = screen.getByRole('button') + const count = trigger.querySelector('[data-job-count]')! + count.style.display = 'none' + pointer(trigger, 'pointerover') + advance(499) + expect(screen.queryByRole('list')).toBeNull() + expect(screen.queryByRole('tooltip')).toBeNull() + advance(1) + expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') + fireEvent.click(trigger) + expect(screen.queryByRole('tooltip')).toBeNull() + pointer(trigger, 'pointerout') + advance(500) + expect(screen.getByRole('list')).toBeDefined() + fireEvent.click(trigger) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('cancels pending wide hover when CSS hides the count and compact clicks close hover-opened lists', () => { + vi.useFakeTimers() + render() + const trigger = screen.getByRole('button') + const count = trigger.querySelector('[data-job-count]')! + pointer(trigger, 'pointerover') + advance(100) + count.style.display = 'none' + advance(50) + expect(screen.queryByRole('list')).toBeNull() + pointer(trigger, 'pointerout') + count.style.display = '' + hoverOpen() + count.style.display = 'none' + fireEvent.click(trigger) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('shows count on keyboard focus immediately and opens and pins with ArrowDown', async () => { + vi.useFakeTimers() + render() + const trigger = screen.getByRole('button') + trigger.querySelector('[data-job-count]')!.style.display = 'none' + fireEvent.keyDown(document.body, { key: 'Tab' }) + act(() => { trigger.focus() }) + expect(screen.getByRole('tooltip').textContent).toBe('1 个后台任务') + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + await act(async () => { vi.runAllTicks() }) + expect(screen.queryByRole('tooltip')).toBeNull() + const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) + expect(document.activeElement).toBe(row) + pointer(trigger, 'pointerout') + advance(120) + expect(screen.getByRole('list')).toBeDefined() + fireEvent.keyDown(row, { key: 'Escape' }) + expect(screen.queryByRole('list')).toBeNull() + expect(document.activeElement).toBe(trigger) + }) + + it('waits for hover, bridges the portal gap, and closes after leaving both surfaces', () => { + vi.useFakeTimers() + const observe = vi.fn(() => () => {}) + const { container } = render() + const trigger = hoverOpen() + const menu = screen.getByRole('list').parentElement! + expect(container.contains(menu)).toBe(false) + expect(observe).not.toHaveBeenCalled() + pointer(trigger, 'pointerout') + advance(119) + pointer(menu, 'pointerover') + advance(120) + expect(screen.getByRole('list')).toBeDefined() + pointer(menu, 'pointerout') + advance(119) + expect(screen.getByRole('list')).toBeDefined() + advance(1) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('cancels short hover and preserves a returning pointer during leave grace', () => { + vi.useFakeTimers() + render() + const trigger = screen.getByRole('button') + pointer(trigger, 'pointerover') + advance(149) + pointer(trigger, 'pointerout') + advance(150) + expect(screen.queryByRole('list')).toBeNull() + hoverOpen() + pointer(trigger, 'pointerout') + advance(100) + pointer(trigger, 'pointerover') + advance(120) + expect(screen.getByRole('list')).toBeDefined() + }) + + it('pins a hover-opened list on click until explicit dismissal', () => { + vi.useFakeTimers() + render() + const trigger = hoverOpen() + fireEvent.click(trigger) + pointer(trigger, 'pointerout') + advance(120) + expect(screen.getByRole('list')).toBeDefined() + fireEvent.click(trigger) + expect(screen.queryByRole('list')).toBeNull() + hoverOpen() + fireEvent.click(trigger) + fireEvent.pointerDown(document.body) + expect(screen.queryByRole('list')).toBeNull() + hoverOpen() + pointer(trigger, 'pointerout') + advance(120) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('ignores touch hover while keeping tap usable', () => { + vi.useFakeTimers() + render() + const trigger = screen.getByRole('button') + pointer(trigger, 'pointerover', 'touch') + advance(150) + expect(screen.queryByRole('list')).toBeNull() + fireEvent.click(trigger) + pointer(trigger, 'pointerout', 'touch') + advance(120) + expect(screen.getByRole('list')).toBeDefined() + fireEvent.click(trigger) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('pins keyboard focus and releases expanded output on Escape or hover close', () => { + vi.useFakeTimers() + const stop = vi.fn() + const observe = vi.fn(() => stop) + render() + const trigger = hoverOpen() + pointer(trigger, 'pointerout') + act(() => { trigger.focus() }) + fireEvent.keyDown(trigger, { key: 'Tab' }) + const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) + expect(document.activeElement).toBe(row) + advance(120) + fireEvent.click(row) + expect(observe).toHaveBeenCalledTimes(1) + fireEvent.keyDown(row, { key: 'Escape' }) + expect(document.activeElement).toBe(trigger) + expect(stop).toHaveBeenCalledTimes(1) + hoverOpen() + expect(observe).toHaveBeenCalledTimes(2) + pointer(trigger, 'pointerout') + advance(120) + expect(screen.queryByRole('list')).toBeNull() + expect(stop).toHaveBeenCalledTimes(2) + }) + + it('pins pointer interaction so leaving cannot interrupt stop confirmation', () => { + vi.useFakeTimers() + render() + const trigger = hoverOpen() + pointer(trigger, 'pointerout') + const stop = screen.getByTitle(zh['kill.stop'].replace('{label}', 'pnpm run build')) + fireEvent.pointerDown(stop) + fireEvent.click(stop) + pointer(screen.getByRole('list').parentElement!, 'pointerout') + advance(120) + expect(stop.getAttribute('data-kill-state')).toBe('armed') + expect(screen.getByRole('list')).toBeDefined() + }) + + it('dismisses a hover-opened list with Escape while focus is elsewhere', () => { + vi.useFakeTimers() + render() + hoverOpen() + fireEvent.keyDown(document.body, { key: 'a' }) + expect(screen.getByRole('list')).toBeDefined() + fireEvent.keyDown(document.body, { key: 'Escape' }) + expect(screen.queryByRole('list')).toBeNull() + }) + + it.each(['opening', 'closing'] as const)('cleans up a pending %s timer on unmount', (phase) => { + vi.useFakeTimers() + const { unmount } = render() + const trigger = screen.getByRole('button') + pointer(trigger, 'pointerover') + if (phase === 'closing') { + advance(150) + pointer(trigger, 'pointerout') + } + unmount() + expect(vi.getTimerCount()).toBe(0) + advance(150) + expect(screen.queryByRole('list')).toBeNull() + }) + + it('releases expanded output and pending hover close before showing another session', () => { + vi.useFakeTimers() + const stop = vi.fn() + const observe = vi.fn(() => stop) + const first = props([outputJob()], observe) + const { rerender } = render() + const trigger = hoverOpen() + const row = screen.getByRole('button', { name: zh['row.expandAria'].replace('{label}', 'pnpm run build') }) + fireEvent.click(row) + expect(observe).toHaveBeenCalledTimes(1) + pointer(trigger, 'pointerout') + const nextId = 'next-session' as SessionId + rerender( select({ rows: { [nextId]: [outputJob()] }, observed: {} })} + />) + expect(stop).toHaveBeenCalledTimes(1) + expect(observe).toHaveBeenCalledTimes(1) + expect(vi.getTimerCount()).toBe(0) + hoverOpen() + advance(120) + expect(screen.getByRole('list')).toBeDefined() + expect(observe).toHaveBeenLastCalledWith(nextId, 'bash-1') + }) + + it('cancels pending hover and clears pins on session change or an empty roster', () => { + vi.useFakeTimers() + const first = props([job()]) + const nextId = 'next-session' as SessionId + const next: JobListActionProps = { + ...first, + sessionId: nextId, + useJobs: select => select({ rows: { [nextId]: [job()] }, observed: {} }), + } + const { rerender } = render() + pointer(screen.getByRole('button'), 'pointerover') + rerender() + advance(150) + expect(screen.queryByRole('list')).toBeNull() + const trigger = hoverOpen() + fireEvent.click(trigger) + rerender() + expect(screen.queryByRole('list')).toBeNull() + pointer(screen.getByRole('button'), 'pointerover') + rerender() + advance(150) + expect(vi.getTimerCount()).toBe(0) + rerender() + hoverOpen() + fireEvent.click(screen.getByRole('button', { name: '1 个后台任务' })) + rerender() + rerender() + expect(screen.queryByRole('list')).toBeNull() + }) +}) + describe('JobListAction rows', () => { it('renders a settled job without retained output as a static row', () => { render( { const settled = [job({ id: 'bash-2' as JobView['id'], label: 'settled work', status: 'completed', finishedAt: 1_700_000_012_000 })] render() openList() - expect(screen.getByText(zh['section.live'])).toBeDefined() + expect(screen.getByText(zh['section.live'], { selector: 'li' })).toBeDefined() const toggle = screen.getByRole('button', { name: zh['section.settledCount'].replace('{count}', '1') }) // Folded by default while something runs; the toggle expands it. expect(toggle.getAttribute('aria-expanded')).toBe('false') @@ -289,7 +623,7 @@ describe('JobListAction observation', () => { vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(440) vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(120) const { container } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + const trigger = screen.getByRole('button', { name: '1 个后台任务' }) const anchor = vi.spyOn(trigger.parentElement!, 'getBoundingClientRect') .mockReturnValue(new DOMRect(344, 40, 180, 28)) fireEvent.click(trigger) @@ -315,7 +649,7 @@ describe('JobListAction observation', () => { vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(600) vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(120) render() - const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + const trigger = screen.getByRole('button', { name: '1 个后台任务' }) vi.spyOn(trigger.parentElement!, 'getBoundingClientRect').mockReturnValue(new DOMRect(4, 540, 180, 28)) fireEvent.click(trigger) const menu = screen.getByRole('list', { name: zh['list.aria'] }) @@ -324,11 +658,41 @@ describe('JobListAction observation', () => { expect(menu?.style.top).toBe('468px') }) + it('follows Visual Viewport panning and resizing and releases its listeners when closed', () => { + const viewport = Object.assign(new EventTarget(), { width: 600, height: 500, offsetLeft: 40, offsetTop: 60 }) + vi.stubGlobal('visualViewport', viewport) + vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(120) + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockReturnValue(80) + const remove = vi.spyOn(viewport, 'removeEventListener') + render() + const trigger = screen.getByRole('button', { name: '1 个后台任务' }) + vi.spyOn(trigger.parentElement!, 'getBoundingClientRect').mockReturnValue(new DOMRect(100, 300, 200, 20)) + fireEvent.click(trigger) + const menu = screen.getByRole('list', { name: zh['list.aria'] }).closest('[data-menu-material]')! + expect(menu.style.left).toBe('140px') + expect(menu.style.top).toBe('385px') + act(() => { + viewport.offsetLeft = 100 + viewport.offsetTop = 120 + viewport.dispatchEvent(new Event('scroll')) + }) + expect(menu.style.left).toBe('200px') + expect(menu.style.top).toBe('445px') + act(() => { + viewport.height = 200 + viewport.dispatchEvent(new Event('resize')) + }) + expect(menu.style.top).toBe('228px') + fireEvent.click(trigger) + expect(screen.queryByRole('list', { name: zh['list.aria'] })).toBeNull() + expect(remove.mock.calls.map(([type]) => type)).toEqual(expect.arrayContaining(['scroll', 'resize'])) + }) + it('keeps portaled controls interactive and releases observation on dismissal and unmount', () => { const stop = vi.fn() const observe = vi.fn(() => stop) const { container, unmount } = render() - const trigger = screen.getByRole('button', { name: '1 个后台任务运行中' }) + const trigger = screen.getByRole('button', { name: '1 个后台任务' }) trigger.focus() fireEvent.click(trigger) const list = screen.getByRole('list', { name: zh['list.aria'] }) @@ -595,7 +959,7 @@ it.each([1, 2, 5, 21])('renders count-independent Russian labels for %i jobs', ( const jobs = Array.from({ length: count }, (_, i) => job({ id: `job-${i}` as JobView['id'] })) const translate: JobListActionProps['t'] = makeTranslate(ru) const view = render() - expect(screen.getByRole('button', { name: `Фоновые задачи выполняются: ${count}` })).toBeDefined() + expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() view.rerender( ({ ...item, status: 'completed', finishedAt: 1_700_000_003_000 })))} t={translate} />) expect(screen.getByRole('button', { name: `Фоновые задачи: ${count}` })).toBeDefined() }) diff --git a/packages/client/ui-model-selection/README.i18n.yaml b/packages/client/ui-model-selection/README.i18n.yaml index e66c1a88ac..b4bb58e659 100644 --- a/packages/client/ui-model-selection/README.i18n.yaml +++ b/packages/client/ui-model-selection/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-model-selection/use-this-package: - en: 9b1eca0aec81ac29 - zh: 9a1599c3abf76513 + en: 0e2230da6a2214a1 + zh: 0452e7556c9175f2 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-and-effort: - en: 2e6d9965e01dc0ce - zh: 332cc82233eb02f3 + en: cead8d55a9508a8f + zh: d1ef63a880cbec55 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/model-label-extensions: en: 23610fb9daf9918a zh: 9f63a97901be100c @@ -27,11 +27,11 @@ en: 7f20428c747ff052 zh: 975e6de728e02fa0 /deepseek-ai-dsh-client-ui-model-selection/use-this-package/selection-failures: - en: 261bbf42296243af - zh: 72779fb7b8fbc473 + en: 80fc237fa5c829f7 + zh: ecff5c8526f45996 /deepseek-ai-dsh-client-ui-model-selection/understand-the-implementation: - en: 56003671ca5acf24 - zh: 251e02201ea82142 + en: 14870a55b8f4d4b7 + zh: f498b469a785271e /deepseek-ai-dsh-client-ui-model-selection/further-exploration: en: 14acd4692e923480 zh: ff89aed852aa0da8 diff --git a/packages/client/ui-model-selection/README.md b/packages/client/ui-model-selection/README.md index a3e3dae81f..1a53aa7c7b 100644 --- a/packages/client/ui-model-selection/README.md +++ b/packages/client/ui-model-selection/README.md @@ -29,7 +29,7 @@ The Web GUI lets users switch the model and reasoning effort for an existing ses DeepSeek account and API-key routes appear as separate provider groups, each exposing the same configured model catalog. -When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog displays “No models available.” +When no model is selected or the saved selection is absent from the catalog, the composer shows “Select model” in regular weight and hides the reasoning effort caption. Clicking it opens the model list directly; Escape and Shift+Tab close it. An empty catalog hides the model menu from display and the accessibility tree and displays “No models available.” in a status region. Mount this plugin alongside `ui-conversation` and the commands package; the composer then shows the model seat next to the pending indicator, and `/model` opens the same directory as a popup. While the seat's menu is open, `↑`/`↓` move focus through root and effort rows, or move the model-list highlight without leaving search. Enter and Tab settle the highlighted model or focused row; Escape and `Shift+Tab` leave a drilled pane first and otherwise close back to the trigger. Drilling focuses model search when shown on desktop devices; otherwise it focuses the current model or effort row, or the first enabled row when none is selected. Going back focuses the cell that opened the pane. Phones and tablets leave search unfocused until the user taps it or uses keyboard navigation. The composer shows the catalog name while the selected model is available. Removing a model or provider, including account sign-out, preserves the stored provider, model, and reasoning effort without displaying their IDs. Restoring the catalog entry restores its name and effort caption. @@ -39,7 +39,7 @@ Mouse selection uses native browser clicks, including their cancellation behavio The button's model menu shows search only when its full catalog contains more than four models; smaller catalogs support keyboard navigation directly and focus the current model or first enabled row on all devices. The `/model` command always keeps its search field. Both search fields match model names case-insensitively, including nonconsecutive characters in order; leading and trailing spaces are ignored. Within each provider, prefix matches come first, followed by alignment score and then catalog order. Empty groups are hidden. Empty catalogs and queries without matches are announced through a status region. Search keeps focus while arrow keys cycle the highlighted result across provider groups; Enter or Tab selects it. Left and right arrows keep their native caret behavior. Opening highlights the current model or the first available row, and editing the query resets the highlight to the first result. Reopening the model pane clears the query. -Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. The clear button appears for a nonempty query and restores the full list with focus in the search field. +Model and reasoning-effort names use weight 400 (regular) in the composer menu, including the selected item. The search field follows the command popup's compact treatment with transparent background and border in both palettes, with no leading icon and a caption-tone placeholder. Its text is 16px on devices with a coarse primary pointer to avoid Safari focus zoom; fine pointers retain 12px. The clear button appears for a nonempty query and restores the full list with focus in the search field. Both entries group models by provider, with DeepSeek Account first and DeepSeek second; third-party providers retain their catalog order. Both use the shared, asynchronously observed sticky headings from [ui-primitives](../ui-primitives/README.md#understand-the-implementation): transparent at rest, with the theme's 94%-opaque fill only while pinned, and `md` corners outside macOS Desktop. The composer menu shows model and effort names only. Navigation chevrons use `--dsw-alias-menu-icon`. The `/model` popup shows provider names as group headings and model names as rows, without repeating the provider on each row or showing catalog descriptions. Its search placeholder, no-match text, and empty-catalog text use the same localized labels as the composer model menu. The popup applies the selected model's default effort; the composer can then choose any advertised effort. An adapter without reasoning metadata leaves the Effort row absent; there is no arbitrary effort input. @@ -61,12 +61,14 @@ Catalog availability does not block sending with a saved selection; request exec When another writer owns the Session, model-selection failures tell the user to quit other running DSH instances and retry. +The session-scoped `conversation.input.model.options` list slot appends controls below model and reasoning selection. Owner props expose `locked`, `reportFailure(message)`, and `dismiss()`, which closes the menu and synchronously focuses its trigger before another overlay opens; contributions read their own projections and supply narrow commands. Enabled switch buttons participate in the menu’s keyboard navigation. + ----- ## Understand the implementation -Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). +Menus use the shared `MenuSurface` material, including the macOS backing for background blur; custom content follows the [menu rules](../../../docs/web-styling.md#component-rules). The composer menu uses a fixed body portal. `useAnchoredPosition` normalizes the trigger's fixed-position coordinates and updates placement on scroll, resize, visual-viewport changes, and menu-size changes. Opening the menu and changing panes measure and place the panel synchronously before paint. Placement starts above the trigger with right edges aligned and an 8px gap; both axes shift to retain a 12px viewport margin without flipping below the trigger. Panel dimensions are capped to the visible viewport, including while the keyboard is open. Model names ellipsize within the panel width while badges stay visible. Model and reasoning-effort lists scroll vertically within the panel height limit.
      Implementation internals — click to expand diff --git a/packages/client/ui-model-selection/README.zh.md b/packages/client/ui-model-selection/README.zh.md index 63c2cd9924..253370b97f 100644 --- a/packages/client/ui-model-selection/README.zh.md +++ b/packages/client/ui-model-selection/README.zh.md @@ -29,7 +29,7 @@ Web GUI 允许用户通过 `/model` 弹窗或 composer 模型控件切换既有 DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示相同的已配置模型目录。 -未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时显示“暂无可用模型” +未选择模型或已保存的选择不在目录中时,composer 以常规字重显示“请选择模型”,并隐藏推理强度文案。点击后直接打开模型列表,Escape 和 Shift+Tab 关闭列表。目录为空时,模型菜单不显示,也不进入无障碍树;状态区域显示“暂无可用模型” 与 `ui-conversation` 及命令包一起挂载本插件;composer 随即在待处理指示器旁显示模型位,`/model` 则以弹窗打开同一份目录。模型位菜单打开期间,`↑`/`↓` 在根菜单和推理等级行间移动焦点,或在模型列表中移动高亮并让焦点保留在搜索框。Enter 和 Tab 选定高亮模型或聚焦行;Escape 与 `Shift+Tab` 先退出已下钻的面板,否则关闭并回到触发器。下钻时,桌面设备在显示模型搜索框时聚焦搜索框;其他情况聚焦当前模型或推理强度行,没有选中项时聚焦首个可用行。返回时聚焦打开该面板的格子。手机和平板在用户主动点按搜索框或使用键盘导航前,不会聚焦搜索框。所选模型可用时,composer 显示目录中的模型名称。模型或提供方被删除时(包括账号退登),保留已保存的提供方、模型和推理强度,但不展示其 ID。目录条目恢复后重新显示名称和推理强度。 @@ -39,7 +39,7 @@ DeepSeek 账号和 API Key 路由显示为独立提供方分组,各自展示 按钮模型菜单仅在完整目录超过四个模型时显示搜索框;较小目录直接支持键盘导航,并在所有设备上聚焦当前模型或首个可用行。`/model` 命令始终保留搜索框。两个搜索框均按模型名称进行不区分大小写的匹配,支持按顺序输入不连续字符,并忽略首尾空格。每个提供方内的结果优先按前缀匹配、其次按匹配得分、最后按目录顺序排列。没有匹配项的分组会隐藏。空目录和无匹配结果均通过状态区域通知屏幕阅读器。方向键在各提供方分组的结果间循环移动高亮,焦点保留在搜索框;Enter 或 Tab 选定高亮项。左右方向键仍用于移动输入光标。打开时高亮当前模型或首个可用选项,修改搜索内容后高亮首个结果。重新打开模型面板会清空搜索内容。 -composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 +composer 菜单中的模型名称和推理等级均使用 400(regular)字重,包括选中项。搜索框沿用 command 弹窗的紧凑样式,在浅/深色主题下均保持背景和边框透明,不显示前置图标,占位文字使用 caption 色。主指针精度较低的设备使用 16px 搜索文字,避免 Safari 聚焦缩放;精细指针设备保留 12px。搜索内容非空时显示清除按钮;点击后恢复完整列表,并将焦点留在搜索框。 两个入口均按提供方分组,DeepSeek 账号排第一,DeepSeek 排第二,第三方提供方保持目录原有顺序。两者采用 [ui-primitives](../ui-primitives/README.zh.md#understand-the-implementation) 异步观察的共享吸顶标题:原位透明,仅吸顶时使用主题的 94% 不透明填充,macOS 桌面端以外使用 `md` 圆角。composer 菜单只显示模型与推理强度名称。导航箭头使用 `--dsw-alias-menu-icon` 文本色。`/model` 弹窗以提供方名称作为分组标题、模型名称作为选项行,不在每行重复提供方,也不显示目录说明。搜索占位文字、无匹配提示和空目录提示与 composer 模型菜单共用同一组本地化文案。弹窗应用所选模型的默认推理强度;composer 随后可以选择任一已公布的推理强度。适配器没有推理元数据时不显示 Effort 行;不存在任意推理强度输入。 @@ -61,12 +61,14 @@ composer 菜单中的模型名称和推理等级均使用 400(regular)字重 当会话被其他写句柄占用时,模型选择失败提示用户退出其他正在运行的 DSH 后重试。 +会话级列表 slot `conversation.input.model.options` 在模型与推理等级选项下方追加控件。Owner props 提供 `locked`、`reportFailure(message)` 和 `dismiss()`,后者关闭菜单并同步聚焦触发按钮,供贡献方随后打开其他浮层;贡献方读取自身投影并提供专用命令。启用的开关按钮参与菜单键盘导航。 + ----- ## 理解实现 -菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。 +菜单采用共享 `MenuSurface` 材质,包括用于背景模糊的 macOS 底层;自定义内容遵循[菜单规则](../../../docs/web-styling.zh.md#component-rules)。composer 菜单通过 body portal 使用 fixed 定位。`useAnchoredPosition` 统一触发按钮的 fixed 定位坐标,并在滚动、窗口缩放、可见视口变化和菜单尺寸变化时更新位置。打开菜单和切换面板时,在绘制前同步完成测量和定位。菜单默认在按钮上方展开、右边缘对齐、间距为 8px;两个方向均可移动以保留 12px 视口边距,但不会翻转到按钮下方。面板尺寸不超过可见视口,键盘打开时也遵循此限制。模型名称超出面板宽度时以省略号截断,角标保持可见。模型与推理等级列表在面板高度限制内纵向滚动。
      实现细节——点击展开 diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.module.css b/packages/client/ui-model-selection/src/client/ModelSelect.module.css index c36809acaa..fdd190fa4c 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.module.css +++ b/packages/client/ui-model-selection/src/client/ModelSelect.module.css @@ -92,16 +92,16 @@ Menu primitive's portal rules), so the sidebar and the columns' overflow clips cannot crop it; z matches the primitive's .portal layer. */ .menu { + box-sizing: border-box; position: fixed; z-index: 1100; display: flex; flex-direction: column; - /* Let the visible pane's rows set the card width, but keep pathological ids - and narrow screens inside a bounded card where ellipsis remains. */ + /* Rows size the card up to its visible bounds; longer names ellipsize. */ width: max-content; - min-width: min(240px, calc(100vw - 32px)); - max-width: min(420px, calc(100vw - 32px)); - max-height: min(360px, calc(100vh - 96px)); + min-width: min(240px, calc(100vw - 32px), var(--dsh-anchored-max-width, 100vw)); + max-width: min(420px, calc(100vw - 32px), var(--dsh-anchored-max-width, 100vw)); + max-height: min(360px, calc(100vh - 96px), var(--dsh-anchored-max-height, 100vh)); overflow: hidden; padding: 4px; /* Surface tokens match the Menu primitive card (ui-primitives @@ -218,12 +218,19 @@ line-height: normal; } +@media (pointer: coarse) { + .searchRow .search input { + font-size: 16px; + } +} + .searchRow .search input::placeholder { color: var(--dsw-alias-label-caption); } -.groups { +.groups:not([hidden]) { min-height: 0; + overflow-x: hidden; overflow-y: auto; } diff --git a/packages/client/ui-model-selection/src/client/ModelSelect.tsx b/packages/client/ui-model-selection/src/client/ModelSelect.tsx index f68d355317..0369578a08 100644 --- a/packages/client/ui-model-selection/src/client/ModelSelect.tsx +++ b/packages/client/ui-model-selection/src/client/ModelSelect.tsx @@ -27,7 +27,7 @@ * chevron, and each row whose value that selection carries shows one in place * of its check mark. */ -import { MenuGroup, MenuSurface, observeStickyMenuGroups } from '@deepseek-ai/dsh-client-ui-primitives' +import { MenuGroup, MenuSurface, observeStickyMenuGroups, useAnchoredPosition } from '@deepseek-ai/dsh-client-ui-primitives' import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent, type FocusEvent, @@ -66,7 +66,7 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 } export function ModelSelect( { locked, available, directory, load, select, resolveText, t, renderSlot }: ModelSelectInjected & Pick, 'locked'> & PropsLocale<'model'> - & Omit, 'SessionProvider'>, + & Omit, 'SessionProvider'>, ) { const state = useSyncExternalStore( fn => directory.subscribe(fn), @@ -89,7 +89,16 @@ export function ModelSelect( const searchRef = useRef(null) const menuRef = useRef(null) const groupsRef = useRef(null) - const [menuPos, setMenuPos] = useState(null) + const menuPos = useAnchoredPosition({ + open: open && available, + anchorRef: triggerRef, + panelRef: menuRef, + side: 'top', + align: 'end', + gap: 8, + margin: 12, + layoutKey: pane, + }) const itemRefs = useRef<(HTMLButtonElement | null)[]>([]) const id = useId() @@ -215,38 +224,6 @@ export function ModelSelect( } }, [open, pane, activeModelIndex, visibleModels]) - // The portal needs viewport coordinates from the trigger and the menu's - // measured size before paint. Slot content can resize without parent renders. - useLayoutEffect(() => { - if (!available || !open) { setMenuPos(null); return } - const place = (): void => { - /* v8 ignore next 2 -- the trigger ref is attached whenever the menu is open. */ - const rect = triggerRef.current?.getBoundingClientRect() - if (rect === undefined) return - const MARGIN = 12 - const lw = menuRef.current?.offsetWidth ?? 0 - const lh = menuRef.current?.offsetHeight ?? 0 - let x = rect.right - lw - let y = rect.top - 8 - lh - if (lw > 0) x = Math.min(Math.max(x, MARGIN), window.innerWidth - lw - MARGIN) - if (lh > 0) y = Math.min(Math.max(y, MARGIN), window.innerHeight - lh - MARGIN) - setMenuPos({ left: x, top: y }) - } - place() - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) - const menu = menuRef.current - const observer = typeof ResizeObserver !== 'undefined' && menu !== null - ? new ResizeObserver(place) - : null - if (menu !== null) observer?.observe(menu) - return () => { - observer?.disconnect() - window.removeEventListener('scroll', place, true) - window.removeEventListener('resize', place) - } - }, [available, open, pane, state, query]) - if (!available) return null const show = (): void => { @@ -290,7 +267,9 @@ export function ModelSelect( } const moveFocus = (offset: number): void => { - const items = itemRefs.current.filter(item => item !== null) + const items = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', + ) ?? []) if (items.length === 0) return const active = items.findIndex(item => item === document.activeElement) // Focus outside the rows (the trigger, which keeps it while the menu @@ -344,7 +323,9 @@ export function ModelSelect( // control inside the card (a retry button) keeps the browser's traversal, // so the keystroke stays unconsumed there. const focused = document.activeElement - const rows = itemRefs.current.filter((item): item is HTMLButtonElement => item !== null) + const rows = Array.from(menuRef.current?.querySelectorAll( + 'button[role="menuitem"]:not([disabled]), button[role="menuitemradio"]:not([disabled]), button[role="switch"]:not([disabled])', + ) ?? []) if (focused instanceof HTMLButtonElement && rows.includes(focused)) { event.preventDefault() focused.click() @@ -530,6 +511,14 @@ export function ModelSelect( )} + {renderSlot('conversation.input.model.options', { + locked: locked || busy, + dismiss: () => { + close() + triggerRef.current?.focus() + }, + reportFailure: (message) => { setToast({ seq: ++toastSeq.current, text: message }) }, + })} )} @@ -644,30 +633,32 @@ export function ModelSelect(
    )} - {effortChoices.length === 0 - ?
    {t('empty.efforts')}
    - : effortChoices.map(level => ( - - ))} +
    + {effortChoices.length === 0 + ?
    {t('empty.efforts')}
    + : effortChoices.map(level => ( + + ))} +
    )} , diff --git a/packages/client/ui-model-selection/src/client/index.ts b/packages/client/ui-model-selection/src/client/index.ts index b91ee20b48..224990e848 100644 --- a/packages/client/ui-model-selection/src/client/index.ts +++ b/packages/client/ui-model-selection/src/client/index.ts @@ -174,6 +174,7 @@ export function apply(ctx: ClientContext): void { locale: NS, children: { 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, }, inject: (sessionId): ModelSelectInjected => { const directory = models.directoryFor(sessionId) diff --git a/packages/client/ui-model-selection/src/client/slots.ts b/packages/client/ui-model-selection/src/client/slots.ts index 4ffddee580..39a31b673f 100644 --- a/packages/client/ui-model-selection/src/client/slots.ts +++ b/packages/client/ui-model-selection/src/client/slots.ts @@ -19,6 +19,19 @@ export interface ModelLabelOwner { declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { + /** Session options appended after model and reasoning controls in the root menu. */ + 'conversation.input.model.options': { + kind: 'list' + scope: 'session' + owner: { + /** Whether the composer currently refuses selection changes. */ + locked: boolean + /** Close the menu and focus its trigger synchronously before opening another overlay. */ + dismiss: () => void + /** Report a failed selection through the menu owner's persistent toast. */ + reportFailure: (message: string) => void + } + } /** * Non-interactive inline model label; selection controls remain owner-managed. * Without a contribution, the badge precedes the catalog name in the trigger diff --git a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx index dbb5b247db..2807820dc5 100644 --- a/packages/client/ui-model-selection/tests/model-select.client.spec.tsx +++ b/packages/client/ui-model-selection/tests/model-select.client.spec.tsx @@ -7,6 +7,7 @@ import { SessionId } from '@deepseek-ai/dsh-session/types' import type { ModelSelection } from '@deepseek-ai/dsh-api-remotes/client' import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import type { ComponentProps } from 'react' +import type { OwnerOf } from '@deepseek-ai/dsh-client-ui-slots' import type { ModelDirectoryState } from '../src/client/directory.ts' import { ModelSelect } from '../src/client/ModelSelect.tsx' import { en, zh } from '../src/client/locales.ts' @@ -98,6 +99,7 @@ describe('ModelSelect label slot', () => { }) await runtime.root.declare({ 'conversation.input.model.label': { kind: 'single', scope: 'session', inline: true }, + 'conversation.input.model.options': { kind: 'list', scope: 'session' }, }, ({ renderSlot, SessionProvider }) => @@ -1121,3 +1123,20 @@ it('restores the account model name after login without changing the saved route expect(screen.getByRole('button', { name: /选择模型,当前/ }).textContent).toBe('DeepSeek FlashHigh') expect(directory.getSnapshot().current).toEqual(selected) }) + + +it('dismisses contributed options with focus on the trigger before opening another overlay', () => { + const renderSlot = vi.fn((_name: string, _owner: object) => null) + render() + const trigger = screen.getByRole('button', { name: /^选择模型/ }) + fireEvent.click(trigger) + const options = renderSlot.mock.calls.find(call => call[0] === 'conversation.input.model.options') + if (options?.[0] !== 'conversation.input.model.options') throw new Error('Missing model options') + act(() => { + screen.getAllByRole('menuitem')[0]!.focus() + ;(options[1] as OwnerOf<'conversation.input.model.options'>).dismiss() + expect(document.activeElement).toBe(trigger) + }) + expect(screen.queryByRole('menu')).toBeNull() +}) diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index f9d7f07f73..781b5d2a7c 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -18,8 +18,8 @@ en: 07da57fb0a0cb10e zh: c743fd96317bec22 /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/installing-a-bundle: - en: 45f62bdddae3f8c0 - zh: 4be303f322a5553a + en: cd4e17d62c407541 + zh: 9610d3ee55c0e56a /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/updating-a-registry-bundle: en: 9312d8b1b381378f zh: 8d0ae7ad26ada2ac diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 66a9a11321..03ed8e8c24 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -62,7 +62,7 @@ On first use, when pnpm uses the unconfigured official npm registry and npmmirro The Host sends GET requests to `https://registry.npmjs.org/-/ping` and `https://registry.npmmirror.com/-/ping` through its normal fetch proxy. A 2xx response wins; redirects and failures do not. The remaining request is cancelled, both response bodies are discarded, and cleanup completes before the result returns. The default deadline is 1500 ms and results, including unavailable results, are cached for five minutes. Configure `registryProbeTimeoutMs` and `registryProbeCacheTtlMs` on `ui-plugin-manager`; `registryProbeEnabled: false` disables probing. If both requests fail or time out, the existing default remains selected. No IP-location service or Session content is involved. -**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. Enter in the package or custom-registry field submits the install request, but Enter used to confirm an input-method candidate does not. **Install guide and examples** under the field opens a guide that shows the package-name example; **Use example** drops it into the field. Typing or pasting the Git or local-path template verbatim still raises the reminder asking for the actual value. A trust box above **Install** stays visible including when the guide is collapsed, and explains that on-demand Official entries offer explicit Update, while other plugins are upgraded by uninstalling and reinstalling. **Registry** beside it names the registry the install asks first and unfolds the choice: pnpm's own registry, named by the registry it actually names — the official npm registry, the mainland China mirror, or its host — which keeps the neutral default name until the Host reads it, is listed once, and carries its host unless that host is already its name; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options use an opaque selector panel, fill rows only on hover, and show hosts in tertiary text without parentheses. The custom-address area highlights on hover; clicking anywhere in it selects the custom registry and focuses its input, whose focus style matches the package field. Keyboard focus alone preserves the selected registry; activating the custom radio or editing the address selects the custom registry. Tab moves from the selected radio to the address, and Shift+Tab moves back; leaving either end closes the selector and returns focus to **Registry**. Switching to an offered registry retains the custom URL draft for switching back. Submitting an invalid custom address blocks installation, opens the registry selector, and focuses the address. Invalid package and custom-address fields keep a red error border and add the shared blue inset focus ring on focus. The options float over the dialog from the control, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The initial choice follows the response comparison above; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one and remains the requested address when installation starts before the registry list returns. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. Each command line stays on one line and scrolls horizontally; selecting its text includes offscreen arguments. A finished install shows the version pnpm installed; when a run that asked one registry installed another version than the one read, it names both versions, attributes the difference to pnpm's supply-chain security policy (`minimumReleaseAge`), states the risk of a newly published version, and gives the exact `name@version` to install after uninstalling. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls to its card if it is on the current page; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — and, when the install asked to enable the added bundle, says when it finished and enabling that bundle is what failed. Its details hold pnpm's output and the path of the settled run's complete Host log, or a note that the dialog received no terminal output; **Retry** is at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate. +**Add plugin** takes a package name with an optional version, a Git address, a tarball, or an absolute local path; the dialog says a package name is what follows `dsh plugin add` in a README. Enter in the package or custom-registry field submits the install request, but Enter used to confirm an input-method candidate does not. **Install guide and examples** under the field opens a guide that shows the package-name example; **Use example** drops it into the field. Typing or pasting the Git or local-path template verbatim still raises the reminder asking for the actual value. A trust box above **Install** stays visible including when the guide is collapsed, and explains that on-demand Official entries offer explicit Update, while other plugins are upgraded by uninstalling and reinstalling. **Registry** beside it names the registry the install asks first and unfolds the choice: pnpm's own registry, named by the registry it actually names — the official npm registry, the mainland China mirror, or its host — which keeps the neutral default name until the Host reads it, is listed once, and carries its host unless that host is already its name; each mirror the Host configured (`pluginManager.registries`), npmmirror as the mainland China mirror; and a typed http(s) address. The options use an opaque selector panel, fill rows only on hover, and show hosts in tertiary text without parentheses. The custom-address area highlights on hover; clicking anywhere in it selects the custom registry and focuses its input, whose focus style matches the package field. Keyboard focus alone preserves the selected registry; activating the custom radio or editing the address selects the custom registry. Tab moves from the selected radio to the address, and Shift+Tab moves back; leaving either end closes the selector and returns focus to **Registry**. Switching to an offered registry retains the custom URL draft for switching back. Submitting an invalid custom address blocks installation, opens the registry selector, and focuses the address. Invalid package and custom-address fields keep a red error border and add the shared blue inset focus ring on focus. The options use `useAnchoredPosition` to stay anchored to the control during browser zoom, scrolling, and resizing, while keeping the viewport margins and desktop frame clearance. They float over the dialog, so unfolding them never lengthens the card, and the card's content scrolls when the guide makes it taller than the viewport. The initial choice follows the response comparison above; the choice is then remembered in this browser (`localStorage`) and starts the next dialog, and a remembered address the Host no longer offers stays as a typed one and remains the requested address when installation starts before the registry list returns. **Install** first asks the Host to read what the spec names (`pluginManager.inspect`) at the chosen registry: a name the list already shows, a name no registry has, a path without a package, a package without a bundle patch, or a spec pnpm would refuse comes back under the field as one sentence, with the spec kept for editing; when no registry could be reached, the sentence names every one asked. The install then starts at the registry that answered. An accepted spec opens the installing screen, which shows the package's name, one-liner, and version as the Host read them and folds pnpm's command and output behind **Show install details**. Each command line stays on one line and scrolls horizontally; selecting its text includes offscreen arguments. A finished install shows the version pnpm installed; when a run that asked one registry installed another version than the one read, it names both versions, attributes the difference to pnpm's supply-chain security policy (`minimumReleaseAge`), states the risk of a newly published version, and gives the exact `name@version` to install after uninstalling. A finished install offers **Enable now**, which switches the new bundle on, closes the dialog, and scrolls to its card if it is on the current page; closing instead leaves it installed and off. While the Host moves on to another registry, the installing screen says which registry could not serve the package and which is asked now, and each pnpm run behind the details carries a badge naming its registry. A failed install says what went wrong in one line, as the Host attributed it — no registry could be reached, naming every one asked; the host a GitHub address or a tarball link is fetched from could not be reached, which no registry helps; the package was not found, the disk is full, the profile is not writable, pnpm blocked a build script — and, when the install asked to enable the added bundle, says when it finished and enabling that bundle is what failed. Its details hold pnpm's output and the path of the settled run's complete Host log, or a note that the dialog received no terminal output; **Retry** is at hand, and **Change registry** beside it when the Host laid the failure at the registry it asked, which returns to the spec with the registry options open; the Host has already put the profile files back. When pnpm blocked a dependency's install scripts, the failed screen lists the packages whose scripts wait for permission and offers **Allow these scripts and retry** in place of **Retry**; the Host saves the permission in the profile's `pnpm-workspace.yaml`, which a failed run leaves as pnpm wrote it, then runs pnpm again, and the installed screen names what was allowed. A successful installation does not certify that a module can activate. During preparation and download, **Cancel install** asks the Host to stop the run and waits for confirmation. Loading the bundle cannot be cancelled. Closing with ×, Escape, or the backdrop hides the dialog immediately and requests cancellation when possible. **View installation** reopens the same task with its output; another installation cannot start while its outcome is pending or unconfirmed. Confirmed cancellation returns to the spec and shows a toast; the manifest and lockfile are restored, while downloaded files can remain. A lost installation response triggers a request to recover the result; **Check installation status** and reconnect retry that request. If the Host has no active request, **Installation result unavailable** allows returning to editing after checking the plugin list. A cancellation sent before acceptance waits and retries automatically; a failed cancellation can be retried manually. Hidden tasks report their outcome through toasts without reopening the dialog. diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index bfffd1fe09..b0dedeaad9 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -62,7 +62,7 @@ kind: "package-reference" Host 通过普通 fetch 代理向 `https://registry.npmjs.org/-/ping` 和 `https://registry.npmmirror.com/-/ping` 发送 GET 请求,以最先返回 2xx 的源为结果;重定向和失败不参与选择。随后取消另一条请求、丢弃两个响应体,并在清理完成后返回。默认时限为 1500 毫秒,包括不可用结果在内的探测结果均缓存五分钟。在 `ui-plugin-manager` 上配置 `registryProbeTimeoutMs` 和 `registryProbeCacheTtlMs`;`registryProbeEnabled: false` 关闭探测。两条请求都失败或超时时保留现有默认源。不使用 IP 地区服务,也不发送 Session 内容。 -**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。在包名或自定义安装源输入框中按 Enter 会提交安装请求,但用于确认输入法候选词的 Enter 不会触发安装。输入框下方的**插件安装引导和示例**展开一段引导,给出包名示例;**填入示例**把它填进输入框。输入框中若原样保留 Git 地址或本地路径的模板文本,仍会显示要求替换为实际值的提醒。**安装**按钮上方的提示框在引导收起后也可见,并说明官方按需插件提供显式更新;其他插件通过卸载后重新安装升级。旁边的**安装源**写着安装首先询问的注册表,展开后可选:pnpm 自身的注册表,按它实际指向的源命名——npm 官方源、中国大陆镜像源,其余以主机名显示——Host 读不到时保留中性的默认名称,只列一次,选项标题带上主机名(主机名即名称时不重复显示);Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项使用不透明选择面板,仅悬停行使用底色,主机名不加括号并使用三级文字色。自定义地址区域在悬停时高亮;点击其中任意位置会选中自定义源并聚焦输入框,焦点样式与包名输入框一致。仅通过键盘聚焦不会改变已选安装源;激活自定义单选项或编辑地址才会选中自定义源。Tab 从已选单选项移到地址框,Shift+Tab 反向返回;从任一端移出时关闭选择器,并将焦点交还**安装源**按钮。切到预设源时保留自定义地址草稿,切回后继续使用。提交无效的自定义地址时会阻止安装,展开安装源选择器并聚焦地址框。包名和自定义地址输入框无效时保留红色错误边框,聚焦时加上共享的蓝色内嵌焦点环。选项从控件上浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。初始选择遵循上文的响应比较规则;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址;在安装源列表返回前开始安装,也仍请求该地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。每条命令行保持单行并可横向滚动;选择文本时可包含屏幕外的参数。安装完成的画面显示 pnpm 实际安装的版本;只问过一个注册表的运行装入的版本与检查读到的不同时,会写明两个版本,说明差异来自 pnpm 供应链安全策略(`minimumReleaseAge`),提示新发布版本的风险,并给出卸载后应安装的精确 `name@version`。安装完成后提供**立即启用**:启用新组合包、关闭对话框,并在当前页面有对应卡片时滚动定位;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——当这次安装要求启用新增的组合包时,还会注明安装本身已完成、失败发生在启用时。详情里有 pnpm 输出和结束这次对话框的那次运行的完整 Host 日志路径,安装详情没有收到终端输出时也会直接说明;**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。 +**添加插件**接受包名(可带版本)、Git 地址、压缩包或本地绝对路径;对话框说明包名就是 README 里 `dsh plugin add` 后面的那一段。在包名或自定义安装源输入框中按 Enter 会提交安装请求,但用于确认输入法候选词的 Enter 不会触发安装。输入框下方的**插件安装引导和示例**展开一段引导,给出包名示例;**填入示例**把它填进输入框。输入框中若原样保留 Git 地址或本地路径的模板文本,仍会显示要求替换为实际值的提醒。**安装**按钮上方的提示框在引导收起后也可见,并说明官方按需插件提供显式更新;其他插件通过卸载后重新安装升级。旁边的**安装源**写着安装首先询问的注册表,展开后可选:pnpm 自身的注册表,按它实际指向的源命名——npm 官方源、中国大陆镜像源,其余以主机名显示——Host 读不到时保留中性的默认名称,只列一次,选项标题带上主机名(主机名即名称时不重复显示);Host 配置的每个镜像(`pluginManager.registries`),npmmirror 显示为中国大陆镜像源;以及手动输入的 http(s) 地址。选项使用不透明选择面板,仅悬停行使用底色,主机名不加括号并使用三级文字色。自定义地址区域在悬停时高亮;点击其中任意位置会选中自定义源并聚焦输入框,焦点样式与包名输入框一致。仅通过键盘聚焦不会改变已选安装源;激活自定义单选项或编辑地址才会选中自定义源。Tab 从已选单选项移到地址框,Shift+Tab 反向返回;从任一端移出时关闭选择器,并将焦点交还**安装源**按钮。切到预设源时保留自定义地址草稿,切回后继续使用。提交无效的自定义地址时会阻止安装,展开安装源选择器并聚焦地址框。包名和自定义地址输入框无效时保留红色错误边框,聚焦时加上共享的蓝色内嵌焦点环。选项使用 `useAnchoredPosition`,在浏览器缩放、滚动和尺寸变化时保持锚定到控件,并保留视口边距和桌面标题栏避让。选项浮在对话框之上,展开不会拉长卡片;引导使卡片高过视口时,卡片内容可以滚动。初始选择遵循上文的响应比较规则;之后选择记在本浏览器(`localStorage`)里,下次打开对话框从它开始,Host 不再提供的已记住地址保留为手动输入的地址;在安装源列表返回前开始安装,也仍请求该地址。**安装**先让 Host 在所选注册表读出 spec 指向什么(`pluginManager.inspect`):列表中已有的名字、所有注册表都没有的名字、没有包的路径、没有组合包 patch 的包,或 pnpm 会拒绝的 spec,都以一句话回到输入框下方,spec 保留可继续编辑;所有注册表都连不上时,这句话列出问过的每一个。随后安装从作答的那个注册表开始。通过检查的 spec 打开安装中界面,展示 Host 读到的包名、一句话简介和版本,pnpm 的命令与输出折叠在**查看安装详情**之后。每条命令行保持单行并可横向滚动;选择文本时可包含屏幕外的参数。安装完成的画面显示 pnpm 实际安装的版本;只问过一个注册表的运行装入的版本与检查读到的不同时,会写明两个版本,说明差异来自 pnpm 供应链安全策略(`minimumReleaseAge`),提示新发布版本的风险,并给出卸载后应安装的精确 `name@version`。安装完成后提供**立即启用**:启用新组合包、关闭对话框,并在当前页面有对应卡片时滚动定位;直接关闭则让它保持已安装但关闭。Host 改问另一个注册表时,安装中界面会说明哪个源没能提供这个包、现在改问哪个,详情里每次 pnpm 运行都带一个写明所用源的标记。安装失败时按 Host 的归因用一行话说明原因——所有安装源都连不上,并列出问过的每一个;GitHub 地址或压缩包链接自身的主机连不上,换源无济于事;包不存在、磁盘已满、profile 不可写、pnpm 拦下了构建脚本——当这次安装要求启用新增的组合包时,还会注明安装本身已完成、失败发生在启用时。详情里有 pnpm 输出和结束这次对话框的那次运行的完整 Host 日志路径,安装详情没有收到终端输出时也会直接说明;**重试**就在手边,Host 把失败归于所问注册表时还在旁边提供**更换安装源**,回到 spec 输入界面并展开安装源选项;Host 已经把 profile 文件放回原样。pnpm 拦下依赖的安装脚本时,失败界面列出等待允许的包,并以**允许这些脚本并重试**取代**重试**;Host 把授权写进 profile 的 `pnpm-workspace.yaml`(失败的运行保留 pnpm 写入的这个文件)再运行 pnpm,安装完成界面会说明允许了哪些脚本。安装成功不代表模块一定能够激活。 准备和下载期间,**取消安装**会请求 Host 停止运行并等待确认。加载组合包的阶段不可取消。点击 ×、按 Escape 或点击遮罩会立即隐藏对话框,并在可以取消时请求取消。**查看安装任务**会重新打开同一任务并保留输出;结果待定或尚未确认时不能发起另一项安装。确认取消后回到 spec 输入界面并显示 toast;manifest 与 lockfile 已恢复,已下载文件可能保留。安装响应丢失后会请求恢复结果;**核对安装状态**和重连会重试该请求。Host 已无活动请求时,**未能获取安装结果**允许检查插件列表后返回编辑。早于接收确认的取消请求会等待并自动重试;取消失败可手动重试。隐藏的任务通过 toast 通知结果,不会重新弹出对话框。 diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css index 595b38885c..4b7b5f55a2 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.module.css @@ -979,6 +979,12 @@ --dsw-elevation-stroke-color: var(--dsw-alias-border-l1); box-shadow: var(--dsw-elevation-prominent); min-width: 0; + max-width: var(--dsh-anchored-max-width, none); + max-height: var(--dsh-anchored-max-height, none); + overflow-x: hidden; + overflow-y: auto; + --dsh-scrollbar-thumb: var(--dsw-alias-scrollbar-bg-l2); + --dsh-scrollbar-thumb-hover: var(--dsw-alias-scrollbar-hover-l2); } .registryOption { diff --git a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx index adacb15d71..242ca6f291 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -735,14 +735,14 @@ describe('PluginManagerPage', () => { pkg({ name: '@acme/dsh-tool', enabled: false }), // Selected by the profile but not a bundle: a problem the person can switch off, in the profile's own group. pkg({ name: 'dsh-selected', installed: false, error: { code: 'not-bundle' } }), - pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', installed: false, optional: true, removable: false, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', installed: false, optional: true, removable: false, enabled: false }), ], busy: ['dsh-protected'], }) const cards = screen.getAllByRole('listitem') // Offered extensions precede installed bundles. expect(cards.map(card => card.getAttribute('data-plugin-package'))).toEqual([ - '@deepseek-ai/dsh-experimental-agent-team-profile', 'dsh-better-sidebar', 'dsh-broken', 'dsh-protected', '@acme/dsh-tool', 'dsh-selected', + '@deepseek-ai/dsh-experimental-voice-input-bundle', 'dsh-better-sidebar', 'dsh-broken', 'dsh-protected', '@acme/dsh-tool', 'dsh-selected', ]) expect(cards.map(card => card.getAttribute('data-plugin-status'))).toEqual(['disabled', 'running', 'problem', 'running', 'disabled', 'problem']) // Group titles have no counts; the official bundle retains its experimental marker. @@ -776,11 +776,11 @@ describe('PluginManagerPage', () => { ].map(name => pkg({ name })), pkg({ name: '@acme/dsh-base', readOnlyReason: 'management-required' }), pkg({ name: 'dsh-better-sidebar' }), - pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', installed: false, optional: true, removable: false }), + pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', installed: false, optional: true, removable: false }), ], }) expect(screen.getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package'))).toEqual([ - '@deepseek-ai/dsh-experimental-agent-team-profile', '@acme/dsh-base', 'dsh-better-sidebar', + '@deepseek-ai/dsh-experimental-voice-input-bundle', '@acme/dsh-base', 'dsh-better-sidebar', ]) expect(document.querySelector('[data-plugin-count]')).toBeNull() }) @@ -789,7 +789,7 @@ describe('PluginManagerPage', () => { const name = '@deepseek-ai/dsh-experimental-terminal-bundle' const b = renderTab({ packages: [ pkg({ name, official: true, enabled, rows: [row()] }), - pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', official: true }), + pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', official: true }), ] }) expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.moreAction })) @@ -807,7 +807,7 @@ describe('PluginManagerPage', () => { it('keeps a shipped bundle out of both lists until one of its declared rows runs', () => { const hidden = '@deepseek-ai/dsh-experimental-liveshare' - const shown = '@deepseek-ai/dsh-experimental-agent-team-profile' + const shown = '@deepseek-ai/dsh-experimental-voice-input-bundle' const offer = (rows: readonly PackageRow[]): PackageView => pkg({ name: hidden, official: true, installed: false, optional: true, removable: false, enabled: false, listedByDefault: false, rows, }) @@ -881,16 +881,16 @@ describe('PluginManagerPage', () => { }) it('opens an official bundle\'s page with its beta tag and no uninstall, and switches it on', () => { - const title = 'Agent Teams' + const title = 'Voice input' const { actions } = renderTab({ - packages: [pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', meta: { title }, installed: false, optional: true, removable: false, enabled: false })], + packages: [pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', meta: { title }, installed: false, optional: true, removable: false, enabled: false })], }) fireEvent.click(screen.getByRole('button', { name: en.openDetail.replace('{name}', title) })) const detail = document.querySelector('[data-plugin-detail]') as HTMLElement expect(within(detail).getByText(en.statusBeta)).toBeTruthy() expect(within(detail).queryByRole('button', { name: en.uninstallLabel.replace('{name}', title) })).toBeNull() fireEvent.click(within(detail).getByRole('switch', { name: en.enableToggle.replace('{name}', title) })) - expect(actions.setEnabled).toHaveBeenCalledExactlyOnceWith('@deepseek-ai/dsh-experimental-agent-team-profile', true) + expect(actions.setEnabled).toHaveBeenCalledExactlyOnceWith('@deepseek-ai/dsh-experimental-voice-input-bundle', true) }) it('keeps the persisted selection while marking a failed component as a problem', () => { @@ -915,7 +915,7 @@ describe('PluginManagerPage', () => { }) it.each([ - ['@deepseek-ai/dsh-experimental-agent-team-profile', true], + ['@deepseek-ai/dsh-experimental-voice-input-bundle', true], ['@deepseek-ai/dsh-experimental-auto-review', true], ['@deepseek-ai/dsh-experimental-fixture-input', false], ['@deepseek-ai/dsh-cua-bundle', true], @@ -1198,11 +1198,11 @@ describe('PluginManagerPage', () => { } it('keeps configuration and installed plugins on the main list and shows eligible official plugins on the secondary page', () => { - const team = '@deepseek-ai/dsh-experimental-agent-team-profile' + const team = '@deepseek-ai/dsh-experimental-voice-input-bundle' renderTab( { packages: [ pkg({ name: '@deepseek-ai/dsh-experimental-badge-skill-bundle', official: true, enabled: false }), - pkg({ name: '@deepseek-ai/dsh-experimental-agent-team-profile', installed: false, optional: true, removable: false, enabled: false }), + pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', installed: false, optional: true, removable: false, enabled: false }), pkg({ name: '@deepseek-ai/dsh-subagent-claude-code', official: true, availability: 'missing', installed: false, enabled: false }), pkg({ name: '@deepseek-ai/dsh-subagent-codex', official: true, enabled: false }), pkg({ name: '@deepseek-ai/dsh-experimental-tool-worktree', official: true, enabled: false }), @@ -1223,7 +1223,7 @@ describe('PluginManagerPage', () => { expect(within(extensions).getByRole('heading', { name: en.extensionsTitle })).toBeTruthy() expect(within(extensions).getByRole('button', { name: en.moreAction }).textContent).toBe(en.moreAction) expect(within(extensions).getAllByRole('listitem').map(card => card.getAttribute('data-plugin-package'))) - .toEqual(['@deepseek-ai/dsh-experimental-agent-team-profile', '@acme/new-official']) + .toEqual(['@deepseek-ai/dsh-experimental-voice-input-bundle', '@acme/new-official']) expect(document.querySelector('[data-plugin-count]')).toBeNull() expect(within(basic).getByText('Limits every command.')).toBeTruthy() expect(within(basic).queryByRole('switch', { name: en.enableToggle.replace('{name}', 'Shell') })).toBeNull() @@ -1364,7 +1364,7 @@ describe('PluginManagerPage', () => { '@deepseek-ai/dsh-experimental-tool-worktree', '@deepseek-ai/dsh-personalized-recommendations', ])('pins enabled %s onto the main list and removes it when disabled', (first) => { - const team = '@deepseek-ai/dsh-experimental-agent-team-profile' + const team = '@deepseek-ai/dsh-experimental-voice-input-bundle' const second = '@deepseek-ai/dsh-experimental-cot-translation-bundle' const entry = (name: string, enabled: boolean): PackageView => pkg({ name, official: true, enabled }) const b = renderTab({ packages: [entry(second, true), entry(team, true), entry(first, false)] }) diff --git a/packages/client/ui-plugin-market/tests/discover.client.spec.tsx b/packages/client/ui-plugin-market/tests/discover.client.spec.tsx index 965275e9f8..9597605788 100644 --- a/packages/client/ui-plugin-market/tests/discover.client.spec.tsx +++ b/packages/client/ui-plugin-market/tests/discover.client.spec.tsx @@ -201,6 +201,7 @@ describe('DiscoverSection', () => { expect(screen.queryByRole('menuitem', { name: en.sortRelevance })).toBeNull() expect(actions.search).toHaveBeenCalledTimes(4) } finally { + cleanup() vi.useRealTimers() } }) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 8bb6988406..d04786950e 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,11 +18,11 @@ en: ead6be55c7c9d7cf zh: 125ad36db7328551 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 289fe5c01b026e81 - zh: 5680066a8443fba9 + en: d898628500d48051 + zh: 3187f5e88b5d7ba5 /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: - en: f13b4ba09521d300 - zh: a6093993d8fd0cdb + en: 0d756c1e8207181d + zh: 921ce997c6b14823 /deepseek-ai-dsh-client-ui-primitives/use-this-package/rendering-agent-output: en: 3271871a42bd52c8 zh: 89b7a9f03018454d @@ -54,8 +54,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-primitives/known-limitations-and-deferred-work: - en: 2f2db9565903b4e6 - zh: ca9d8fed836d857c + en: 6b4d21406db53e7c + zh: aa130102a8f7cd13 /deepseek-ai-dsh-client-ui-primitives/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index 4e538ecaeb..299c78633c 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -45,11 +45,11 @@ Check this table before writing a control in a feature package. A plugin cannot | `Button` | Clickable action; `variant` selects `primary`, `ghost`, `outline`, or `toolbar`. Outlined actions use an inset hairline. Its ref targets the native button for focus and overlay anchoring. | | `Switch` | Two-state toggle, 36×20. The off-state thumb reads `--dsw-alias-switch-thumb` so it stays light in both themes, and the on-state thumb contrasts with the brand track. Disabled controls use half opacity. `label` is required, so the control cannot ship unnamed. | | `SegmentedControl` | Tablist of two or more equal-width segments with one sliding indicator, for switching a card or panel between a few modes; the owner holds the selection and `label` names the list. `id` seeds each tab's id (`-`) and the panel it controls (`--panel`), which the owner renders and points back at the tab with `aria-labelledby`; a segment may be `disabled` with a `title`, and `disabled` on the control locks every segment while the shown panel has work in flight. | -| `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. | +| `Checkbox` | Labeled native checkbox with controlled state, keyboard interaction, and disabled styling; the caller supplies localized `label` text. `modalAutofocus` marks the input for its owning Modal's initial focus without moving focus itself. | | `Input` | Single-line text entry for search boxes and inline forms. Its ref targets the native input for focus and is cleared on unmount. | | `InlineEditor` | Autofocused multi-line inline editor for short drafts such as queued messages and goals. It grows with its text and its width up to six lines, then scrolls; Enter saves, Shift+Enter breaks the line, Enter during IME composition does nothing, and Escape cancels. The caller supplies the localized `label` and rebinds the scrollbar on an elevated surface. | | `ZoomControls`, `DOCUMENT_ZOOM` | Floating document zoom controls with localized labels, fixed presets, and visibility/activity callbacks. An omitted `fit` hides the fitting row. The toolbar carries `data-document-zoom-controls`, plus `data-document-zoom-visible` while visible. An owner `className` overrides `bottom` and `max-width` regardless of stylesheet order; `inset-inline-start` and `transform` center the toolbar and move it on enter and exit, `opacity` fades it, and all three stay with the primitive. Renderers share the published scale limits. | -| `Menu`, `MenuItemButton` | Dropdown of `items` data rows, separators, and group labels, with nested submenus; `children` adds component rows, each a `MenuItemButton` (`separatorBefore` starts a new group), in the same list. `MenuItemButton.current` exposes the current page or view through `aria-current` without changing selection or appearance. Every row shares the styling, the keyboard walk, and the focus return; closing stays the owner's state change for both kinds. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. | +| `Menu`, `MenuItemButton` | Dropdown of `items` data rows, separators, and group labels, with nested submenus; `children` adds component rows, each a `MenuItemButton` (`separatorBefore` starts a new group), in the same list. `MenuItemButton.current` exposes the current page or view through `aria-current` without changing selection or appearance. Every row shares the styling, the keyboard walk, and the focus return; closing stays the owner's state change for both kinds. While open, ↑/↓ (with Home and End) walk the list, Tab settles the focused row, and Escape or Shift+Tab close back to the anchor; selecting a row also returns the keyboard to the anchor unless the owner moved it itself. Only a keyboard on the anchor or inside the list is intercepted, and `autoFocus` decides solely whether opening focuses the first row. A disabled `MenuItemButton` with a `disabledReason` stays hoverable and focusable (`aria-disabled`) but cannot be activated; it shows the reason in a `Tooltip` and exposes it as the row's description. | | `MenuGroup`, `observeStickyMenuGroups` | Localized, accessible groups for custom menus and listboxes, with shared sticky-heading styling and native intersection/size observation; the caller owns the observer's lifetime. | | `Pill` | Selectable capsule button for view switchers and filters; takes `active` and `onClick`. | | `SegmentedTabs` | Controlled equal-width tabs with a sliding indicator and Left/Right, Home, and End navigation. The caller supplies labels, tab/panel ids, and panel content. Default `size="md"` is 42px tall with a 4px inset; `size="sm"` is 34px tall with a 2px inset. | @@ -61,12 +61,13 @@ Check this table before writing a control in a feature package. A plugin cannot | `AnimatedRows` | Keyed list movement with 200 ms glides and 100 ms entry/exit fades. Starts after local pointer or keyboard input, honors reduced motion, and settles loading or view replacement. Mark rows with `data-row-key`, supply matching `rowKeys`, and position the parent for the inert exit overlay; `role` and `label` belong to the caller. | | `useRowDragPreview` | Native drag preview using an inert offscreen row copy. The optional `inheritedProperties` list names the CSS custom properties whose computed values the offscreen wrapper copies; omitting it copies none. Keep the list reference stable, because replacing it clears an active preview. Unlisted custom properties follow normal inheritance at the preview's location. Supply a class for the surface background and, for a child drag handle, pass the row to `start`; `clear` and unmount remove the copy. | | `TextShimmer` | One left-to-right highlight across a row’s title, separators, summary, and suffix, with a 300ms initial delay, a one-second sweep and a 500ms rest. The mask spans the content width, capped by the visible row and tilts 15° from vertical, with a flat peak and soft edges. The moving decoration stays clipped to the row without enlarging its scrollable area. Base text inherits the caller’s color, including hover changes; the theme supplies the translucent highlight. Place icons and chevrons outside `TextShimmer` so only text and separators receive the highlight. A string child uses the same retained text interface; nested `TextShimmer` instances share the outer animation. Composite children render twice while active and must have no effects or element ids. Mark separators with `data-shimmer-decoration` so their fill receives the highlight. `DisclosureRow` forwards `contentClassName` for the text area and `contentLayoutClassName` for its inner layout. The inert decorative copy is excluded from interaction, selection, and accessibility; text updates retain the animation, and reduced-motion mode keeps the static base. | -| `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. | -| `RiskConfirmation` | Sensitive action gated behind an explicit checkbox. | +| `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. `tone="warning"` places an amber warning icon in the title and removes the body's extra top margin; other dialogs retain their spacing. | +| `RiskConfirmation` | Sensitive action gated behind an explicit checkbox, using the shared warning-title layout. | | `Tooltip` | Hover and keyboard-focus text anchored to a cloned child; optional `delayMs` controls hover delay and `focusDelayMs` controls keyboard-focus delay, both defaulting to 0 ms. Optional `portal` rendering escapes clipping containers and ancestor stacking contexts that cap the bubble's z-index. | | `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. | | `DraggableImage` | Original-image gestures with explicit transfer and feedback callbacks. | | `ImageLightbox` | Shared image modal with focus restoration and Escape dismissal. | +| `useAnchoredPosition` | Fixed-panel coordinates that follow the anchor through browser zoom, scrolling, and resizing. | | `Toast` | Transient top-center banner held for the owner's `holdMs`. | | `SettingsForm`, `SettingsValueField`, `SettingsSecretField` | The frame and the controls of a plugin's settings page: the frame takes its copy as `labels`, saves only on its button, and discards on unmount; a value field shows staged text with the overridden badge and reset; a secret field starts blank, requests no saved-password autofill, and reports only whether a value is configured. | | `SettingsFormModel`, `settingsNumberField`, `settingsTextField` | The staged-edit model behind such a page over a settings scope: drafts are staged and written on save, a field is overridden by its presence in the user layer, and a save that did not land keeps its drafts. | @@ -96,7 +97,7 @@ Writing your own component in your own package is fine when the need is genuinel ### Controls and icons -The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` for the supplied one-pixel artwork or `Medium` for the same geometry at a 1.3px stroke; the `size` prop controls rendered dimensions. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredPosition` and `useAnchoredMaxHeight` keep floating panels and bottom-anchored overlays clamped to the viewport and following their anchor; anchored overlays and portalled `Menu` add 20px to the frame's published top clearance, or keep 20px in native fullscreen, while preserving their own minimum margins in ordinary browsers; while an anchor is inside that top strip, its overlay, including a `HoverCard`, is never pushed lower than the anchor's bottom edge plus the overlay's gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists follow their anchor during dragging and CSS transforms, and stop tracking when closed. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. +The catalog above lists what each export is for; this section covers the behavior that props alone do not show. Product icon names omit artboard sizes and end in `Regular` for the supplied one-pixel artwork or `Medium` for the same geometry at a 1.3px stroke; the `size` prop controls rendered dimensions. Named components keep the chosen weight visible at import sites; the library owns stroke geometry instead of consumer CSS overrides. Each product icon renders an `` box with one `` of its `dsw-icon--` symbol, for example `dsw-icon-search-outline-regular`, and names that id in `data-icon`. `ICON_SYMBOLS` holds every symbol's default SVG document; ui-theme renders the document icon sprite from it, and an icon whose symbol is missing renders nothing. Artwork reached through `` inherits `currentColor` and CSS variables from the use site. Each product, reference, link, and permission glyph intentionally keeps both weight exports even when the current product uses only one, so callers can choose emphasis without adding another API later; fill-only pairs render identically. `IconWarningOutlineRegular`/`Medium` use a circle; `IconWarningTriangleOutlineRegular`/`Medium` use a rounded triangle. `FishLogo` and `BrandWordmark` fill brand slots. `FileTypeIcon` renders the traditional 28px spreadsheet, folder, HTML, image, Markdown, generic, PDF, PPT, video, and Word glyphs, and uses the imported square technology artwork for the established 48 code and configuration categories. The import replaces artwork only: archive-only categories do not extend `CodeFileType`. `classifyFileType` applies exact filename, prefix, suffix, optional project-context, and extension rules in that order; React names win over TypeScript/JavaScript, Angular suffixes win over their base extension, and a Dart file becomes Flutter only when the supplied project files contain a `pubspec.yaml` with `flutter:`. Markdown and SVG remain traditional Markdown and image files. Spreadsheet mappings include CSV, TSV, Excel workbooks and templates, OpenDocument spreadsheets, and Numbers; KEY maps to slides, while RTF/ODT/Pages map to documents. `fileExtension` exposes the same basename and final-dot parsing for adjacent metadata labels. Traditional glyphs use a solid category-colored sheet with a white mark and translucent white corner; the generic code glyph uses angle brackets and a slash at the supplied 1.35px stroke; the generic file uses a grey sheet and darker grey corner. Callers may override the sheet color through `--dsh-file-type-icon-color`. The full-color technology artwork is the deliberate exception and retains its embedded palette. All glyphs are decorative and carry no label. `LinkIconMedium` is the leading glyph for clickable artifact links — globe, folder, code, image, document, or plain paper, and for a `url` link the mark of a well-known site named by its `href` — the developer sites a transcript usually cites (GitHub, GitLab, npm, PyPI, Stack Overflow, MDN, Wikipedia, Hacker News, YouTube, X, Bilibili, Zhihu, Juejin, CSDN) and mainstream search, video, social, shopping, and reference sites (Google, Baidu, DuckDuckGo, TikTok, Netflix, Spotify, Facebook, Instagram, Reddit, Telegram, WhatsApp, WeChat, QQ, Weibo, Taobao, AliExpress, eBay, Quora, V2EX, Apple) — while `classifyLinkPath` folds the shared file types into that existing six-category vocabulary. `ConnectionIndicator` renders a warning-colored disconnected action whose permanent retry glyph marks the retry action beside the owner-supplied outage label, the shared ongoing loader in the same warning color as its label whose one-to-three dots advance every 500ms independently of retry timing, or a success-colored recovered status. Clicking either warning state requests an immediate reconnect; no hover interaction changes the copy. The pill fades in on appearance, fades out for 150ms before unmounting, and sizes to its current label. Its owner supplies visibility, the recovery hold, localized labels, and the immediate-reconnect callback; the primitive uses no native title tooltip. `useAnchoredPosition` measures fixed, body-portaled panels synchronously before paint and follows window scrolling, Visual Viewport changes, anchor movement, and element resizing. It normalizes WebKit client coordinates, preserves viewport margins and desktop frame clearance, and exposes visible size limits through `--dsh-anchored-max-width` and `--dsh-anchored-max-height`; panel CSS consumes those variables. `frameClearance: false` keeps only the viewport margin for pointer-positioned menus. `layoutKey` requests measurement after a content change, and `minWidthFromAnchor` follows the anchor width within the visible viewport. A missing host-provided anchor rect hides the panel until it becomes available. `useAnchoredMaxHeight` keeps bottom-anchored overlays within the visible viewport; an oversized panel keeps the near margin instead of sliding off that edge. A submenu-free portalled `Menu` caps its card height against the dynamic viewport so its pinned footer stays on screen. Anchored overlays and portalled `Menu` add 20px to the frame's published top clearance, or keep 20px in native fullscreen, while preserving their own minimum margins in ordinary browsers; while an anchor is inside that top strip, its overlay, including a `HoverCard`, is never pushed lower than the anchor's bottom edge plus the overlay's gap. `HoverCard` keeps its portaled preview reachable across the anchor gap and can expose a copy button through the `copyText` prop. Touch entry does not open its preview or intercept the anchor action. Mouse entry requires an available hover-capable pointer; keyboard focus remains independent of that capability. Its `preview` variant uses the anchor or `widthAnchorRef` element’s width minus 48px, centers the panel with 24px side insets, and places it above or below the row within the viewport. The panel keeps the frame’s top clearance except below an anchor inside the top strip, caps its height at 420px, and follows content and anchor resizing; Escape or pointer and keyboard activation of the anchor dismisses it. The whole preview fades in and out over 100ms; a closing preview stops receiving pointer input and unmounts after the fade. Re-entering the anchor during the fade restores it. Reduced-motion preferences suppress the transition. Copy labels are required only when copying is enabled. `HoverCard` and nested action tooltips display independently; use `Tooltip.portal` to layer the small bubble above the card. A visible nested `Tooltip` suppresses only its enclosing tooltip, not the hover card. `Toast` uses the owner's `holdMs` for both the fade delay and its hold-and-fade lifetime. Rerenders with unchanged `holdMs` do not restart that lifetime; completion uses the latest callback, and fully faded actions cannot receive input. A new component key restarts the banner. `rankByName` is the `/` menu's shared candidate ranker for the command and skill sources: the query must be a case-insensitive ordered subsequence of the name; prefix hits rank first, then alignment score, then source order. Portalled `Menu` lists use `useAnchoredPosition` to follow their anchor during dragging, CSS transforms, and browser zoom, including Safari visual-viewport panning; tracking stops when closed. They stay hidden until the first position resolves, and `autoFocus` waits until the list is visible. `Menu.autoFocus` focuses its first enabled item, supports Arrow Up/Down and Home/End navigation, and focuses the first button in the anchor on Escape; it is opt-in for action menus. `Tooltip` reads the anchor on hover or keyboard focus and fits its bubble from `ResizeObserver` border-box sizes. It stays hidden until its first fit, prefers the requested side, then tries the opposite and perpendicular sides, sliding along the anchor without covering it when a side fits. Horizontal placements keep a 10px gap; vertical placements use `gap` (8px by default). Width and height stay within a 12px viewport margin; text wraps, and content taller than the viewport scrolls when pinned. If no side fits, a stable viewport-bounded fallback can overlap the anchor. Viewport resize refreshes the anchor coordinates; label-size changes reuse them. Fitting does not synchronously measure the bubble or trigger a React render. Touch presses dismiss unpinned hints and do not trigger hover hints, including compatibility mouse events. Mouse entry opens hints only while `(any-hover: hover)` reports an available hover-capable input, excluding iOS mouse entry caused by a tapped icon changing. Keyboard focus and explicit click-to-open explanations remain available on touch-only devices. Opt-in `openOnClick` lets an informational button pin the bubble by click or tap and associates it with the anchor description. Another click or tap, Escape, Tab, or an outside pointerdown closes it. Ordinary action buttons execute their action directly without a touch tooltip. Opt-in `onlyWhenClipped` shows the bubble only when the anchor or an HTML element inside it overflows horizontally when the bubble is about to show, so a label that repeats ellipsis-cut text appears only while it adds information. @@ -237,8 +238,6 @@ These limits define how the atoms behave at the edges; they are current package - **Product icons need the ui-theme sprite** — each icon only references its symbol, so without ui-theme, or inside another document such as an iframe, the icon renders nothing. - **No `Active` `StateDot` variant** — the supported states are done, warning, ongoing, error, and idle. - **User-facing copy is required at the render site** — the atoms are zero-Cordis and cannot reach `ctx.locale`; each feature must supply complete localized labels through the primitive's typed props ([decision](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.md)). -- **Display math keeps fallback shapes** — a `$$x$$ trailing` on the opening line resolves through upstream inline math and leaves the surrounding prose in place, while the same trailing text on a later line declines the block and upstream takes the prose up to the next lone `$$` or EOF; a block left open ends at the next lone `$$` or at EOF; a later fence behind a `%` comment that holds text closes nothing, so a block nothing else closes reaches the same fallback; a multi-line block whose opening line carries a solitary `$` stays in its paragraph unless a blank line separates them; and a container continuation line that leaves the item indentation hands the block to upstream, which drops the opening line. `$$` fence meta is no longer honored ([decision](../../../.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.md)). -- **A fence after a `\verb` delimiter is content** — the tokenizer reads the six characters before a fence, so the `$` right after `\verb` or `\verb*` is that command's delimiter rather than a closing fence, and a region whose text ends in `\verb` (`\verb**\verb*$$`) reads the same way. A fence inside an unterminated region (`\verb|$$`) still closes the block there, because the region's content is not parsed. - **`TerminalBlock` is not a terminal emulator** — it renders settled or still-running command output, not an interactive session: SGR colors, carriage return, backspace, erase-in-line, tab stops, and character width are honored; absolute cursor positioning, screen clearing, and alternate-screen sequences are stripped. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 5e0262cdc2..29fd963e29 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -45,11 +45,11 @@ kind: "package-library" | `Button` | 可点击操作;`variant` 选择 `primary`、`ghost`、`outline` 或 `toolbar`。描边操作使用内侧细线。ref 指向原生按钮,供焦点控制与浮层锚定使用。 | | `Switch` | 36×20 的双态开关。关闭态滑块读取 `--dsw-alias-switch-thumb`,在两种主题下均保持亮色;开启态滑块与品牌色轨道形成对比。禁用控件使用半透明样式。`label` 必填,控件不可能在没有名称的情况下发布。 | | `SegmentedControl` | 两段或更多等宽分段加一个滑动指示块的 tablist,用于在几种模式间切换一张卡片或面板;选中项由调用方持有,`label` 为列表命名。`id` 派生每个 tab 的 id(`-`)及其控制的面板 id(`--panel`),面板由调用方渲染并用 `aria-labelledby` 指回 tab;分段可 `disabled` 并带 `title`,控件级 `disabled` 在当前面板有进行中的操作时锁住全部分段。 | -| `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。 | +| `Checkbox` | 带标签的原生复选框,支持受控状态、键盘交互和禁用样式;调用方提供本地化的 `label` 文本。`modalAutofocus` 将输入标记为所属 Modal 的初始焦点,本身不会移动焦点。 | | `Input` | 单行文本输入,用于搜索框与行内表单。ref 指向原生输入框,供焦点控制使用,并在卸载时清空。 | | `InlineEditor` | 自动聚焦的多行行内编辑器,用于排队消息、goal 等短草稿。它随文本和宽度增高,最多六行,之后滚动;Enter 保存,Shift+Enter 换行,输入法组合中的 Enter 不生效,Escape 取消。调用方提供本地化 `label`,并在 elevated 表面上重绑滚动条。 | | `ZoomControls`, `DOCUMENT_ZOOM` | 悬浮文档缩放控件,接收本地化标签、固定预设,以及可见性和交互状态回调。省略 `fit` 时不显示适配项。工具栏带 `data-document-zoom-controls`,可见时另带 `data-document-zoom-visible`。owner 的 `className` 覆盖 `bottom` 与 `max-width`,不受样式表加载顺序影响;`inset-inline-start` 和 `transform` 负责居中与进出场位移,`opacity` 负责淡入淡出,三者都由原语保留。渲染器共用导出的缩放范围。 | -| `Menu`, `MenuItemButton` | 由 `items` 数据行、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单;`children` 在同一列表中加入组件行,每行一个 `MenuItemButton`(`separatorBefore` 开启新分组)。`MenuItemButton.current` 通过 `aria-current` 标识当前页面或视图,不改变选中状态或外观。所有行共享样式、键盘走位与焦点归还;两类行的关闭都是 owner 状态的改变。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 | +| `Menu`, `MenuItemButton` | 由 `items` 数据行、分隔线与分组标题构成的下拉菜单,支持嵌套子菜单;`children` 在同一列表中加入组件行,每行一个 `MenuItemButton`(`separatorBefore` 开启新分组)。`MenuItemButton.current` 通过 `aria-current` 标识当前页面或视图,不改变选中状态或外观。所有行共享样式、键盘走位与焦点归还;两类行的关闭都是 owner 状态的改变。打开期间 `↑`/`↓`(以及 Home、End)在列表中走位,Tab 选定聚焦行,Escape 或 Shift+Tab 关闭并把焦点还给锚点;选定一行同样把键盘还给锚点——除非拥有者自己移动了焦点。只拦截位于锚点或列表内的键盘,`autoFocus` 仅决定打开时是否聚焦首行。 带 `disabledReason` 的禁用 `MenuItemButton` 仍可悬停和聚焦(`aria-disabled`),但不能激活;它在 `Tooltip` 中显示原因,并把原因作为该行的描述。 | | `MenuGroup`、`observeStickyMenuGroups` | 为自定义菜单与列表框提供本地化、可访问的分组,共用吸顶标题样式与原生交叉/尺寸观察;调用方负责观察器的生命周期。 | | `Pill` | 可选中的胶囊按钮,用于视图切换与筛选器;接受 `active` 与 `onClick`。 | | `SegmentedTabs` | 受控的等宽分段标签,支持滑动指示条及左/右方向键、Home、End 导航。调用方提供文案、标签与面板 id,以及面板内容。默认 `size="md"` 总高 42px、内边距 4px;`size="sm"` 总高 34px、内边距 2px。 | @@ -61,12 +61,13 @@ kind: "package-library" | `AnimatedRows` | 带键列表的位移动画:移动为 200 ms,进出淡变为 100 ms。列表内发生指针或键盘输入后才启用,遵循减少动态效果设置,加载或替换视图时直接完成。为行标记 `data-row-key` 并传入对应的 `rowKeys`,为父容器设置定位以承载不可交互的退出层;`role` 和 `label` 由调用方提供。 | | `useRowDragPreview` | 使用不可交互的离屏行副本生成原生拖拽预览。可选的 `inheritedProperties` 列表指定离屏包装层需要复制其计算值的 CSS 自定义属性;省略时不复制。列表引用需保持稳定,因为替换列表会清除活动预览。未列出的自定义属性按预览所在位置的正常继承规则生效。传入设置表面底色的类名;拖拽来自子级手柄时,将行元素传给 `start`;`clear` 和卸载会移除副本。 | | `TextShimmer` | 同一道高光从左到右扫过一行的标题、分隔符、摘要与后缀:首次等待 300ms,扫动一秒,再静止 500ms。遮罩覆盖内容宽度,并限制在可见行宽内,相对垂直方向倾斜 15°,峰值区域平坦,两侧柔和渐隐。移动的装饰层始终裁剪在行内,不会扩大可滚动区域。底色继承调用方的颜色,包括悬停变化;主题提供半透明高光。图标和箭头放在 `TextShimmer` 外,只有文字和分隔符参与扫光。字符串子节点沿用稳定的文字接口;嵌套的 `TextShimmer` 共用外层动画。活动期间组合子节点渲染两次,因此不得带副作用或元素 id。分隔符标记 `data-shimmer-decoration`,让填色参与扫光。`DisclosureRow` 将 `contentClassName` 传给文字区域,将 `contentLayoutClassName` 传给内部布局。惰性装饰副本不参与交互、选区和无障碍访问;文字更新保留动画,减少动态效果模式保留静态底色。 | -| `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。 | -| `RiskConfirmation` | 以显式复选框把关的敏感操作确认。 | +| `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。`tone="warning"` 在标题中显示橙色警告图标,并移除正文额外的顶部间距;其他弹窗的间距保持不变。 | +| `RiskConfirmation` | 以显式复选框把关的敏感操作确认,采用共用的警告标题布局。 | | `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 | | `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。 | | `DraggableImage` | 通过显式传递与反馈回调提供原图拖放。 | | `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 | +| `useAnchoredPosition` | 随浏览器缩放、滚动和尺寸变化持续跟随锚点的 fixed 面板坐标。 | | `Toast` | 顶部居中的瞬时横幅,保持时长由所有者的 `holdMs` 决定。 | | `SettingsForm`、`SettingsValueField`、`SettingsSecretField` | 插件设置页的框架与控件:框架以 `labels` 接收文案,只在按钮点击时保存,卸载即丢弃;值字段显示暂存文本以及已覆盖标签和重置;密文字段每次为空,请求浏览器不要自动填入已保存的密码,只报告是否已配置。 | | `SettingsFormModel`、`settingsNumberField`、`settingsTextField` | 这类页面背后基于设置 scope 的暂存编辑模型:草稿先暂存、保存时写入,字段是否被覆盖看用户层是否含有它,未落地的保存保留草稿。 | @@ -96,7 +97,7 @@ kind: "package-library" ### 控件与图标 -上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 表示原始 1px 图形,以 `Medium` 表示同一几何的 1.3px 描边;`size` prop 控制渲染尺寸。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredPosition` 与 `useAnchoredMaxHeight` 让浮动面板与底部锚定浮层始终钳制在视口内并跟随锚点;锚定浮层与 portal 模式的 `Menu` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,其浮层(包括 `HoverCard`)不会被推到低于锚点底边加浮层间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 列表会在拖动和 CSS 变换期间跟随锚点,并在关闭时停止跟踪。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 +上面的目录说明每个导出的用途;本节讲 props 本身看不出来的行为。产品图标名称不含画板尺寸,以 `Regular` 表示原始 1px 图形,以 `Medium` 表示同一几何的 1.3px 描边;`size` prop 控制渲染尺寸。具名组件让所选线重在导入处可见;描边几何由组件库拥有,而不是由消费方 CSS 覆盖。每个产品图标渲染一个 `` 框,其中包含一个引用对应 `dsw-icon--` symbol 的 ``,例如 `dsw-icon-search-outline-regular`,并在 `data-icon` 中写出该 id。`ICON_SYMBOLS` 保存每个 symbol 的默认 SVG 文档;ui-theme 据此渲染文档的图标 sprite,缺少对应 symbol 的图标不渲染任何内容。通过 `` 引用的图形会从使用处继承 `currentColor` 与 CSS 变量。每个产品、引用、链接与权限图形都会有意保留两种线重导出,即使当前产品只使用其中一种,也让调用方无需再次扩展 API 就能选择强调程度;仅填充的成对图形外观相同。`IconWarningOutlineRegular`/`Medium` 使用圆形;`IconWarningTriangleOutlineRegular`/`Medium` 使用圆角三角形。`FishLogo` 与 `BrandWordmark` 填充品牌 slot。`FileTypeIcon` 渲染传统的 28px spreadsheet、folder、HTML、image、Markdown、generic、PDF、PPT、video 与 Word 图形,并为现有 48 个代码和配置类别使用导入的方形技术图形。该导入只替换图形:资源包中额外的类别不会扩展 `CodeFileType`。`classifyFileType` 按完整文件名、前缀、后缀、可选项目上下文、扩展名的顺序匹配;React 文件名优先于 TypeScript/JavaScript,Angular 后缀优先于基础扩展名,只有传入的项目文件包含带 `flutter:` 的 `pubspec.yaml` 时 Dart 文件才使用 Flutter。Markdown 与 SVG 仍分别使用传统 Markdown 与图片图形。表格映射包括 CSV、TSV、Excel 工作簿与模板、OpenDocument 表格和 Numbers;KEY 映射为幻灯片,RTF/ODT/Pages 映射为文档。`fileExtension` 为相邻元数据 label 暴露同一套 basename 与最终点号解析。传统图形使用实色分类底板、白色标记和半透明白色折角;通用代码图形使用尖括号与斜线,保留原图 1.35px 描边;通用文件使用灰色底板与较深灰色折角。调用方可通过 `--dsh-file-type-icon-color` 覆盖底板颜色。全彩技术图形是明确例外,会保留其内嵌调色板。所有图形都是装饰性的,不自带 label。`LinkIconMedium` 是可点击产物链接的前置图形——地球、文件夹、代码、图片、文档或纸张,`url` 链接的 `href` 指向已知站点时则改用该站点自己的标记——转写内容常引用的开发者站点(GitHub、GitLab、npm、PyPI、Stack Overflow、MDN、Wikipedia、Hacker News、YouTube、X、Bilibili、知乎、掘金、CSDN),以及主流搜索、视频、社交、购物与参考资料站点(Google、百度、DuckDuckGo、TikTok、Netflix、Spotify、Facebook、Instagram、Reddit、Telegram、WhatsApp、微信、QQ、微博、淘宝、速卖通、eBay、Quora、V2EX、Apple)——`classifyLinkPath` 把共享文件类型折叠进原有六类词汇。`ConnectionIndicator` 可渲染警告色的断联操作(常驻重试图形指明重试动作,断联文案由持有方提供)、与文案使用相同警告色的共享 ongoing loading 加一至三个点以独立于 retry 时序的 500ms 节奏推进的连接中状态,或成功色的恢复状态。点击任一警告状态都会请求立即重连;没有任何悬停交互会改变文案。药丸出现时淡入、卸载前淡出 150ms,宽度随当前 label 自适应。它的持有方提供可见性、恢复驻留时间、本地化 label 与立即重连回调;该原语不使用原生 title tooltip。`useAnchoredPosition` 在绘制前同步测量通过 body portal 渲染的 fixed 面板,跟踪窗口滚动、Visual Viewport 变化、锚点移动和元素尺寸变化。它统一 WebKit 的客户端坐标,保留视口边距和桌面标题栏避让,并通过 `--dsh-anchored-max-width`、`--dsh-anchored-max-height` 提供可见尺寸上限,由面板 CSS 应用。`frameClearance: false` 让按指针定位的菜单只保留视口边距。`layoutKey` 在内容变化后触发测量,`minWidthFromAnchor` 在可见视口内跟随锚点宽度。宿主提供的锚点矩形为空时,面板隐藏直到锚点可用。`useAnchoredMaxHeight` 将底部锚定浮层限制在可见视口内;过大的面板保留近端边距,不会滑出该边缘。无子菜单的 portal 模式 `Menu` 按动态视口限制卡片高度,使固定页脚保持可见。锚定浮层与 portal 模式的 `Menu` 在框架发布的顶部占用量上增加 20px,原生全屏时保留 20px,普通浏览器中沿用自身的最小边距;锚点位于该顶部区域内时,其浮层(包括 `HoverCard`)不会被推到低于锚点底边加浮层间距的位置。`HoverCard` 通过指针离开宽限期让采用 portal 的预览在跨过锚点间隙时仍可触及,并可通过 `copyText` prop 提供复制按钮。触摸进入不会打开预览,也不会拦截锚点操作。鼠标进入要求存在可悬停的指针设备;键盘聚焦不依赖该能力。其 `preview` 变体使用 anchor 或 `widthAnchorRef` 元素的宽度减去 48px,左右各内缩 24px,并在视口内放置于行的上方或下方。浮层避开框架顶部保留区(位于顶部区域内的锚点下方时除外),高度最多 420px,会跟随内容及 anchor 尺寸变化;Escape 或通过鼠标和键盘激活锚点可将其关闭。整个浮层的淡入和淡出各持续 100ms;关闭中的浮层停止接收指针输入,淡出后卸载。在淡出期间移回锚点可恢复显示。减少动态效果偏好会禁用过渡动画。只有启用复制时才必须提供复制标签。`HoverCard` 与嵌套的操作提示独立显示;使用 `Tooltip.portal` 将小气泡置于卡片上层。可见的嵌套 `Tooltip` 只隐藏外层 tooltip,不隐藏悬停卡片。`Toast` 使用调用方的 `holdMs` 同时控制淡出延迟与停留加淡出的总时长。`holdMs` 未变时,父组件重渲染不会重启该生命周期;完成时调用最新回调,完全淡出的操作不能接收输入。新的组件 key 会重新开始横幅周期。`rankByName` 是 `/` 菜单命令源与 skill(技能)源共享的候选排序器:查询必须是名字的不区分大小写的有序子序列;前缀命中排最前,其次按对齐分数,再按来源顺序。 portal 模式的 `Menu` 列表使用 `useAnchoredPosition` 在拖动、CSS 变换和浏览器缩放期间跟随锚点,包括 Safari visual viewport 平移;关闭时停止跟踪。首次定位完成前列表保持隐藏,`autoFocus` 等待列表可见后再聚焦。`Menu.autoFocus` 聚焦首个启用项,支持上下方向键与 Home/End 导航,并在 Escape 时聚焦 anchor 内的第一个按钮;操作菜单可显式启用。 `Tooltip` 在悬停或键盘聚焦时读取锚点位置,再根据 `ResizeObserver` 提供的边框盒尺寸调整气泡。首次定位前保持隐藏,优先使用指定方向,再尝试相反方向和垂直于该方向的两侧;只要某一侧容得下,就沿锚点平移而不遮挡锚点。左右放置保留 10px 间距,上下放置使用 `gap`(默认 8px)。宽高限制在视口内并保留 12px 边距;文本自动换行,超出视口高度的内容在固定气泡后可滚动。若所有方向都放不下,则使用稳定的视口内回退位置,可能遮挡锚点。视口尺寸变化会重新读取锚点坐标,标签尺寸变化则复用坐标;定位不会同步测量气泡,也不会触发 React 渲染。 触摸按下会关闭未固定的提示,且不会触发悬停提示,包括触摸后的兼容鼠标事件。只有 `(any-hover: hover)` 表明存在可悬停的输入设备时,鼠标进入才会打开提示,从而排除 iOS 因已点击图标变化而生成的鼠标进入事件。仅有触摸输入的设备仍可使用键盘聚焦提示和显式点击打开的说明。信息按钮可显式启用 `openOnClick`,通过鼠标或触摸点击固定气泡供阅读,并将内容关联为锚点的无障碍描述;再次点击、Escape、Tab 或外部 pointerdown 会关闭。普通操作按钮在触摸点击时直接执行操作,不显示 Tooltip。可选的 `onlyWhenClipped` 只在气泡即将显示时锚点或其内部某个 HTML 元素横向溢出才显示气泡,因此重复被省略号截断文本的标签只在能补充信息时出现。 @@ -237,8 +238,6 @@ kind: "package-library" - **产品图标依赖 ui-theme 的 sprite**:每个图标只引用自己的 symbol,因此没有 ui-theme 时,或在 iframe 等另一个文档中,图标不渲染任何内容。 - **`StateDot` 没有 `Active` 变体**:支持的状态为 done、warning、ongoing、error 和 idle。 - **面向用户的文案必须由渲染点提供**:这些原子组件是 zero-Cordis 的,拿不到 `ctx.locale`;各功能必须通过原子组件的带类型 prop 提供完整本地化 label(见[决策](../../../.agents/notes/implemented/architecture/2026-08-23-locale-owned-client-ui-copy.zh.md))。 -- **显示数学保留若干回退形状**:开围栏行上的 `$$x$$ trailing` 走上游行内数学,前后正文保持不变;同样形态出现在后续行时块被放弃,随后由上游把正文吞到下一个独占行 `$$` 或文件结尾;未闭合的块在下一个独占行 `$$` 或文件结尾结束;后续行的围栏若位于**含文本**的 `%` 注释之后则不闭合,若无其他围栏闭合,块走同一条回退;开围栏行含孤立 `$` 的多行块会留在段落内,除非与前文空一行;容器内续行若离开条目缩进,块交由上游 flow 处理并丢弃开围栏行。`$$` 围栏 meta 不再生效(见[决策](../../../.agents/notes/implemented/bug-fix/2026-09-17-multiline-display-dollar-math.zh.md))。 -- **紧跟 `\verb` 分隔符的围栏属于内容**:解析器只读取围栏之前的六个字符,因此紧跟 `\verb` 或 `\verb*` 的 `$` 是该命令的分隔符而不是闭合围栏,内容以 `\verb` 结尾的区域(`\verb**\verb*$$`)同理。未闭合区域内部的围栏(`\verb|$$`)仍会在该处闭合块,因为区域内容不被解析。 - **`TerminalBlock` 不是终端模拟器**:它渲染已结束或仍在运行的命令输出,而不是交互式会话:SGR 颜色、回车、退格、行内擦除、制表位与字符宽度会被遵循;绝对光标定位、清屏与备用屏幕序列会被剥离。 diff --git a/packages/client/ui-primitives/src/Checkbox.tsx b/packages/client/ui-primitives/src/Checkbox.tsx index bf1cbf9a65..e53456863d 100644 --- a/packages/client/ui-primitives/src/Checkbox.tsx +++ b/packages/client/ui-primitives/src/Checkbox.tsx @@ -11,19 +11,22 @@ import css from './Checkbox.module.css' * @param props.disabled - whether the control refuses changes. * @param props.title - optional localized hover text. * @param props.className - extra class for the label's placement. + * @param props.modalAutofocus - designate the input for the owning Modal's initial focus without React autoFocus. * @returns the label containing its checkbox. */ -export function Checkbox({ checked, onChange, label, disabled = false, title, className }: { +export function Checkbox({ checked, onChange, label, disabled = false, title, className, modalAutofocus = false }: { checked: boolean onChange: (next: boolean) => void label: string disabled?: boolean title?: string | undefined className?: string | undefined + modalAutofocus?: boolean }) { return ( {label} diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index d3c24aad2b..6745788276 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -30,8 +30,8 @@ top: calc(100% + 4px); left: 0; z-index: 100; - min-width: 144px; - max-width: 360px; + min-width: min(144px, var(--dsh-anchored-max-width, 100vw)); + max-width: min(360px, var(--dsh-anchored-max-width, 100vw)); } /* Legacy slots can render no rows; keep empty context popups out of layout. */ @@ -63,12 +63,16 @@ /* Viewport fit: the card stops 12px short of the viewport's top/bottom edges * (the portal MARGIN in Menu.tsx; the top side widens to the frame's published - * overlay inset) and taller content scrolls inside - * .viewport, so a pinned .footer stays visible. Menus with submenu rows skip - * this class — the overflow clip would crop the side card, so they rely on - * staying short. */ + * overlay inset) and taller content scrolls inside .viewport, so a pinned + * .footer stays visible. The dynamic unit, not `vh`: mobile browser chrome + * shrinks the visible height while `vh` keeps the taller bars-hidden height, so + * a `vh` cap exceeds the viewport the placement clamps into and the card ends + * up taller than the screen showing it. Menus with submenu rows skip this + * class — the overflow clip would crop the side card, so they rely on staying + * short. */ .scrollable { - max-height: calc(100vh - 12px - max(12px, var(--dsh-frame-overlay-top, 12px))); + max-height: min(calc(100vh - 12px - max(12px, var(--dsh-frame-overlay-top, 12px))), var(--dsh-anchored-max-height, 100vh)); + max-height: min(calc(100dvh - 12px - max(12px, var(--dsh-frame-overlay-top, 12px))), var(--dsh-anchored-max-height, 100vh)); } .viewport { @@ -121,7 +125,7 @@ } @media (hover: hover) { - .item:hover:not(:disabled) { + .item:hover:not(:disabled):not([aria-disabled='true']) { background: var(--dsw-alias-interactive-bg-hover); } } @@ -145,7 +149,7 @@ .list.compactList, .submenu.compactList { - min-width: 156px; + min-width: min(156px, var(--dsh-anchored-max-width, 100vw)); padding: 4px; } @@ -173,7 +177,8 @@ line-height: 15px; } -.item:disabled { +.item:disabled, +.item[aria-disabled='true'] { opacity: 0.4; cursor: not-allowed; } @@ -251,7 +256,7 @@ } @media (hover: hover) { - .danger:hover:not(:disabled) { + .danger:hover:not(:disabled):not([aria-disabled='true']) { background: var(--dsw-alias-interactive-bg-hover-danger); } } @@ -312,4 +317,7 @@ .list[data-menu-phase='dismiss'], .list[data-menu-phase='replace'] { pointer-events: none; } -.list[data-context-menu].scrollable { max-height: calc(100vh - 24px); } +.list[data-context-menu].scrollable { + max-height: min(calc(100vh - 24px), var(--dsh-anchored-max-height, 100vh)); + max-height: min(calc(100dvh - 24px), var(--dsh-anchored-max-height, 100vh)); +} diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index 753de26f95..095ea4d9bd 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -1,15 +1,16 @@ -import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode, SyntheticEvent } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' import { IconCheckOutlineRegular } from './icons/index.tsx' -import { overlayTopMargin } from './overlay-top-margin.ts' +import { useAnchoredPosition } from './useAnchoredPosition.ts' import { usePointerGrace } from './pointer-grace.ts' import { isBehindModal } from './useModalLayer.ts' import { observeComposition } from './keyboard-composition.ts' import { focusWithoutRing } from './focus.ts' import { ShortcutKeys } from './ShortcutKeys.tsx' import { MenuSurface } from './MenuSurface.tsx' +import { Tooltip } from './Tooltip.tsx' import css from './Menu.module.css' /** Selectable row (optionally with a nested submenu). */ @@ -55,6 +56,12 @@ export interface MenuItemButtonProps { current?: boolean /** Whether the row cannot be activated. */ disabled?: boolean + /** + * Why the disabled row cannot be activated. The row then stays hoverable and + * focusable, shows the reason in a tooltip, and exposes it as the row's + * description; an enabled row ignores it. + */ + disabledReason?: string | undefined /** Destructive row: error-colored text/icon and danger hover fill. */ danger?: boolean /** @@ -79,30 +86,41 @@ export interface MenuItemButtonProps { * @param props.icon - optional leading icon. * @param props.current - whether the row identifies the currently displayed page or view. * @param props.disabled - whether the row cannot be activated. + * @param props.disabledReason - why a disabled row cannot be activated, shown in a tooltip and read as its description. * @param props.danger - whether to use the destructive row colors. * @param props.separatorBefore - whether this row starts a new group (hairline above it). * @param props.onSelect - row activation callback. * @returns one menu-item row. */ export function MenuItemButton({ - children, shortcut, icon, current, disabled = false, danger = false, separatorBefore = false, onSelect, + children, shortcut, icon, current, disabled = false, disabledReason, danger = false, separatorBefore = false, onSelect, }: MenuItemButtonProps) { + const reasonId = useId() + // Native disabled buttons do not deliver the hover/focus events Tooltip needs, + // so an explained row is only marked unavailable. The Tooltip wraps every row, + // so a reason that comes or goes never remounts the focused row. + const explained = disabled && disabledReason !== undefined return (
    {separatorBefore &&
    } - + + + + {explained && }
    ) } @@ -160,9 +178,9 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 } * @param props.align - list alignment against the anchor (default 'start'). * @param props.side - open below (`bottom`, default) or above (`top`) the anchor. * @param props.portal - render the list into document.body, fixed-positioned - * from the anchor rect (follows movement and resizing while open). Use when an - * ancestor's overflow clipping would crop the in-place list; default false - * keeps the pure-CSS in-place behavior. + * synchronously (follows movement, resizing, and browser zoom while open) + * and clamped inside the visual viewport. Use when an ancestor's overflow clipping would crop the + * in-place list; default false keeps the pure-CSS in-place behavior. * @param props.closeOnPointerLeave - close the list once the pointer has left * both trigger and list for the pointer grace (default false keeps it open * until outside click/Escape/selection). The grace makes the 4px trigger->list @@ -173,8 +191,8 @@ const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 } * directly (e.g. from a host-owned trigger button) instead of measuring the * Menu's own wrapper span. Required when the wrapper isn't itself laid out at * the trigger (render-prop anchors, effect-positioned proxies — measuring the - * wrapper there races the host's layout effects). Called on open, each animation - * frame, and scroll/resize; return null to skip placement for that frame. + * wrapper there races the host's layout effects). Called while tracking the + * anchor and on scroll/resize; return null to defer placement. * @param props.minWidthFromAnchor - in portal mode, keep the menu at least as wide as its anchor, bounded by viewport margins. * @param props.footer - rows pinned below the scrolling items area, separated * by a hairline; contextual menus reuse an explicit leading separator. These rows stay visible while the items above scroll. @@ -280,81 +298,34 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI const openRef = useRef(open) openRef.current = open const [openSubmenuId, setOpenSubmenuId] = useState(null) - const [fixedPos, setFixedPos] = useState(null) const close = useRef(onClose) close.current = onClose + // Keep the dismissal fade at the last interactive anchor position. + const lastAnchorRect = useRef(null) + const readAnchor = useCallback(() => { + const anchorElement = returnFocus?.() ?? rootRef.current + if (anchorElement?.closest('[inert], [hidden]') != null) { + if (exitingRef.current === undefined) close.current() + return lastAnchorRect.current + } + lastAnchorRect.current = getAnchorRect === undefined ? rootRef.current?.getBoundingClientRect() ?? null : getAnchorRect() + return lastAnchorRect.current + }, [getAnchorRect, returnFocus]) + const fixedPos = useAnchoredPosition({ + open: open && portal, + anchorRef: rootRef, + panelRef: listRef, + side, + align, + gap: 4, + margin: 12, + frameClearance: !contextual, + minWidthFromAnchor, + getAnchorRect: readAnchor, + }) + const positioned = !portal || fixedPos !== null const { arm: armClose, cancel: cancelClose } = usePointerGrace(onClose) - // Portal mode: fixed-position the list from the anchor rect before paint; - // track the anchor while open (capture-phase scroll catches nested panes). - // getAnchorRect trumps measuring the wrapper span: a child layout effect - // runs before the parent's, so a wrapper the host positions in its own - // effect measures stale here — the host callback owns the truth instead. - useLayoutEffect(() => { - if (!open || !portal) { setFixedPos(null); return } - const place = () => { - const anchorElement = returnFocus?.() ?? rootRef.current - if (anchorElement?.closest('[inert], [hidden]') != null) { - if (exitingRef.current === undefined) close.current() - return - } - let r: DOMRect | null - if (getAnchorRect !== undefined) { - r = getAnchorRect() - } else { - /* v8 ignore next 2 -- the ref is attached before the layout effect runs and the listeners die with it. */ - r = rootRef.current?.getBoundingClientRect() ?? null - } - if (r === null) return - const MARGIN = 12 - const GAP = 4 - const vw = window.innerWidth - const vh = window.innerHeight - const listEl = listRef.current - if (listEl !== null) { - const minimum = minWidthFromAnchor ? `${Math.min(r.width, Math.max(0, vw - MARGIN * 2))}px` : '' - if (listEl.style.minWidth !== minimum) listEl.style.minWidth = minimum - } - const lw = listEl?.offsetWidth ?? 0 - const lh = listEl?.offsetHeight ?? 0 - - let x: number - let y: number - if (side === 'right') { - x = r.right + GAP - y = r.top - } else if (align === 'start') { - x = r.left - y = side === 'bottom' ? r.bottom + GAP : r.top - lh - GAP - } else { - x = r.right - lw - y = side === 'bottom' ? r.bottom + GAP : r.top - lh - GAP - } - - if (lw > 0) x = Math.min(Math.max(x, MARGIN), vw - lw - MARGIN) - if (lh > 0) y = Math.min(Math.max(y, contextual ? MARGIN : overlayTopMargin(MARGIN, r, GAP)), vh - lh - MARGIN) - - setFixedPos(current => current?.left === x && current.top === y ? current : { left: x, top: y }) - } - // First run measures the hidden pre-render (same commit as `open`), so - // end/top alignment and clamping use real dimensions before anything - // paints — no visible jump from a zero-size first guess. - place() - // Dragging or transforming an ancestor moves the anchor without a scroll or resize event. - const track = () => { - place() - frame = requestAnimationFrame(track) - } - let frame = requestAnimationFrame(track) - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) - return () => { - cancelAnimationFrame(frame) - window.removeEventListener('scroll', place, true) - window.removeEventListener('resize', place) - } - }, [open, portal, align, side, getAnchorRect, minWidthFromAnchor, contextual, returnFocus]) - // Opening remembers where the keyboard was, so closing can hand it back to // that control — an anchor wrapping several (a split button) cannot be asked // for it by position. Declared before the autoFocus effect so the capture @@ -367,12 +338,12 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI }, [open]) useEffect(() => { - if (!open || exiting !== undefined || (portal && fixedPos === null) || !autoFocus + if (!open || exiting !== undefined || !autoFocus || !positioned || listRef.current?.contains(document.activeElement)) return const first = listRef.current?.querySelector('button:not(:disabled)') walkIndex.current = first === undefined || first === null ? null : 0 if (first != null) focusWithoutRing(first) - }, [open, autoFocus, items.length, footer?.length, fixedPos, portal, exiting]) + }, [open, autoFocus, items.length, footer?.length, positioned, exiting]) useEffect(() => { if (!open || exiting !== undefined) { @@ -425,6 +396,11 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI if (insideList) { if (focused instanceof Element && focused.getAttribute('role') === 'menuitem') { e.preventDefault() + if (focused.getAttribute('aria-disabled') === 'true') { + onClose() + refocusAnchor(true) + return + } selectingWithTab.current = true try { (focused as HTMLElement).click() } finally { selectingWithTab.current = false } @@ -578,10 +554,7 @@ export function Menu({ open, anchor, items = [], children, selectedId, selectedI setOpenSubmenuId(null) } - // Portal lists render hidden until placed: the placement effect measures - // this pre-render in the same commit, so the first painted frame is - // already at the final position (with getAnchorRect returning null the - // list simply stays hidden). + // Portal lists stay hidden until their first synchronous measurement. const list = open && ( void title: string + tone?: 'warning' description?: string children?: ReactNode footer?: ReactNode @@ -31,6 +32,7 @@ type ModalProps = ModalBaseProps & ( * @param props.onClose - application close command, Escape, or mask click; while a menu is open inside the * dialog, Escape belongs to that menu first. * @param props.title - dialog heading (aria-label in every mode). + * @param props.tone - warning adds an amber title icon and compact title-to-body spacing; ignored for headless dialogs. * @param props.closeLabel - localized accessible close-button label. * @param props.description - optional supporting sentence under the title. * @param props.children - dialog body; mark its initial-focus control with @@ -47,7 +49,7 @@ type ModalProps = ModalBaseProps & ( */ export function Modal({ open, onClose, title, closeLabel, description, children, footer, className, contentClassName, - onKeyDownCapture, headless = false, backdropBlur = true, shortcutModal, + onKeyDownCapture, headless = false, backdropBlur = true, shortcutModal, tone, }: ModalProps) { const dialog = useRef(null) useModalLayer(dialog, open, onClose) @@ -61,7 +63,7 @@ export function Modal({ ref={dialog} tabIndex={-1} data-shortcut-modal={shortcutModal} - className={clsx(css.dialog, className)} + className={clsx(css.dialog, !headless && tone === 'warning' && css.warning, className)} role="dialog" aria-modal="true" aria-label={title} @@ -72,7 +74,10 @@ export function Modal({ <>
    -

    {title}

    +

    + {tone === 'warning' &&

    diff --git a/packages/client/ui-primitives/src/RiskConfirmation.module.css b/packages/client/ui-primitives/src/RiskConfirmation.module.css index 3c29131429..6a7db49ffa 100644 --- a/packages/client/ui-primitives/src/RiskConfirmation.module.css +++ b/packages/client/ui-primitives/src/RiskConfirmation.module.css @@ -16,52 +16,26 @@ } } -.warning { - display: flex; - align-items: flex-start; - gap: 10px; +.description { + margin: 0; color: var(--dsw-alias-label-secondary); font-size: 14px; line-height: 22px; } -.warning p { - margin: 0; -} - -.warningIcon { - flex: none; - margin-top: 2px; - color: var(--dsw-alias-state-error-primary); -} - -.acknowledgement { - display: flex; +.confirmation .acknowledgement { align-items: flex-start; - gap: 10px; - margin-top: 20px; - color: var(--dsw-alias-label-primary); + margin-top: 16px; + color: var(--dsw-alias-label-secondary); font-size: 14px; - line-height: 22px; - cursor: pointer; + font-weight: 400; + line-height: 20px; } -.acknowledgement input { - flex: none; - width: 16px; - height: 16px; - margin: 3px 0 0; - accent-color: var(--dsw-alias-button-primary-fill); - cursor: pointer; -} - -.acknowledgement input:focus-visible { - outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); - outline-offset: 2px; -} - -.acknowledgement input:disabled { - cursor: default; +.confirmation .acknowledgement input { + width: 14px; + height: 14px; + margin-top: 3px; } .modalAction { diff --git a/packages/client/ui-primitives/src/RiskConfirmation.tsx b/packages/client/ui-primitives/src/RiskConfirmation.tsx index 7109d096b2..1ad24e8298 100644 --- a/packages/client/ui-primitives/src/RiskConfirmation.tsx +++ b/packages/client/ui-primitives/src/RiskConfirmation.tsx @@ -3,7 +3,7 @@ * must gate a sensitive action behind an explicit checkbox. */ import { Button } from './Button.tsx' -import { IconWarningOutlineRegular } from './icons/index.tsx' +import { Checkbox } from './Checkbox.tsx' import { Modal } from './Modal.tsx' import css from './RiskConfirmation.module.css' @@ -45,6 +45,7 @@ export function RiskConfirmation({ open={open} onClose={onCancel} title={title} + tone="warning" closeLabel={closeLabel} className={css.confirmation ?? ''} contentClassName={css.confirmationContent ?? ''} @@ -64,20 +65,15 @@ export function RiskConfirmation({ )} > -
    - -

    {description}

    -
    - +

    {description}

    + ) } diff --git a/packages/client/ui-primitives/src/icons/artwork.ts b/packages/client/ui-primitives/src/icons/artwork.ts index 073f9988d3..28a3819995 100644 --- a/packages/client/ui-primitives/src/icons/artwork.ts +++ b/packages/client/ui-primitives/src/icons/artwork.ts @@ -20,6 +20,7 @@ interface IconArtwork { /** Default artwork keyed by glyph name; symbol ids derive from these keys. */ export const ICON_ARTWORK = { + 'layers-outline': { size: 16, svg: strokeWidth => `` }, 'save-outline': { size: 16, svg: strokeWidth => `` }, 'new-chat-outline': { size: 16, svg: strokeWidth => `` }, 'search-outline': { size: 16, svg: strokeWidth => `` }, @@ -59,7 +60,8 @@ export const ICON_ARTWORK = { 'check-circle-fill': { size: 16, svg: strokeWidth => `` }, 'warning-triangle-outline': { size: 16, svg: strokeWidth => `` }, 'user-outline': { size: 16, svg: strokeWidth => `` }, - 'users-outline': { size: 16, svg: strokeWidth => `` }, + // Users has inset contours in the 16px box; only coordinates, never stroke widths, carry the inset. + 'users-outline': { size: 16, svg: strokeWidth => `` }, 'paper-plane-outline': { size: 14, svg: strokeWidth => `` }, 'stop-fill': { size: 16, svg: strokeWidth => `` }, 'paperclip-outline': { size: 16, svg: strokeWidth => `` }, diff --git a/packages/client/ui-primitives/src/icons/index.tsx b/packages/client/ui-primitives/src/icons/index.tsx index a8f86d71ab..b6f03f1299 100644 --- a/packages/client/ui-primitives/src/icons/index.tsx +++ b/packages/client/ui-primitives/src/icons/index.tsx @@ -24,6 +24,12 @@ function productIcon(glyph: IconGlyph, weight: IconWeight): (props: IconProps) = ) } +/** Regular one-pixel IconLayersOutline artwork. */ +export const IconLayersOutlineRegular = productIcon('layers-outline', 'regular') + +/** Medium IconLayersOutline artwork with a 1.3px stroke. */ +export const IconLayersOutlineMedium = productIcon('layers-outline', 'medium') + /** Regular one-pixel IconNewChatOutline artwork. */ export const IconNewChatOutlineRegular = productIcon('new-chat-outline', 'regular') diff --git a/packages/client/ui-primitives/src/markdown/mathCompatibility.ts b/packages/client/ui-primitives/src/markdown/mathCompatibility.ts index 15932c5e76..3edd9d1e63 100644 --- a/packages/client/ui-primitives/src/markdown/mathCompatibility.ts +++ b/packages/client/ui-primitives/src/markdown/mathCompatibility.ts @@ -1,26 +1,13 @@ -/** - * Extend upstream dollar-only math syntax with TeX delimiters while reusing its - * token vocabulary. The dollar construct is dispatched before upstream's - * `mathFlow`, so the shapes it accepts keep the opening line's text as math - * instead of fence meta, which the renderer does not read. A `$$` candidate it - * declines — a `$$` sequence the line does not end after, or a block left open - * — is left to that upstream flow. - */ +/** Extend upstream dollar-only math syntax with TeX delimiters while reusing its token vocabulary. */ import { factorySpace } from 'micromark-factory-space' import type {} from 'micromark-extension-math' -import { markdownLineEnding, markdownSpace } from 'micromark-util-character' +import { markdownLineEnding } from 'micromark-util-character' import { codes, constants, types } from 'micromark-util-symbol' import type { Construct, Extension, Previous, State, Tokenizer } from 'micromark-util-types' // oxlint-disable typescript/no-this-alias -- micromark binds tokenizer context only on the outer callback. -/** Prefixes whose following character is a `\verb` delimiter, not a fence. */ -const VERB_DELIMITER_PREFIXES = ['\\verb', '\\verb*'] as const - -/** Longest prefix above, in code units. */ -const VERB_DELIMITER_TAIL = 6 - const previousBackslash: Previous = function (code) { if (code !== codes.backslash) return true const tail = this.events.at(-1) @@ -133,16 +120,10 @@ const tokenizeBackslashMathText: Tokenizer = function (effects, ok, nok) { } } -function createMathFlow(marker: number, openMarker: number, closeMarker: number): Construct { +function createMathFlow(marker: number, openMarker: number, closeMarker: number, multiline: boolean): Construct { const tokenize: Tokenizer = function (effects, ok, nok) { const self = this let oddBackslashRun = false - let inComment = false - let commentHasContent = false - let crossedLineEnding = false - let sawClosingFenceSequence = false - let consumedTail = '' - let failedClose = false const tail = self.events.at(-1) const initialSize = tail?.[1].type === types.linePrefix ? tail[2].sliceSerialize(tail[1], true).length @@ -174,13 +155,7 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) function content(code: number | null): State | undefined { if (code === codes.eof) return nok(code) - if (code === marker && marker === codes.dollarSign && !inComment && verbDelimiterAhead()) { - // The `$` here delimits a `\verb…` region rather than closing the block, - // so it is content, and a `$` right after it closes an empty region and - // is content too. A comment holds no commands. - return verbatimDelimiter(code) - } - if (code === marker && closingFenceAllowed()) { + if (code === marker && (marker !== codes.dollarSign || !oddBackslashRun)) { return effects.attempt( { partial: true, tokenize: tokenizeClosingFence }, closed, @@ -188,83 +163,17 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) )(code) } if (markdownLineEnding(code)) { - // A close that failed earlier on this candidate ends it at the line - // ending, which is what the grammar this flow replaced did: a failed - // `$$x$$ trailing` never reaches the next line. - if (marker === codes.dollarSign && failedClose) return nok(code) - // A trailing backslash escapes the line ending, not the next line's - // first character, so the escape run ends here, and a TeX comment ends - // with the line. The comment exception covers only a closing fence on a - // later line, which is where the multi-line block can hide one; the - // same-line form keeps closing as it did before this flow spanned lines. - oddBackslashRun = false - inComment = false - commentHasContent = false - consumedTail = '' - if (marker === codes.dollarSign) crossedLineEnding = true - // A paragraph-interruption check on the dollar flow must not consume the - // line ending: that keeps the paragraph open across the line boundary, - // and the document layer then counts the next line lazy for every - // construct tried afterwards. Declining leaves the interruption decision - // to the upstream flow, whose own check short-circuits without consuming - // and claims only the fences it accepts. The backslash construct has no - // upstream counterpart and keeps consuming here. - if (self.interrupt && marker === codes.dollarSign) return nok(code) - return effects.attempt(nonLazyContinuation, afterContinuation, nok)(code) + return multiline + ? effects.attempt(nonLazyContinuation, afterContinuation, nok)(code) + : nok(code) } return valueStart(code) } - /** - * Whether the marker under the scanner may close the block. The dollar flow - * keeps an escaped `$` and a `%` comment that holds text from closing. - */ - function closingFenceAllowed(): boolean { - if (marker !== codes.dollarSign) return true - return !oddBackslashRun && !(inComment && commentHasContent && crossedLineEnding) - } - - /** Whether the marker under the scanner is a `\verb` region's delimiter. */ - function verbDelimiterAhead(): boolean { - return VERB_DELIMITER_PREFIXES.some(prefix => consumedTail.endsWith(prefix)) - } - - function verbatimDelimiter(code: number | null): State | undefined { - effects.enter('mathFlowValue') - oddBackslashRun = false - rememberConsumed(code) - effects.consume(code) - return verbatimDelimiterClose - } - - function verbatimDelimiterClose(code: number | null): State | undefined { - if (code !== marker) return value(code) - rememberConsumed(code) - effects.consume(code) - return value - } - - /** Record one consumed code unit so a fence can be told from a delimiter. */ - function rememberConsumed(code: number | null): void { - /* v8 ignore next 2 -- every call site passes a code unit, never EOF. */ - if (code === null) return - consumedTail = `${consumedTail}${String.fromCharCode(code)}`.slice(-VERB_DELIMITER_TAIL) - } - function afterClosingFenceAttempt(code: number | null): State | undefined { - if (marker === codes.backslash) { - return effects.check({ partial: true, tokenize: tokenizeOpeningFence }, nok, markerValueStart)(code) - } - // A full `$$` that the line does not end after closes nothing there. On - // the opening line the scan continues, so `$$x$$ trailing` declines at - // that line's ending while a later `$$` on the same line still closes; on - // any later line it ends the candidate outright, so a following block is - // not swallowed. A solitary `$` is content, not a failed fence. - if (sawClosingFenceSequence) { - if (crossedLineEnding) return nok(code) - failedClose = true - } - return markerValueStart(code) + return marker === codes.backslash + ? effects.check({ partial: true, tokenize: tokenizeOpeningFence }, nok, markerValueStart)(code) + : markerValueStart(code) } function afterContinuation(code: number | null): State | undefined { @@ -279,17 +188,7 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) function valueStart(code: number | null): State | undefined { effects.enter('mathFlowValue') - // An unescaped `%` opens a TeX comment wherever it is the first character - // of a value run, such as a line that starts inside the block. The - // backslash construct reads neither this state nor the escape run. oddBackslashRun = code === codes.backslash - if (code === codes.percentSign && marker === codes.dollarSign && !inComment) { - inComment = true - commentHasContent = false - } else if (inComment && !markdownSpace(code)) { - commentHasContent = true - } - rememberConsumed(code) effects.consume(code) return value } @@ -297,15 +196,12 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) function markerValueStart(code: number | null): State | undefined { effects.enter('mathFlowValue') oddBackslashRun = false - if (inComment) commentHasContent = true - rememberConsumed(code) effects.consume(code) return valueAfterMarker } function valueAfterMarker(code: number | null): State | undefined { if (code === marker) { - rememberConsumed(code) effects.consume(code) return value } @@ -317,25 +213,7 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) effects.exit('mathFlowValue') return content(code) } - const escaped = oddBackslashRun - const doubleBackslash = code === codes.backslash && escaped - oddBackslashRun = code === codes.backslash ? !escaped : false - // An unescaped `%` starts a TeX comment that runs to the line ending, so - // a `$$` inside it closes nothing. A `%` the fence follows immediately - // holds no comment text, which is how writers use it mid-formula - // (`95%$$`, and `95 %$$` alike); only a comment holding a non-whitespace - // character suppresses the close, and a `%` inside an open comment is - // comment text like any other character. - if (!escaped && code === codes.percentSign && marker === codes.dollarSign && !inComment) { - inComment = true - commentHasContent = false - } else if (inComment && !markdownSpace(code)) { - commentHasContent = true - } - // `\\verb` is a line break followed by letters, not the command, so the - // pair's second backslash never reaches the tail the command match reads. - if (doubleBackslash) consumedTail = '' - else rememberConsumed(code) + oddBackslashRun = code === codes.backslash ? !oddBackslashRun : false effects.consume(code) return value } @@ -350,7 +228,6 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) closeOk: State, closeNok: State, ): State { - sawClosingFenceSequence = false return factorySpace(closeEffects, sequenceStart, types.linePrefix, constants.tabSize) function sequenceStart(code: number | null): State | undefined { @@ -365,7 +242,6 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) if (code !== closeMarker) return closeNok(code) closeEffects.consume(code) closeEffects.exit('mathFlowFenceSequence') - sawClosingFenceSequence = true return factorySpace(closeEffects, after, types.whitespace) } @@ -402,7 +278,7 @@ function createMathFlow(marker: number, openMarker: number, closeMarker: number) return { concrete: true, - name: marker === codes.dollarSign ? 'dollarMathFlow' : 'backslashMathFlow', + name: marker === codes.dollarSign ? 'sameLineDollarMathFlow' : 'backslashMathFlow', tokenize, } } @@ -443,29 +319,29 @@ const backslashMathFlow = createMathFlow( codes.backslash, codes.leftSquareBracket, codes.rightSquareBracket, + true, ) -const dollarMathFlow = createMathFlow( +const sameLineDollarMathFlow = createMathFlow( codes.dollarSign, codes.dollarSign, codes.dollarSign, + false, ) const backslashMath: Extension = { flow: { [codes.backslash]: backslashMathFlow, - [codes.dollarSign]: dollarMathFlow, + [codes.dollarSign]: sameLineDollarMathFlow, }, text: { [codes.backslash]: backslashMathText }, } /** - * TeX backslash delimiters and display-dollar blocks as a micromark syntax - * extension reusing `micromark-extension-math`'s token vocabulary; the caller - * must also register `math()` on the same parse so the emitted tokens compile - * to standard math nodes. Both `$$$$` on one line and a `$$` block - * closed by a trailing `$$` parse as one math node, and a closing `$$` may sit - * at the end of a content line. + * TeX backslash delimiters and same-line display-dollar blocks as a micromark + * syntax extension reusing `micromark-extension-math`'s token vocabulary; the + * caller must also register `math()` on the same parse so the emitted tokens + * compile to standard math nodes. * @returns The micromark syntax extension. */ export function mathCompatibility(): Extension { diff --git a/packages/client/ui-primitives/src/markdown/parse.ts b/packages/client/ui-primitives/src/markdown/parse.ts index 11cc358c33..463e1003ba 100644 --- a/packages/client/ui-primitives/src/markdown/parse.ts +++ b/packages/client/ui-primitives/src/markdown/parse.ts @@ -43,10 +43,7 @@ export function parseGfm(text: string): Root { */ export function parseGfmWithMath(text: string): Root { return recoverLocalImages(fromMarkdown(text, { - // `mathCompatibility()` MUST stay last: micromark dispatches the extension - // registered last first, so its dollar flow takes precedence over `math()` - // and keeps the opening line's text as math instead of upstream's fence meta. - extensions: [gfm(gfmOptions), cjkFriendlyStrong(), math(), mathCompatibility()], + extensions: [gfm(gfmOptions), cjkFriendlyStrong(), mathCompatibility(), math()], mdastExtensions: [gfmFromMarkdown(), mathFromMarkdown(), windowsPathDestinations()], }), text) } diff --git a/packages/client/ui-primitives/src/useAnchoredPosition.ts b/packages/client/ui-primitives/src/useAnchoredPosition.ts index 11256ae00a..61a891e5a9 100644 --- a/packages/client/ui-primitives/src/useAnchoredPosition.ts +++ b/packages/client/ui-primitives/src/useAnchoredPosition.ts @@ -1,86 +1,120 @@ -/** - * Keep a fixed-position floating element anchored to a trigger. - * - * A portaled panel is positioned from its anchor's viewport rect, which stops - * being true the moment anything scrolls or the window resizes. This owns that - * one concern: measure the anchor, offset the panel below or above it, clamp - * the result inside the viewport, and re-run on scroll (capture phase, so - * scrollers nested inside the page are caught too), on resize, and on the - * panel's own size changes while the element is open. - * @module @deepseek-ai/dsh-client-ui-primitives/useAnchoredPosition - */ - +/** Synchronous placement for body-portaled panels with a viewport fixed-position containing block. */ import { useLayoutEffect, useState, type CSSProperties, type RefObject } from 'react' import { overlayTopMargin } from './overlay-top-margin.ts' /** Inputs for {@link useAnchoredPosition}. */ export interface AnchoredPositionOptions { - /** Whether the floating element is mounted and should track its anchor. */ + /** Whether the panel is mounted and should track its anchor. */ open: boolean - /** The element the panel is placed from. */ + /** Element whose viewport rect anchors the panel. */ anchorRef: RefObject - /** The floating element, measured so the clamp uses real dimensions. */ + /** Body-portaled, fixed-position panel; its ancestors must not establish a containing block. */ panelRef: RefObject - /** Which anchor edge the panel hangs from: below it (`bottom`, the default) or above it (`top`). */ - side?: 'top' | 'bottom' - /** Which anchor edge the panel lines up with: its left edge (`start`, the default) or its right edge (`end`). */ + /** Preferred anchor edge; right-side panels align their top edges. */ + side?: 'top' | 'bottom' | 'right' + /** Horizontal alignment for panels above or below the anchor. */ align?: 'start' | 'end' - /** Distance kept between the anchor edge named by `side` and the panel. */ + /** Distance from the preferred anchor edge, in CSS pixels. */ gap: number - /** Distance kept between the panel and each viewport edge; the frame's overlay inset widens the top margin. */ + /** Minimum viewport inset; desktop frame clearance can increase the top inset. */ margin: number + /** Reserve desktop frame clearance in addition to the margin; false keeps only the viewport margin. Defaults to true. */ + frameClearance?: boolean + /** Host-supplied client rect; null hides the panel until the anchor is available. */ + getAnchorRect?: () => DOMRect | null + /** Re-measure a committed content change before paint. */ + layoutKey?: string | number + /** Minimum panel width follows the anchor, bounded by the visible viewport. */ + minWidthFromAnchor?: boolean } /** - * Track an anchor and return the panel's fixed coordinates. - * @param options - the open state, the two refs, the placement side and alignment, and the gap/margin distances. - * @returns `left`/`top` for the panel, or `null` before the first measurement. + * Keep a fixed panel aligned and constrained to the visible viewport. + * Panel CSS consumes `--dsh-anchored-max-width` and `--dsh-anchored-max-height` for size limits. + * The hook owns those inline variables and optional min-width while open, restoring them on cleanup. + * @param options - Open state, element refs, placement, and optional host rect or content change key. + * @returns Fixed left/top coordinates, or null while closed or awaiting an anchor; the first measurement completes before paint. */ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProperties | null { - const { open, anchorRef, panelRef, side = 'bottom', align = 'start', gap, margin } = options + const { open, anchorRef, panelRef, side = 'bottom', align = 'start', gap, margin, + getAnchorRect, layoutKey, minWidthFromAnchor = false, frameClearance = true } = options const [position, setPosition] = useState(null) useLayoutEffect(() => { if (!open) { setPosition(null) return } - const place = () => { - /* v8 ignore start -- geometry read from real layout: jsdom reports zero - offset sizes, so the positive-size clamp arms are exercised by browser - scenarios rather than unit tests. */ - const rect = anchorRef.current?.getBoundingClientRect() - if (rect === undefined) return - const panel = panelRef.current - const width = panel?.offsetWidth ?? 0 - const height = panel?.offsetHeight ?? 0 - let left = align === 'end' ? rect.right - width : rect.left - let top = side === 'top' ? rect.top - gap - height : rect.bottom + gap - if (width > 0) left = Math.min(Math.max(left, margin), window.innerWidth - width - margin) - if (height > 0) top = Math.min(Math.max(top, overlayTopMargin(margin, rect, gap)), window.innerHeight - height - margin) - /* v8 ignore stop */ - setPosition({ left, top }) - } - // The first run measures the panel in the same commit that opened it, so - // the clamp uses real dimensions before anything paints. - place() - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) - // The panel's own height changes without either event — a status line - // appearing inside it, or a `resize: vertical` textarea dragged taller — - // and a stale clamp would let a panel near the bottom edge cross the - // margin it is supposed to respect. The guard keeps the hook usable where - // `ResizeObserver` is absent, which is how jsdom runs. + const anchor = anchorRef.current const panel = panelRef.current - let observer: ResizeObserver | null = null - if (typeof ResizeObserver !== 'undefined' && panel !== null) { - observer = new ResizeObserver(place) - observer.observe(panel) + if (anchor === null || panel === null) return + const win = anchor.ownerDocument.defaultView + if (win === null) return + const viewport = win.visualViewport + // WebKit client rects use the visual origin; viewport-fixed CSS uses the layout origin. + const visualOrigin = typeof win.CSS !== 'undefined' && win.CSS.supports('-webkit-backdrop-filter', 'none') + const properties = ['--dsh-anchored-max-width', '--dsh-anchored-max-height', ...minWidthFromAnchor ? ['min-width'] : []] + const previous = properties.map(name => [name, panel.style.getPropertyValue(name), panel.style.getPropertyPriority(name)] as const) + let active = true + let lastRect: Pick | null = null + const readRect = () => getAnchorRect === undefined ? anchor.getBoundingClientRect() : getAnchorRect() + const place = (rect: DOMRect | null): void => { + lastRect = rect === null ? null : { x: rect.x, y: rect.y, width: rect.width, height: rect.height } + let next: CSSProperties | null = null + if (rect !== null) { + const x = viewport?.offsetLeft ?? 0 + const y = viewport?.offsetTop ?? 0 + const width = viewport?.width ?? (anchor.ownerDocument.documentElement.clientWidth || win.innerWidth) + const height = viewport?.height ?? (anchor.ownerDocument.documentElement.clientHeight || win.innerHeight) + const topMargin = frameClearance ? overlayTopMargin(margin, rect, gap) : margin + const maxWidth = Math.max(0, width - margin * 2) + panel.style.setProperty('--dsh-anchored-max-width', `${maxWidth}px`) + panel.style.setProperty('--dsh-anchored-max-height', `${Math.max(0, height - topMargin - margin)}px`) + if (minWidthFromAnchor) panel.style.minWidth = `${Math.min(rect.width, maxWidth)}px` + const panelWidth = panel.offsetWidth + const panelHeight = panel.offsetHeight + const offsetX = visualOrigin ? x : 0 + const offsetY = visualOrigin ? y : 0 + const left = offsetX + (side === 'right' ? rect.right + gap : align === 'end' ? rect.right - panelWidth : rect.left) + const top = offsetY + (side === 'right' ? rect.top : side === 'top' ? rect.top - gap - panelHeight : rect.bottom + gap) + next = { + left: Math.max(x + margin, Math.min(left, x + width - margin - panelWidth)), + top: Math.max(y + topMargin, Math.min(top, y + height - margin - panelHeight)), + } + } + setPosition(current => current?.left === next?.left && current?.top === next?.top ? current : next) } + const update = (): void => { + if (!active) return + place(readRect()) + } + update() + win.addEventListener('scroll', update, true) + win.addEventListener('resize', update) + viewport?.addEventListener('scroll', update) + viewport?.addEventListener('resize', update) + const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update) + observer?.observe(anchor) + observer?.observe(panel) + // Transforms and surrounding layout can move an anchor without resizing either element. + let frame = 0 + const track = (): void => { + if (!active) return + const rect = readRect() + if (rect?.x !== lastRect?.x || rect?.y !== lastRect?.y + || rect?.width !== lastRect?.width || rect?.height !== lastRect?.height) place(rect) + frame = win.requestAnimationFrame(track) + } + frame = win.requestAnimationFrame(track) return () => { + active = false + win.cancelAnimationFrame(frame) observer?.disconnect() - window.removeEventListener('scroll', place, true) - window.removeEventListener('resize', place) + win.removeEventListener('scroll', update, true) + win.removeEventListener('resize', update) + viewport?.removeEventListener('scroll', update) + viewport?.removeEventListener('resize', update) + for (const [name, value, priority] of previous) panel.style.setProperty(name, value, priority) } - }, [open, anchorRef, panelRef, side, align, gap, margin]) + }, [open, anchorRef, panelRef, side, align, gap, margin, getAnchorRect, layoutKey, minWidthFromAnchor, frameClearance]) return position } diff --git a/packages/client/ui-primitives/tests/atoms.client.spec.tsx b/packages/client/ui-primitives/tests/atoms.client.spec.tsx index 8b198e4365..1bd9692b64 100644 --- a/packages/client/ui-primitives/tests/atoms.client.spec.tsx +++ b/packages/client/ui-primitives/tests/atoms.client.spec.tsx @@ -173,6 +173,10 @@ describe('MenuItemButton', () => { }) describe('Menu', () => { + beforeEach(() => { + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) + }) + afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) const items = [ { id: 'a', label: 'Alpha' }, { id: 'b', label: 'Beta', disabled: true }, @@ -226,6 +230,68 @@ describe('Menu', () => { expect(document.activeElement).toBe(trigger) }) + it('explains an unavailable component row on hover and focus without activating it', () => { + vi.useFakeTimers() + vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: true }))) + try { + const onSelect = vi.fn() + const reason = 'Available at 15:51:37.' + const menu = (explanation: string | undefined) => ( + trigger} onClose={() => {}}> + Run now + + ) + const { rerender } = render(menu(reason)) + const row = screen.getByRole('menuitem', { name: 'Run now', description: reason }) + expect(row.hasAttribute('disabled')).toBe(false) + expect(row.getAttribute('aria-disabled')).toBe('true') + fireEvent.click(row) + expect(onSelect).not.toHaveBeenCalled() + fireEvent.pointerEnter(row, { pointerType: 'mouse' }) + act(() => { vi.advanceTimersByTime(499) }) + expect(screen.queryByRole('tooltip')).toBeNull() + act(() => { vi.advanceTimersByTime(1) }) + expect(screen.getByRole('tooltip').textContent).toBe(reason) + fireEvent.pointerLeave(row, { pointerType: 'mouse' }) + expect(screen.queryByRole('tooltip')).toBeNull() + // The arrow walk reaches the row, and keyboard focus shows the reason at once. + const trigger = screen.getByRole('button', { name: 'trigger' }) + fireEvent.keyDown(document.body, { key: 'Tab' }) + trigger.focus() + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + expect(document.activeElement).toBe(row) + expect(screen.getByRole('tooltip').textContent).toBe(reason) + // A reason that goes away keeps the focused row mounted and makes it an ordinary row. + rerender(menu(undefined)) + expect(document.activeElement).toBe(row) + expect(row.hasAttribute('aria-disabled')).toBe(false) + expect(row.hasAttribute('aria-describedby')).toBe(false) + expect(screen.queryByRole('tooltip')).toBeNull() + fireEvent.click(row) + expect(onSelect).toHaveBeenCalledOnce() + } finally { + vi.useRealTimers() + vi.unstubAllGlobals() + } + }) + + it('closes an explained unavailable row on Tab and returns focus to the trigger', () => { + const onClose = vi.fn() + const onSelect = vi.fn() + render(trigger} onClose={onClose}> + Run now + ) + const trigger = screen.getByRole('button', { name: 'trigger' }) + trigger.focus() + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + const row = screen.getByRole('menuitem', { name: 'Run now' }) + expect(document.activeElement).toBe(row) + fireEvent.keyDown(row, { key: 'Tab' }) + expect(onClose).toHaveBeenCalledOnce() + expect(onSelect).not.toHaveBeenCalled() + expect(document.activeElement).toBe(trigger) + }) + it('disabled item does not select; Escape and outside pointerdown close', () => { const onSelect = vi.fn() const onClose = vi.fn() @@ -610,6 +676,59 @@ describe('Menu', () => { expect(screen.queryByRole('menu')).toBeNull() }) + it('shows and focuses a portal menu when its host anchor becomes available', () => { + vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] }) + let rect: DOMRect | null = null + try { + render( rect} anchor={null} + items={[...items, { id: 'c', label: 'Gamma' }]} onClose={() => {}} />) + expect(screen.queryByRole('menu')).toBeNull() + rect = new DOMRect(40, 100, 32, 28) + act(() => { vi.advanceTimersToNextFrame() }) + expect(screen.getByRole('menu').style.left).toBe('40px') + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Alpha' })) + screen.getByRole('menuitem', { name: 'Gamma' }).focus() + rect = new DOMRect(80, 100, 32, 28) + act(() => { vi.advanceTimersToNextFrame() }) + expect(screen.getByRole('menu').style.left).toBe('80px') + expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'Gamma' })) + } finally { + cleanup() + vi.useRealTimers() + } + }) + + it('keeps a portal menu aligned through WebKit zoom and visual-viewport panning', () => { + const viewport = Object.assign(new EventTarget(), { width: 500, height: 400, offsetLeft: 40, offsetTop: 60 }) + vi.stubGlobal('visualViewport', viewport) + vi.stubGlobal('CSS', { supports: (property: string) => property === '-webkit-backdrop-filter' }) + vi.spyOn(HTMLDivElement.prototype, 'offsetWidth', 'get').mockReturnValue(120) + vi.spyOn(HTMLDivElement.prototype, 'offsetHeight', 'get').mockReturnValue(80) + const remove = vi.spyOn(viewport, 'removeEventListener') + const ui = render( new DOMRect(100, 200, 200, 20)} + anchor={null} items={items} onClose={() => {}} />) + const menu = screen.getByRole('menu') + expect(menu.style.left).toBe('220px') + expect(menu.style.top).toBe('284px') + act(() => { viewport.dispatchEvent(new Event('resize')) }) + expect(menu.style.left).toBe('220px') + expect(menu.style.top).toBe('284px') + act(() => { + viewport.offsetLeft = 100 + viewport.offsetTop = 120 + viewport.dispatchEvent(new Event('scroll')) + }) + expect(menu.style.left).toBe('280px') + expect(menu.style.top).toBe('344px') + act(() => { + viewport.height = 200 + viewport.dispatchEvent(new Event('resize')) + }) + expect(menu.style.top).toBe('228px') + ui.unmount() + expect(remove.mock.calls.map(([type]) => type)).toEqual(expect.arrayContaining(['scroll', 'resize'])) + }) + it('follows an anchor moving without scroll or resize and stops tracking when closed or unmounted', () => { vi.useFakeTimers({ toFake: ['requestAnimationFrame', 'cancelAnimationFrame'] }) let rect = new DOMRect(40, 100, 32, 28) @@ -703,6 +822,52 @@ describe('Menu', () => { />) expect(screen.getByRole('menu').className).not.toMatch(/scrollable/) }) + + it('keeps the near viewport margin when the list cannot fit the visible viewport', () => { + // jsdom lays nothing out, so the list's own size and the viewport it has to + // fit inside are stubbed: this is the tall workspace list on a phone, where + // the browser chrome leaves less height than the list needs. + const height = vi.spyOn(HTMLDivElement.prototype, 'offsetHeight', 'get').mockReturnValue(900) + const width = vi.spyOn(HTMLDivElement.prototype, 'offsetWidth', 'get').mockReturnValue(900) + vi.stubGlobal('innerHeight', 600) + vi.stubGlobal('innerWidth', 600) + try { + render( {}} onClose={() => {}} />) + const menu = screen.getByRole('menu') + expect(menu.style.top).toBe('12px') + expect(menu.style.left).toBe('12px') + } finally { + height.mockRestore() + width.mockRestore() + vi.unstubAllGlobals() + } + }) + + it('clamps inside the visual viewport where the browser reports a smaller one', () => { + // Mobile browser chrome: the visual viewport is what the user sees, while + // window.innerHeight keeps the taller layout viewport. + const height = vi.spyOn(HTMLDivElement.prototype, 'offsetHeight', 'get').mockReturnValue(400) + vi.stubGlobal('innerHeight', 900) + vi.stubGlobal('innerWidth', 900) + vi.stubGlobal('visualViewport', Object.assign(new EventTarget(), { width: 500, height: 500, offsetLeft: 0, offsetTop: 0 })) + try { + render( + new DOMRect(10, 700, 40, 20)} + anchor={null} + items={items} + onSelect={() => {}} + onClose={() => {}} + />) + // 500 - 400 - 12, not the layout viewport's 900. + expect(screen.getByRole('menu').style.top).toBe('88px') + } finally { + height.mockRestore() + vi.unstubAllGlobals() + } + }) }) describe('Modal', () => { @@ -733,6 +898,22 @@ describe('Modal', () => { expect(onClose).toHaveBeenCalledTimes(2) }) + it('places a decorative warning icon in the title only for warning dialogs', () => { + const view = render( {}}> +

    Review the consequences.

    +
    ) + const heading = screen.getByRole('heading', { name: 'Confirm change' }) + const icon = heading.querySelector('svg') + expect(icon).not.toBeNull() + expect(icon?.getAttribute('aria-hidden')).toBe('true') + expect(screen.getByText('Review the consequences.').querySelector('svg')).toBeNull() + view.rerender( {}}>Body) + expect(screen.getByRole('heading', { name: 'Confirm change' }).querySelector('svg')).toBeNull() + view.rerender( {}}>Body) + expect(screen.queryByRole('heading')).toBeNull() + expect(screen.getByRole('dialog').querySelector('svg')).toBeNull() + }) + it('renders headless content without the default close chrome', () => { render( {}} title="Custom surface" headless backdropBlur={false}> diff --git a/packages/client/ui-primitives/tests/checkbox.client.spec.tsx b/packages/client/ui-primitives/tests/checkbox.client.spec.tsx index 838a589dab..1386decedc 100644 --- a/packages/client/ui-primitives/tests/checkbox.client.spec.tsx +++ b/packages/client/ui-primitives/tests/checkbox.client.spec.tsx @@ -25,6 +25,14 @@ it('refuses label activation while disabled', () => { expect(screen.getByRole('checkbox').checked).toBe(true) }) +it('marks initial modal focus only when requested', () => { + const view = render( {}} />) + expect(screen.getByRole('checkbox').hasAttribute('data-modal-autofocus')).toBe(false) + view.rerender( {}} modalAutofocus />) + expect(screen.getByRole('checkbox').hasAttribute('data-modal-autofocus')).toBe(true) + expect(document.activeElement).not.toBe(screen.getByRole('checkbox')) +}) + it('preserves caller hover text', () => { const onChange = vi.fn() render() diff --git a/packages/client/ui-primitives/tests/context-menu.client.spec.tsx b/packages/client/ui-primitives/tests/context-menu.client.spec.tsx index 4639f49e40..ffef90d4dd 100644 --- a/packages/client/ui-primitives/tests/context-menu.client.spec.tsx +++ b/packages/client/ui-primitives/tests/context-menu.client.spec.tsx @@ -14,6 +14,7 @@ it('places pointer menus at the cursor above the frame inset and focuses after p getAnchorRect={() => new DOMRect(200, 20, 0, 0)} items={[{ id: 'copy', label: 'Copy' }]} />) const menu = view.getByRole('menu') expect(menu.style.top).toBe('24px') + expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe(`${window.innerHeight - 24}px`) await waitFor(() => { expect(document.activeElement).toBe(view.getByRole('menuitem')) }) fireEvent.pointerDown(document.body, { button: 2 }) expect(close).not.toHaveBeenCalled() diff --git a/packages/client/ui-primitives/tests/fixtures/markdown-dom/math-multiline-display.settled.txt b/packages/client/ui-primitives/tests/fixtures/markdown-dom/math-multiline-display.settled.txt deleted file mode 100644 index cb3815748b..0000000000 --- a/packages/client/ui-primitives/tests/fixtures/markdown-dom/math-multiline-display.settled.txt +++ /dev/null @@ -1,89 +0,0 @@ -
    -

    - #text "Opening line carries math:" - - - - - - - - #text "a" - - #text "+" - - #text "b" - - #text "c" - - #text "+" - - #text "d" - - #text "a+b\nc+d" -