diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml index 95484d284b..280cafd0db 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.i18n.yaml @@ -12,8 +12,8 @@ en: a15c7c13f167e5ac zh: 63bcc2ef60c2f344 /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/packaging-route-yao-pkg-pkg-s-sea-mode: - en: f1c2b60e9474111d - zh: 5de398b5e8554429 + en: da2d0e038a0cab9d + zh: 495c770640264c1d /agent-note-single-file-executable-sdk-runtime-distribution-single-exe/decision/the-serving-interface-is-a-plugin-inside-the-dsh-application: en: 5fdde26e9e8c6108 zh: 629559d733c1f0c5 diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md index a70ab115be..0a3b958af9 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.md @@ -25,6 +25,8 @@ The exe is packaged with the **`--sea` (enhanced SEA) mode** of [@yao-pkg/pkg](h The same patch makes the SEA bootstrap's native-addon extraction atomic. On the first `dlopen` of an addon inside the VFS, pkg's `patchDlopen` copies the addon's package tree to `$PKG_NATIVE_CACHE_PATH/pkg//` (default `~/.cache/pkg/...`), a per-user directory that every concurrent process of the same executable shares; upstream writes each file straight to its final path with `writeFileSync`, which truncates a file another process may already have mapped and lets that process's `existsSync`/hash check read a half-written file. Concurrent first starts therefore die with SIGBUS on Linux or fail with `ERR_DLOPEN_FAILED: Library not loaded` on sharp's libvips on macOS (#4664). The patch routes the three write sites through a same-directory temporary file and `renameSync`, so a cache path is either absent or complete, every process finishes its own copy pass before it loads, and concurrent renames of identical content need no lock. The cache location, hash keying, and per-file comparison are unchanged, so a consumer that isolates the cache per instance through `PKG_NATIVE_CACHE_PATH` keeps working; worker threads only define the hook and never install it. Measured (linux-x64, node24 target, pkg 6.21.0, a probe that loads sharp with its 18 MB libvips library, 16 concurrent first starts against one empty cache, five rounds): 39 of 80 processes died with SIGBUS before the change and 0 of 80 after it, with no temporary files left behind. +The same patch makes the VFS honor `{ bigint: true }` in `stat`, `lstat`, their synchronous forms, and `fs.promises`. Upstream returns the same number-valued stats whatever the options, while `dsh-fs-local` and `dsh-fs-sandbox` read VFS paths through BigInt stats, so every `ctx.fs` access to a packaged file failed with `Cannot mix BigInt and other types`: the `read` tool could not open a packaged skill file, and a `skill-filesystem` root inside the VFS made skill discovery incomplete. The patch converts a VFS entry's numbers to the `BigIntStats` fields, including nanosecond times derived from the millisecond values; paths outside the VFS keep Node's own results. + Terminology reminder: pkg's `/snapshot` VFS has nothing to do with this repo's testing-system "snapshot" (ACP replay expected outputs, `$DSH_SNAPSHOT`); this document says "VFS" for the former. ### The serving interface is a plugin inside the dsh application diff --git a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md index e1ff276504..d7ef76d0e8 100644 --- a/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-10-single-file-executable-sdk-runtime-distribution.zh.md @@ -25,6 +25,8 @@ exe 使用 [@yao-pkg/pkg](https://github.com/yao-pkg/pkg)(vercel/pkg 归档后 同一补丁还把 SEA bootstrap 的原生插件解包改成原子写入。VFS 内的插件首次 `dlopen` 时,pkg 的 `patchDlopen` 会把该插件所在的包目录整棵拷到 `$PKG_NATIVE_CACHE_PATH/pkg/<.node 文件的 sha256>/`(默认 `~/.cache/pkg/...`),这是同一个 exe 的所有并发进程共用的按用户目录;上游用 `writeFileSync` 直接写目标路径,会把另一个进程可能已经映射的文件截断,并让该进程的 `existsSync`/哈希比对读到写了一半的文件。因此并发首次启动在 Linux 上以 SIGBUS 崩溃,在 macOS 上对 sharp 的 libvips 报 `ERR_DLOPEN_FAILED: Library not loaded`(#4664)。补丁让三处写入都经过同目录临时文件加 `renameSync`,于是缓存路径要么不存在、要么完整,每个进程都在加载前走完自己的拷贝,相同内容的并发 rename 不需要锁。缓存位置、哈希键与逐文件比对均未改变,通过 `PKG_NATIVE_CACHE_PATH` 按实例隔离缓存的消费方照常工作;worker 线程只定义该钩子而从不安装。 实测(linux-x64、node24 构建目标、pkg 6.21.0,一个加载 sharp 及其 18 MB libvips 库的探针,16 个进程对同一个空缓存并发首次启动,跑五轮):改动前 80 个进程中 39 个以 SIGBUS 崩溃,改动后 80 个全部正常,且无残留临时文件。 +同一补丁还让 VFS 的 `stat`、`lstat`、它们的同步形式以及 `fs.promises` 遵守 `{ bigint: true }`。上游无论选项如何都返回同一份数值型 stats,而 `dsh-fs-local` 与 `dsh-fs-sandbox` 通过 BigInt stats 读取 VFS 路径,因此经 `ctx.fs` 访问打包文件时都会以 `Cannot mix BigInt and other types` 失败:`read` 工具打不开打包的 skill 文件,位于 VFS 内的 `skill-filesystem` 根使 skill 发现不完整。补丁把 VFS 条目的数值转换为 `BigIntStats` 字段,其中纳秒时间由毫秒值换算;VFS 之外的路径仍使用 Node 自身的结果。 + 术语提醒:pkg 的 `/snapshot` VFS 与本仓库测试体系的「快照」(ACP(Agent Client Protocol)回放预期输出、`$DSH_SNAPSHOT`)无关,本文用「VFS」指前者。 ### 对外服务接口是 dsh 应用中的插件 diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml index 958a8e1545..97db170db9 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml @@ -9,8 +9,8 @@ en: 31fba384d90ce7d2 zh: f8b814868f3280c3 /agent-note-session-working-directory/decision: - en: 5de5171ee52a62b4 - zh: 7f78197ea38af658 + en: 5ff0c24c29c916b9 + zh: bfbb082623c2a86c /agent-note-session-working-directory/alternatives-considered: en: f0995feb9b6bcce8 zh: 97417085fd17f70f diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md index 779dd302d1..6b8a6c9507 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md @@ -16,11 +16,11 @@ Only Host operations change the directory: worktree creation and exit, the forge Required user-context snapshots carry the current value; each committed change attempts to queue a notice through the ordinary Agent inbox. Cancellation or disposal may discard unadmitted notices while the directory event survives for subsequent requests. The original project is the recovery destination when the selected directory disappears. Missing recovery destinations produce an error. Write permissions remain independent. -Subagents start in the parent's current directory or a Host-chosen directory and commit that directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. Project instructions, skills, and completion follow the effective directory without changing Session identity, grouping, or runtime composition. +Subagents start in the parent's current directory or a Host-chosen directory and commit that directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. The model's file and process tools, project instructions, skills, completion, and the sandbox boundary follow the effective directory, which is the [workspace root](2026-11-03-session-workspace-root.md), without changing Session identity, grouping, or runtime composition. -Live Session skill catalogs and file completion validate through the same directory owner. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directory. Cold skill catalogs read the recorded projection without activating an Agent. +Live Session skill catalogs and file completion validate through the same directory owner, then read the workspace root. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directories. Cold skill catalogs read the recorded root projection without activating an Agent. -Web sidebar terminal environment lookup reads the effective directory without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning; the process keeps that directory independently of later Session changes. +Web sidebar terminal environment lookup reads the workspace root without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning in the workspace root; the process keeps that directory independently of later Session changes. Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory. diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md index 18c7f9afea..8d99661c89 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md @@ -16,11 +16,11 @@ Status: implemented 必需的用户上下文快照携带当前值;每次已提交变更都会尝试通过普通 Agent 收件箱排入通知。取消或销毁可能丢弃尚未进入请求的通知,但目录事件仍然保留,供后续请求使用。所选目录消失时恢复到原始项目。恢复目录也消失时返回错误。写权限保持独立。 -子代理从父代理的当前目录或 Host 选定的目录启动,并在继承历史之后提交该目录。已有进程、终端和持久 shell 保留进程局部目录。项目指令、技能和补全跟随有效目录,不改变 Session 身份、归属或运行时组合。 +子代理从父代理的当前目录或 Host 选定的目录启动,并在继承历史之后提交该目录。已有进程、终端和持久 shell 保留进程局部目录。模型的文件与进程工具、项目指令、技能、补全和沙箱边界都跟随有效目录,即[工作区根](2026-11-03-session-workspace-root.zh.md),不改变 Session 身份、归属或运行时组合。 -活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的投影,不激活 Agent。 +活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录,再读取工作区根。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的根投影,不激活 Agent。 -Web 侧栏终端的环境查询读取有效目录,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录;后续 Session 目录变更不会改变该进程的目录。 +Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录,并在工作区根中启动;后续 Session 目录变更不会改变该进程的目录。 Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。 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 5207fd6764..b5619fae4c 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,8 +9,8 @@ en: abd0263d14861926 zh: e1736cd08e87f795 /agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision: - en: f1c2b98bf56cdba3 - zh: 7e9444f8e73a4834 + en: cf4dc376cbdb0e90 + zh: 6aea79fb9dfe419d /agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered: en: 3964f7d653747b55 zh: b50636faea4917ef 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 9592d362f0..d35b63180e 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 @@ -16,7 +16,7 @@ The library answers discriminated results and carries no failure vocabulary. `pa 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. +`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each reported user-message 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. `Duration` holds one span as a single millisecond count, and it is a class rather than a branded number because TypeScript's arithmetic erases a brand: adding two differently branded numbers answers an unbranded `number`, so a brand cannot stop seconds and milliseconds from being mixed, while an instance can. The unit is milliseconds because every producer and consumer in this repository already uses it (`Date.now()`, `SessionEvent.time`, the session log, the client), and because a double holds every millisecond of the whole `Date` range exactly, so no precision is spent on the unit. Instances are frozen, no coercion hook is overridden, and a span is bounded by the exactly representable millisecond range, which is what makes the split exact. The published surface is `fromMilliseconds` and a whole-part `decompose()`, the two entries the migrated consumer calls. 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 619cd29751..8576e9b889 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 @@ -16,7 +16,7 @@ Status: implemented Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们调用共享解析器并映射其原因。纯 Cron/RRULE 解析与有界发生时点搜索归本库所有,接收显式参考时间,并通过 `fourDigitYearEpoch` 校验已提交时点。Schedule 拥有持久记录、折叠与状态转移权威、抗注入的框架文本、每日与每周日期遍历、投递限制及领域错误。共享值不拥有任务状态、墙钟或定时器。 -`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条 user-rpc 时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。 +`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条用户消息上报的时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。 `Duration` 以单一毫秒计数保存一段时间;它做成类而不是 branded number,是因为 TypeScript 的算术会抹掉 brand:两个不同品牌的数字相加得到的是无品牌的 `number`,所以 brand 挡不住秒与毫秒的混用,而实例可以。单位选毫秒,是因为本仓库的每个生产者与消费者本来就用它(`Date.now()`、`SessionEvent.time`、Session 日志、客户端),也因为 double 能精确表示 `Date` 全范围内的每一个毫秒,这个单位不消耗任何精度。实例被冻结,不覆盖任何强制转换钩子,且时间段受可精确表示的毫秒范围约束——这正是拆分精确的前提。公开面就是 `fromMilliseconds` 与整数量拆解 `decompose()`,即已迁移消费方所调用的两个入口。 diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml index 68269e8997..93432e3ee9 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.i18n.yaml @@ -15,8 +15,8 @@ en: 7f33895364a9f5cc zh: f1c79ea15f5c151e /agent-note-initial-draft-content-and-structured-reference-restoration/decision/classes-and-methods: - en: e57394545d9d93ff - zh: 5ab142e661750b82 + en: 9039c6bf700da3cf + zh: 2808757aed8615b3 /agent-note-initial-draft-content-and-structured-reference-restoration/decision/data-flow: en: dd57e639e9328f1d zh: 5e16cb2e3a73597c diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md index cbb15cc56a..24355ccf35 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.md @@ -37,7 +37,7 @@ The existing `dsh.conversation.` key remains. Readers accept both leg | `SessionInputShell.refreshLexiconSubscription()` / `DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` owns the Session-scope `inject` callback that connects the lexicon after caching the shell, reconnects when the service arrives or is replaced, and unsubscribes on disposal. Both connection and catalog updates rescan the current editor without writing old text back; `setDraft` does not establish the subscription | | `ConversationStoreState` / `createConversationStore` | Support structured input and legacy strings in draft storage, keeping View state and the original key | | `DefaultConversationViews` | Remove restoration and prefill effects, retaining persistence binding and unbinding. Initial saving reads the owner's current snapshot, never text captured during render | -| The existing `selectWorkspace` callback in `apply.ts` | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | +| The cross-Workspace draft move (`moveDraft` in `apply.ts`) | Keep the existing cross-Workspace draft-transfer rules, passing `draftSnapshot` instead of plain text so transfer retains references | There is no new draft service, storage key, general task framework, or Session creation entry point. SlotRenderer, Host Session logs, command execution, and file-discovery RPCs are unchanged. `InputActions` remains the shared input-action entry; components receive no separate content-initialization callback. diff --git a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md index 12d4e4731a..8a3a964e95 100644 --- a/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-30-structured-draft-initialization.zh.md @@ -37,7 +37,7 @@ Status: implemented | `SessionInputShell.refreshLexiconSubscription()`/`DraftEditorRuntime.refreshLexiconSubscription()` | `InputHub` 拥有 Session scope 的 `inject` 回调,在缓存输入对象后连接词典,服务到达或替换时重接,销毁时退订。连接和词典更新都会重扫当前 editor,不覆盖旧文本;`setDraft` 不负责建立订阅 | | `ConversationStoreState`/`createConversationStore` | draft 支持兼容旧字符串的结构化输入,View 状态及原 key 保持 | | `DefaultConversationViews` | 删除恢复/预填 effect;保留持久化回调的绑定和解绑。初始保存只能读取 owner 的当前快照,不能把 render 时的旧文字写回 | -| `apply.ts` 中现有 `selectWorkspace` 回调 | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | +| 跨工作区的草稿移动(`apply.ts` 中的 `moveDraft`) | 沿用原有跨工作区携带规则,但传递 `draftSnapshot` 而不是纯文本,防止携带时再次丢失引用 | 不新增草稿服务、存储 key、通用任务框架或另一套 Session 创建入口;不改 SlotRenderer、Host Session 日志、命令执行和文件发现 RPC。`InputActions` 保留统一输入操作入口,组件不单独注入另一条内容初始化回调。 diff --git a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml index b21f9c6fb1..6ab2ebf052 100644 --- a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.i18n.yaml @@ -9,11 +9,11 @@ en: 755fe8a192cfebe1 zh: 855ad2920b33e364 /agent-note-runtime-download-of-upstream-skills/decision: - en: e601879f83a17cba - zh: a5ab03a7804787fc + en: 98f6d4a4c6b7849f + zh: a361378d5020c954 /agent-note-runtime-download-of-upstream-skills/alternatives-considered: - en: 3828cc141c037db6 - zh: 3a164d7a5886cbd2 + en: 250ab524fc33cd94 + zh: bc4d8008af1f9d61 /agent-note-runtime-download-of-upstream-skills/consequences: - en: 124556ff88e9e014 - zh: d25070f79bb2c726 + en: 5df2a8d5d5b9fbb6 + zh: b827f6539833ee87 diff --git a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md index 8464038b57..5eb4974a94 100644 --- a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.md @@ -10,7 +10,7 @@ The WeCom and Tencent Meeting plugins index guides that their vendors publish on ## Decision -Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them in `$DSH_HOME/cache/`, and lists the entry skill with that directory as its base directory. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin. +Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the upstream files by repository, commit, kept directory, exclusions, license file, total size, and a digest of the kept files, and registers both with `ctx.upstreamSkills`, the Service of [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.md). The Service downloads the commit archive from GitHub when the plugin loads, keeps the directory and the license file, verifies them, publishes them under `$DSH_HOME/cache/`, and lists the entry skill with the published directory as its base directory. In a profile the files go to that profile's own directory, `$DSH_HOME/cache//`, which only that profile's processes read, and each registration deletes the other pins there once, when its own pin first is in place: a plugin update leaves one copy, and an unchanged pin is never downloaded again. The plugin shows the download state beside the account state. Its check reads only the account and restarts a failed download without waiting for it: the CLI account runtime runs one operation at a time, so a check that waited for a slow GitHub download would also hold sign-in. Each archive source has `skillsTimeoutMs` to deliver the whole archive, and reading stops once the kept files exceed the pinned size. A plugin's `skillsDir` points at prepared files for tests and offline installations, and the Service's `skillsUrls` replaces the archive host for every plugin. ## Alternatives considered @@ -24,8 +24,14 @@ Each of these plugins keeps only its DSH-authored entry `SKILL.md`, pins the ups **A digest of the archive bytes.** The files of a commit archive are stable, but GitHub does not keep its compressed bytes stable, so the digest covers the kept files' paths and contents instead. +**One cache directory shared by every profile.** It saves one download per profile. Two DSH installations of different versions on one `$DSH_HOME` can pin different commits for one plugin, so deleting a replaced pin there deletes files the other installation reads, and keeping every pin leaves a copy per plugin update. + +**Deleting the other pins after every download.** Processes of one profile can run different versions of a plugin at the same time, such as one started before a plugin update and one started after it, and they share the profile's directory. Each would delete the other's pin after each of its downloads and download its own again at its next check, without end. Deleting once per registration ends that: the later process still deletes the earlier one's pin once, the earlier one downloads it again, and both pins stay until another load. A record of the pins in use, or a period during which a replaced pin stays, would also keep the running process's pin, at the price of a protocol between processes or of a second copy for that period. + +**The DSH version in the directory name.** Connector packages carry the DSH version, but a version in the name does not decide which installation may delete which directory, and it downloads the files again at every DSH release although the pin rarely changes. + **DingTalk's downloader.** DingTalk downloads checksummed release assets together with its executable. WeCom and Tencent Meeting publish no release assets and install their CLIs from npm, so only these two plugins register with this Service, and DingTalk keeps its own downloader. ## Consequences -The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Published directories are never pruned. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it. +The repository and the plugins' npm packages carry only the entry skills. The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the failure, which its next check retries. Tests, recorded Sessions, and Web end-to-end tests set `skillsDir` to fixture files and make no network requests. Each profile that loads a plugin downloads its own copy. A process that still runs another version of a plugin loses its pin once to a later process of the same profile and downloads it again at its next check. Removing a plugin leaves its pin in the cache, and without a profile no pin is deleted. Updating a pin is a code change: `scripts/upstream-skills-digest.ts` prints the new pin, and the entry's guide index and a real-model run follow it. diff --git a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md index 5cf2467522..b7bbcb491e 100644 --- a/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-28-upstream-skills-runtime-download.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>`,再列出入口技能,并把这个目录作为它的基础目录。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。 +这些插件只保留 DSH 自己编写的入口 `SKILL.md`,按仓库、提交、保留的目录、排除项、许可证文件、总大小和保留文件的摘要固定上游文件,并把两者注册到 `ctx.upstreamSkills`,即 [`@deepseek-ai/dsh-upstream-skills`](../../../../packages/connector/upstream-skills/README.zh.md) 的 Service。插件加载时,Service 从 GitHub 下载这个提交的归档,保留该目录和许可证文件,校验后发布到 `$DSH_HOME/cache/<插件>` 下,再列出入口技能,并把发布的目录作为它的基础目录。在 profile 中,文件发布到这个 profile 自己的目录 `$DSH_HOME/cache/<插件>/`,只有这个 profile 的进程读取它;每次注册在自己的固定提交第一次就位时,删除一次那里其他的固定提交:插件更新后只留下一份,固定提交不变时也不会重新下载。插件在账号状态旁显示下载状态。它的检查只读取账号,并在不等待的情况下重新开始失败的下载:CLI 账号运行时一次只执行一个操作,检查若等待缓慢的 GitHub 下载,登录也会被占住。每个归档来源要在 `skillsTimeoutMs` 内送达完整归档,保留文件超过固定的大小时停止读取。插件的 `skillsDir` 为测试和离线安装指向准备好的文件,Service 的 `skillsUrls` 为所有插件替换归档主机。 ## 考虑过的替代方案 @@ -24,8 +24,14 @@ Status: implemented **对归档字节做摘要。** 提交归档中的文件是稳定的,但 GitHub 不保证压缩后的字节稳定,因此摘要覆盖保留文件的路径和内容。 +**所有 profile 共用一个缓存目录。** 它让每个 profile 少下载一次。同一个 `$DSH_HOME` 上两个不同版本的 DSH 安装,可能为同一个插件固定不同的提交,因此在那里删除被替换的固定提交,会删掉另一个安装正在读取的文件;而全部保留,则每次插件更新都多留一份。 + +**每次下载完成后都删除其他固定提交。** 同一个 profile 的多个进程可以同时运行同一插件的不同版本,例如一个在插件更新之前启动,另一个在更新之后启动,它们共用这个 profile 的目录。这样每个进程都会在自己每次下载完成后删除对方的固定提交,并在下一次检查时重新下载自己的,没有尽头。每次注册只删除一次就结束了这个循环:后启动的进程仍会删除一次先启动的进程的固定提交,先启动的进程重新下载,此后两个固定提交都保留,直到下一次加载。记录正在使用的固定提交,或让被替换的固定提交保留一段时间,也能保住运行中进程的固定提交,代价是进程之间要有一套约定,或者在这段时间里多留一份。 + +**在目录名中加入 DSH 版本。** Connector 包的版本与 DSH 版本一致,但目录名里的版本并不能决定哪个安装可以删除哪个目录,而且固定提交很少变化,每次 DSH 发版却都要重新下载这些文件。 + **钉钉的下载器。** 钉钉把带校验和的发布资产和可执行文件一起下载。企业微信和腾讯会议没有发布资产,CLI 从 npm 安装,因此只有这两个插件注册到这个 Service,钉钉保留自己的下载器。 ## 影响 -仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。已发布的目录从不清理。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。 +仓库和插件的 npm 包里只有入口技能。换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示失败,下一次检查会重试。测试、录制的 Session 和 Web 端到端测试都把 `skillsDir` 设为夹具文件,不发起网络请求。每个加载该插件的 profile 都各自下载一份。仍在运行插件另一个版本的进程,会被同一 profile 后启动的进程删除一次固定提交,并在下一次检查时重新下载。移除插件后,它的固定提交仍留在缓存中;没有 profile 时,任何固定提交都不会被删除。更新固定提交需要改代码:`scripts/upstream-skills-digest.ts` 输出新的固定信息,随后更新入口的子指南索引,并用真实模型运行一次。 diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml index 5c0fef0e12..e175e54207 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.i18n.yaml @@ -9,8 +9,8 @@ en: 3f5dacf86015cebb zh: cf0d5bceb9941554 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision: - en: 0682ebef17f6a5e7 - zh: 6ea399459262eb0c + en: e243a7d535022011 + zh: fd1dd8634b9603cf /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/registered-providers-are-observable-availability-is-not: en: 38ce796dea91fa35 zh: d312a9cd29fd5cc9 @@ -21,17 +21,17 @@ en: dca56d7ced4e5294 zh: e984a7fddac3228f /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/defaults-and-stored-selections: - en: 5fcd3319fbceed1d - zh: 20771646b9c36fa6 + en: eba9b7ca32681406 + zh: 7ab74b8054bea720 /agent-note-web-provider-selection-independent-menus-over-registered-providers/decision/legacy-messages-search: - en: 2c7c84f8fa1e8745 - zh: 5d0244e4f17ba12a + en: 8f3180e3dd327bfc + zh: 012b2ebe8d2f5aac /agent-note-web-provider-selection-independent-menus-over-registered-providers/alternatives-considered: - en: 2ec7f019ec3ce309 - zh: a6a5a8db1f1dd682 + en: d72b359bb9ff9666 + zh: 33c9a12488a81826 /agent-note-web-provider-selection-independent-menus-over-registered-providers/consequences: - en: ea4d3f05e8be197a - zh: 81faeb3edf122869 + en: fe529b10fcbb2d0a + zh: ed3eabbce90ddb92 /agent-note-web-provider-selection-independent-menus-over-registered-providers/verification: - en: 0db673b16e4aeda3 - zh: 3b086edecebdc5b5 + en: a8f08dc7ec5845fd + zh: a491c4a93db41c3f diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md index 9c903db910..de93ba4bb9 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.md @@ -10,7 +10,7 @@ The web service selects search and fetch providers through two independent field ## Decision -Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition selects the Search API for search and local HTTP fetch for fetch, and the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential. +Users choose search and fetch providers independently from the Host's registered provider lists. The shipped composition fixes no search provider, so search follows the conversation's model route, and selects local HTTP fetch for fetch; the DeepSeek Search and Fetch APIs follow the conversation's DeepSeek credential. ### Registered providers are observable; availability is not @@ -38,18 +38,24 @@ A capability whose YAML sets a non-empty `searchBaseURL` or `searchApiKeyEnv` (` ### Defaults and stored selections -The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `searchProvider: deepseek-search-api` and `fetchProvider: http`. Search defaults to the Search API because it returns sources without Harness starting an auxiliary model request. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away. +The [base composition](../../../../packages/bundle/base/cordis.patch.yml) sets `fetchProvider: http` and no `searchProvider`. With no search provider configured, `dsh-web` prefers one registered, usable provider per provider route of the model request a search serves: Messages search (`deepseek-official`) on the `deepseek-official` and `deepseek-account` model routes, because DeepSeek makes no per-search charge for the server-side search tool a DeepSeek model request declares, and the Search API (`deepseek-search-api`) on every other route and outside a model request, because it returns sources without an auxiliary model request to a provider the conversation does not use. `dsh-tool-web` puts the route of the calling Session's latest model request into each search request, and `searchReady()` selects with the route of the step being prepared, so readiness and execution name the same provider. The two routes and two provider ids are constants of `dsh-web`: a deployment changes the outcome only by configuring `searchProvider`, and the settings page shows the unconfigured state as **Automatic**. Fetch defaults to local HTTP fetch because it has no per-request API charge, applies Harness's own URL validation and resource limits, and reaches intranet and local addresses. The Fetch API remains one menu choice away. A stored selection, whether in the settings document or in a deployment's own composition, wins over the shipped default, and an upgrade does not rewrite it. A selection is never replaced at execution: when the selected provider is missing, unavailable, or fails, the operation fails with its structured error and does not fall back to another search or fetch provider. A fallback would send the query and credential to an endpoint the user did not choose and change billing without notice. ### Legacy Messages search -The DeepSeek Messages search provider remains available as **DeepSeek (legacy)**. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider. +The DeepSeek Messages search provider remains available as **DeepSeek server-side search** and serves unconfigured searches on the DeepSeek model routes. A stored `web.searchProvider: deepseek-official` (or `DSH_WEB_SEARCH_PROVIDER=deepseek-official`) selects it for every route, so users whose gateways serve Messages search but not `/v1/tools` can retain their working provider. The Messages provider owns and writes `web/deepseek-search-llm-request`. The declaration and payload retain compatibility with released Sessions; the Search and Fetch API package neither declares nor writes this auxiliary event. ## Alternatives considered +**Let each provider declare the routes it is the default for.** A `defaultFor(llmProvider)` member on `WebSearchProvider` keeps `dsh-web` free of DeepSeek ids, but it changes both DeepSeek provider packages for a rule that has one instance. + +**Put the route-to-provider table in `dsh-web` configuration.** A profile patch replaces a row's whole `config`, so a stored provider selection would also store a copy of the table and stop following the shipped one, and the table is not a choice users need: fixing a provider already overrides it. + +**Have the Search API provider delegate to Messages search on DeepSeek routes.** The menu would keep two entries, but the entry named DeepSeek Search API would run another provider, a user could not fix the Search API for a DeepSeek model, and one provider package would depend on the other. + **Keep one switch for both APIs.** It lets Fetch API adoption need no configuration edit, but it ties fetch billing and target access policy to the search choice, and it cannot express a provider that another plugin registers. **Filter the lists by availability, or add availability to each entry.** A filtered list hides a provider while its credential is missing, right when the user needs to choose and configure it. Availability also depends on the request's model route and credential state, so a listed boolean could disagree with execution. The archived [observation-surface decision](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md) allows only the smallest signal a consumer reads; the menus read registration only. @@ -76,10 +82,10 @@ The Messages provider owns and writes `web/deepseek-search-llm-request`. The dec ## Consequences -Users without a stored search selection search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures until they select Messages search or set `searchBaseURL` to a base that serves them. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup. +Users without a stored search selection search through Messages search in a conversation on a DeepSeek model route: each search is one auxiliary Messages request billed as model tokens, to Messages search's own endpoint, which does not follow the model provider's base URL, so a deployment whose DeepSeek model provider points at a gateway gets search failures until it saves that gateway as the Messages Base URL or fixes the Search API ([upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md)). On every other route they search through the Search API: their queries go to the Search endpoint the conversation's DeepSeek credential selects, cost a Search API request each, and send up to 128 characters of the latest human prompt as `ori_question` unless `sendOriginalQuestion` is off. Deployments whose gateway has no `/v1/tools` routes get search failures there until they select Messages search or set `searchBaseURL` to a base that serves them. `dsh-web` names two DeepSeek model routes and two DeepSeek search providers, which a second route-specific default would have to replace with a provider-neutral rule. A stored `deepseek-official` selection uses Messages search. Users without a stored fetch selection fetch through local HTTP fetch. A signed-in user without an API key has DeepSeek web search with `auto` billing in every conversation except those on the DeepSeek API-key route; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.md) lists each affected setup. A plugin provider, including one written in creator mode, appears in the matching menu as soon as it registers, under its `title`. The menus can offer a provider that cannot run for the current request; the failure appears when a search or fetch runs. Each registry change costs one forwarded event and one list read in each Client that observes it. ## Verification -[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, and contained listener failures. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps. +[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) covers list contents and order, titles, events after registration and disposal, no event for a rejected duplicate, contained listener failures, and the per-route preference with its fallbacks; [tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) covers the route `web_search` sends, and the `web-search-legacy-endpoint-guidance` snapshot runs Messages search on a DeepSeek route with no provider configured. [deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) covers the independent Messages provider, and [credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) covers, for both capabilities, the account token on the account route and its invalidation after HTTP 401, the API-key fallback without a sign-in, the route key and endpoint in official, non-DeepSeek, and Session-less conversations, the account fallback without a key outside the DeepSeek routes, account-only and API-key-only billing on every route, own fields over billing, `DEEPSEEK_API_KEY` and the official base without that route, YAML-only own fields that never send the token, independent capabilities, readiness matching each operation, and ignored removed fields; [composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) boots the real model routes through the Loader. [remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) covers event forwarding, and [base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) pins the shipped defaults. The settings page's controller and card specs and the [plugin configuration browser scenario](../../../../apps/web/tests/plugin-config.e2e.ts) cover menu contents, independent Search and Fetch selection, the billing menus of the DeepSeek APIs, and the settings each provider keeps. diff --git a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md index ae7f79c9cb..b76ac74083 100644 --- a/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-29-web-provider-selection.zh.md @@ -10,7 +10,7 @@ Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 两个独立字段 ## 决策 -用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合将搜索设为 Search API,将抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。 +用户从 Host 已注册的提供方列表中分别选择搜索和抓取提供方。内置组合不固定搜索提供方,搜索因此跟随会话的模型路由,抓取设为本地 HTTP 抓取;DeepSeek Search 与 Fetch API 跟随会话的 DeepSeek 凭据。 ### 已注册的提供方可观察,可用性不可观察 @@ -38,18 +38,24 @@ Search 与 Fetch 各有一个计费方式设置 `web-deepseek-api.searchBilling` ### 默认值与已保存的选择 -[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `searchProvider: deepseek-search-api` 和 `fetchProvider: http`。搜索默认使用 Search API,因为它返回来源时无需 Harness 发起辅助模型请求。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。 +[base 组合](../../../../packages/bundle/base/cordis.patch.yml)设置 `fetchProvider: http`,不设置 `searchProvider`。没有配置搜索提供方时,`dsh-web` 按搜索所服务的模型请求的提供方路由,优先选用一个已注册且可用的提供方:在 `deepseek-official` 与 `deepseek-account` 模型路由上是 Messages 搜索(`deepseek-official`),因为 DeepSeek 不对 DeepSeek 模型请求声明的服务端搜索工具按次收费;在其他路由上以及模型请求之外是 Search API(`deepseek-search-api`),因为它返回来源时无需向会话没有使用的提供方发起辅助模型请求。`dsh-tool-web` 把发起调用的 Session 最近一次模型请求的路由写入每个搜索请求,`searchReady()` 按正在准备的步骤的路由选择,因此就绪判断与执行指向同一个提供方。这两条路由和两个提供方 id 是 `dsh-web` 中的常量:部署只能通过配置 `searchProvider` 改变结果,设置页把未配置的状态显示为**自动选择**。抓取默认使用本地 HTTP 抓取,因为它没有按次的 API 费用,执行 Harness 自身的 URL 校验和资源限制,并且可以访问内网和本地地址。Fetch API 仍可在下拉框中直接选择。 已保存的选择——无论位于设置文档还是部署自身的组合中——优先于内置默认值,升级不会改写它。执行时从不替换选择:所选提供方缺失、不可用或失败时,操作以结构化错误失败,不会回退到其他搜索或抓取提供方。回退会把查询和凭据发往用户未选择的端点,并在不提示的情况下改变计费。 ### 旧版 Messages 搜索 -DeepSeek Messages 搜索提供方仍以 **DeepSeek(旧版)**提供。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。 +DeepSeek Messages 搜索提供方仍以 **DeepSeek 服务端搜索**提供,并承担 DeepSeek 模型路由上未配置提供方的搜索。已保存的 `web.searchProvider: deepseek-official`(或 `DSH_WEB_SEARCH_PROVIDER=deepseek-official`)会在所有路由上选中它,因此网关支持 Messages 搜索但不提供 `/v1/tools` 的用户可以保留可用的提供方。 Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声明和载荷保持与已发布会话兼容;Search 与 Fetch API 包既不声明也不写入这一辅助事件。 ## 考虑过的替代方案 +**让每个提供方声明自己是哪些路由的默认项。** 在 `WebSearchProvider` 上加一个 `defaultFor(llmProvider)` 成员可以让 `dsh-web` 不含 DeepSeek 的 id,但要为只有一个实例的规则修改两个 DeepSeek 提供方包。 + +**把路由到提供方的表放进 `dsh-web` 的配置。** profile 补丁会替换条目的整个 `config`,因此已存的提供方选择会连带存下这张表的副本,不再跟随内置的表;而这张表也不是用户需要做的选择:固定提供方已经可以覆盖它。 + +**让 Search API 提供方在 DeepSeek 路由上转交给 Messages 搜索。** 菜单可以保持两项,但名为 DeepSeek Search API 的条目会运行另一个提供方,用户无法为 DeepSeek 模型固定 Search API,而且一个提供方包要依赖另一个。 + **保留一个同时切换两个 API 的开关。** 它让使用 Fetch API 无需修改配置,但把抓取的计费和目标访问策略绑在搜索选择上,也无法表达其他插件注册的提供方。 **按可用性过滤列表,或在每个条目中加入可用性。** 过滤后的列表恰好会在凭据缺失时隐藏提供方,而这正是用户需要选择并配置它的时候。可用性还取决于请求的模型路由和凭据状态,列表中的布尔值可能与实际执行结果不一致。已归档的[观察面决策](../../archived/simplification/2026-07-04-drop-unconsumed-web-observation-surface.md)只允许引入消费方实际读取的最小信号;下拉框只读取注册情况。 @@ -76,10 +82,10 @@ Messages 提供方负责声明并写入 `web/deepseek-search-llm-request`。声 ## 影响 -没有已保存搜索选择的用户通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。 +没有已保存搜索选择的用户在 DeepSeek 模型路由上的会话中通过 Messages 搜索进行搜索:每次搜索是一次按模型 token 计费的辅助 Messages 请求,发往 Messages 搜索自己的端点,该端点不跟随模型提供方的基础地址,因此 DeepSeek 模型提供方指向网关的部署会遇到搜索失败,直到把该网关保存为 Messages Base URL 或固定使用 Search API([升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md))。在其他路由上他们通过 Search API 搜索:查询发往会话的 DeepSeek 凭据所选的 Search 端点,每次计为一次 Search API 请求,并且除非关闭 `sendOriginalQuestion`,还会把最近一条用户提示的至多 128 个字符作为 `ori_question` 发送。网关没有 `/v1/tools` 路由的部署在这些路由上会遇到搜索失败,直到选择 Messages 搜索,或把 `searchBaseURL` 设为提供这些路由的基础地址。`dsh-web` 点名了两条 DeepSeek 模型路由和两个 DeepSeek 搜索提供方,再出现一个按路由的默认值时须改为提供方无关的规则。已保存的 `deepseek-official` 选择使用 Messages 搜索。没有已保存抓取选择的用户通过本地 HTTP 抓取。已登录但没有 API 密钥的用户在 `auto` 计费下,除 DeepSeek API 密钥路由上的会话外,都可以使用 DeepSeek 网页搜索;[升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/web-search-credential-modes/guide.zh.md)列出了每种受影响的配置。 插件提供方(包括在创作模式下编写的提供方)一经注册,就会以其 `title` 出现在对应的下拉框中。下拉框可能提供在当前请求中无法运行的提供方;失败会在执行搜索或抓取时出现。每次注册表变更会在每个观察它的 Client 中产生一次转发事件和一次列表读取。 ## 验证 -[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件,以及监听器失败的隔离。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。 +[web.spec.ts](../../../../packages/web/web/tests/web.spec.ts) 覆盖列表内容与顺序、标题、注册与撤销后的事件、重复注册被拒绝时不触发事件、监听器失败的隔离,以及按路由的优先规则及其回退;[tool-web.spec.ts](../../../../packages/web/tool-web/tests/tool-web.spec.ts) 覆盖 `web_search` 发送的路由,`web-search-legacy-endpoint-guidance` 快照在未配置提供方的 DeepSeek 路由上运行 Messages 搜索。[deepseek.spec.ts](../../../../packages/web/web-search-deepseek/tests/deepseek.spec.ts) 覆盖独立的 Messages 提供方,[credential-resolution.spec.ts](../../../../packages/web/web-deepseek-api/tests/credential-resolution.spec.ts) 针对两个能力覆盖账号路由上的账号令牌及其在 HTTP 401 后被作废、未登录时回退到 API 密钥、官方、非 DeepSeek 和会话之外的操作使用路由密钥与端点、DeepSeek 路由之外没有密钥时回退到账号、在每个路由上只用账号或只用 API 密钥的计费、单独字段优先于计费方式、没有该路由时使用 `DEEPSEEK_API_KEY` 与官方基础地址、从不发送令牌的 YAML 单独字段、两个能力相互独立、就绪判断与每次操作一致,以及被忽略的已移除字段;[composition.spec.ts](../../../../packages/web/web-deepseek-api/tests/composition.spec.ts) 通过 Loader 启动真实的模型路由。[remote-events.host.spec.ts](../../../../packages/api/remotes/tests/remote-events.host.spec.ts) 覆盖事件转发,[base.spec.ts](../../../../packages/bundle/base/tests/base.spec.ts) 固定内置默认值。设置页的 controller 与 card 测试以及[插件配置浏览器场景](../../../../apps/web/tests/plugin-config.e2e.ts)覆盖下拉框内容、Search 与 Fetch 的分别选择、DeepSeek API 的计费方式下拉框,以及各提供方保留的设置。 diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml index 863d2f26eb..772a8c6bcd 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -9,14 +9,11 @@ en: 6938aa715106bb99 zh: ea1497b337712f33 /agent-note-session-workspace-root/decision: - en: b42597fdf9838587 - zh: cb36853abde00754 -/agent-note-session-workspace-root/deferred: - en: 8807b3829badfdcd - zh: 2ec10ce7f0dda3f4 + en: 0b07db6326c2ecd6 + zh: 19ba9a1adf93af1f /agent-note-session-workspace-root/alternatives-considered: - en: 35ccc31b8b40d014 - zh: 7bf3c9f45afae8ab + en: 8a4859a6f96ef49e + zh: fa7088d29ebe3dd6 /agent-note-session-workspace-root/consequences: - en: 7cef9fcd81f95833 - zh: 4211d4ae53dd4974 + en: a6bf8aa40464f524 + zh: 61997dc31615bdbb diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md index e7e6eac1a3..a37849a230 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -16,9 +16,9 @@ A Session works in one directory, and only Host operations move it. The model-fa Worktree creation enters the checkout through `set`. The model has one tool for entering a checkout, `enter_worktree`: a name selects a worktree inside the pool of the checkout the Session works in. An existing one is entered through `ctx.worktrees.enter`, and a new one is created through `ctx.worktrees.create` when none has that name. The name cannot leave that pool, so the model still cannot choose an arbitrary directory. `ctx.worktrees.exit`, exposed as `exit_worktree`, returns the Session from the recorded worktree that contains its directory to the checkout it created or entered that worktree from. A child subagent keeps the parent's original project in its header and starts, through `set`, in the parent's directory or a Host-chosen directory. -## Deferred +Every consumer reads that directory. The model's file, search, and process tools resolve relative paths from it, and everything the user sees or that describes the project is bounded by it: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace. -The sandbox write boundary, the workspace file service, desktop file drag, the change recorder, and the client file tree, deliverables, open-in-app actions, and Session rows still read `header.cwd`. Until those consumers read the Session's directory, they behave as they did before this decision, and a worktree outside the original project is writable only where the original project's boundary already allows it. +The sandbox policy reads no Git layout: it bounds a Session by its directory and adds only the directories the deployment configured or a Host plugin registered for that Session through `registerWritableRoot`. A repository's Git directory lies outside a linked worktree, so after a move into a worktree a Git command that writes it, such as `git commit`, is denied under `workspace-write` until a grant covers that directory; the original project is not writable either. Granting the Git directory of the checkout a Session works in belongs to a separate plugin that reads the Git layout and registers the directory, which this decision defers. Host maintenance of a checkout the Session does not work in keeps the original boundary: removing a worktree on archive, restoring a removed one, and reading its branch in the source repository run under a policy the worktree service and the forge panel build themselves, the Session's mode and grants with the recorded source checkout as the root. The Session's own root may be the removed directory, and a process sandbox cannot bind a missing or vanishing root. ## Alternatives considered @@ -40,10 +40,10 @@ The sandbox write boundary, the workspace file service, desktop file drag, the c **Two public reads.** `get` for relative paths beside `rootOf` for the workspace root kept every stored directory, and made each consumer choose between two values that are equal in every Session started from this version on. One read removes that choice. -**Keep every stored directory.** Reading every stored `working-directory/change` as the directory would let a stored model `cd`, including one to a home directory, become the write boundary once consumers follow the directory. +**Keep every stored directory.** Reading every stored `working-directory/change` as the directory would let a stored model `cd`, including one to a home directory, become the write boundary, because consumers follow the directory. **Keep stored directories inside the original project.** A Session that entered a worktree would resume there, but the rule cannot tell a worktree from a `cd`: a stored `cd` into a subdirectory would narrow the write boundary and the file views, and a worktree outside the directory a Session was opened in would be dropped. ## Consequences -Consumers read one directory through `get`. A stored Session resumes in its original project whatever directory its `working-directory/change` events recorded, and follows Host moves from there. One that worked in a worktree returns to it through `enter_worktree`; until then its relative paths resolve in the original project. The model enters a checkout only through `enter_worktree`: a new one, or a registered one in the pool. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. The worktree snapshot fixture covers entering, leaving, and losing a worktree. Moving the consumers listed under Deferred is a separate change. +Consumers read one directory through `get`. A stored Session resumes in its original project whatever directory its `working-directory/change` events recorded, and follows Host moves from there. One that worked in a worktree returns to it through `enter_worktree`; until then its relative paths resolve in the original project. The model enters a checkout only through `enter_worktree`: a new one, or a registered one in the pool. A checkout elsewhere needs a Host operation. The ACP, SDK, and Web producers record the original project by its canonical spelling, so a Host move back to it records no change. A Session that works in a linked worktree, whether it entered one or was opened in one, cannot run `git commit` under `workspace-write` without a grant for the repository's Git directory; on the previous boundary a Session that entered a worktree inside its project could. An SDK `setWorkingDirectory` call and a child started in a Host-chosen directory move the `workspace-write` boundary with the directory. The worktree snapshot fixture covers entering, leaving, and losing a worktree. diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md index 96791eb6a6..c35b5a9f83 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -16,9 +16,9 @@ Status: implemented 工作树创建通过 `set` 进入检出目录。模型只有一个进入检出的工具 `enter_worktree`:名称在 Session 所在检出的池中选中一个工作树。已有的工作树通过 `ctx.worktrees.enter` 进入,没有同名工作树时通过 `ctx.worktrees.create` 新建。名称无法离开该池,因此模型仍然不能选择任意目录。`ctx.worktrees.exit` 以 `exit_worktree` 的形式提供,它找到包含 Session 目录的已记录工作树,把 Session 送回创建或进入该工作树时所在的检出。子代理的 header 保留父级的原始项目,并通过 `set` 从父级的目录或 Host 选定的目录启动。 -## Deferred +每个消费方都读取这个目录。模型的文件、搜索与进程工具从它解析相对路径,用户看到的、以及描述项目的一切都以它为界:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。 -沙箱写边界、工作区文件服务、桌面文件拖拽、变更记录器,以及客户端文件树、交付物、在应用中打开的操作和 Session 行仍然读取 `header.cwd`。在这些消费方改读 Session 的目录之前,它们的行为与本决策之前相同,位于原始项目之外的工作树只有在原始项目的边界已经允许时才可写。 +沙箱策略不读取任何 Git 布局:它以 Session 的目录为界,只加入部署配置的目录,以及 Host 插件通过 `registerWritableRoot` 为该 Session 注册的目录。仓库的 Git 目录位于链接工作树之外,因此移入工作树之后,写入它的 Git 命令(例如 `git commit`)在 `workspace-write` 下会被拒绝,直到有授权覆盖该目录;原始项目也不再可写。为 Session 所在检出目录授权其 Git 目录,属于一个读取 Git 布局并注册该目录的独立插件,本决策将其延后。Host 对 Session 并不在其中工作的检出目录做维护时保留原来的边界:归档时移除 worktree、恢复被删除的 worktree、在源仓库中读取其分支,都在 worktree 服务与 forge 面板自己构造的策略下运行,即沿用 Session 的模式与授权、以记录中的源检出目录为根。Session 自身的根可能正是被删除的目录,而进程沙箱无法绑定缺失或正在消失的根。 ## Alternatives considered @@ -40,10 +40,10 @@ Status: implemented **两个公开读取接口。** 用 `get` 读相对路径的基准、用 `rootOf` 读工作区根,可以保留每个已存储的目录,但每个消费方都要在两个值之间做选择,而这两个值在从这个版本起启动的每个 Session 中都相等。只保留一个读取接口,就不需要这种选择。 -**保留每个已存储的目录。** 把每条已存储的 `working-directory/change` 都读作目录,消费方跟随目录之后,已存储的模型 `cd`(包括进入用户主目录的)会成为写边界。 +**保留每个已存储的目录。** 把每条已存储的 `working-directory/change` 都读作目录,由于消费方跟随目录,已存储的模型 `cd`(包括进入用户主目录的)会成为写边界。 **保留原始项目之内的已存储目录。** 进入过工作树的 Session 会在工作树中恢复,但这条规则分不清工作树与 `cd`:已存储的进入子目录的 `cd` 会收窄写边界和文件视图,而位于 Session 打开目录之外的工作树会被丢弃。 ## Consequences -消费方通过 `get` 读取一个目录。无论 `working-directory/change` 事件记录了什么目录,已存储的 Session 都在原始项目中恢复,并从那里跟随 Host 移动。曾在工作树中工作的 Session 通过 `enter_worktree` 回到工作树;在此之前,它的相对路径在原始项目中解析。模型只能通过 `enter_worktree` 进入检出:新建的检出,或池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。工作树快照夹具覆盖进入、离开和失去工作树。迁移 Deferred 中列出的消费方是另一项变更。 +消费方通过 `get` 读取一个目录。无论 `working-directory/change` 事件记录了什么目录,已存储的 Session 都在原始项目中恢复,并从那里跟随 Host 移动。曾在工作树中工作的 Session 通过 `enter_worktree` 回到工作树;在此之前,它的相对路径在原始项目中解析。模型只能通过 `enter_worktree` 进入检出:新建的检出,或池中已登记的检出。其他位置的检出需要 Host 操作。ACP、SDK 与 Web 的生产方以规范拼写记录原始项目,因此 Host 移回原始项目时不记录变更。在链接工作树中工作的 Session,无论是进入的还是直接在其中打开的,在没有仓库 Git 目录授权时都不能在 `workspace-write` 下运行 `git commit`;在此前的边界下,进入项目内工作树的 Session 可以。SDK 的 `setWorkingDirectory` 调用以及在 Host 选定目录启动的子代理,会让 `workspace-write` 边界随目录一起移动。工作树快照夹具覆盖进入、离开和失去工作树。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index c07882cc9d..7bc1c28c58 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -12,8 +12,8 @@ en: 5d2dc730467e4bf3 zh: 4aca28691504cd7b /agent-note-change-request-panel-and-worktree-sessions/deferred: - en: 32ef8af85f4d2f66 - zh: b82b67f94346399e + en: e76e8129691db30f + zh: fd242e67bab2633d /agent-note-change-request-panel-and-worktree-sessions/alternatives-considered: en: e471e16b6b6450ca zh: 5fbc9242edc8d112 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index a21fbba569..b1ebb4a0ec 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -32,12 +32,7 @@ Review comments capture the file, side, range, complete hunk, and reviewed head ## Deferred -A left-navigation review page next to Plugins and Scheduled tasks, listing the user's pull requests or merge requests on the selected provider, is deferred. It attaches without changing this package's Session surfaces: - -- **Provider capability** — an optional `ForgeProvider` method such as `listForViewer(host, filter, signal)` returns change request references; GitHub implements it with `gh search prs --author @me` or the GraphQL `viewer`, and the registry aggregates enabled providers. -- **Remote** — a stream like `follow` that is keyed by provider and filter instead of a Session and polls through the same `ctx.forge.watch`. -- **Client** — a `sidebar.panellist` entry with a `main` page in this package, as `ui-schedule` does, rendering `ChangeRequestCard`, which takes a change request, its snapshot, and optional actions. -- **Settings** — provider choice and hosts on the bundle's configuration page. +The left-navigation review page this section deferred is implemented as the [code review page](2026-11-11-forge-review-page.md); its lists come from an optional provider capability and its page reads change requests by URL, so this package's Session surfaces did not change. The changes view offers no scope for one commit or for the last turn yet; both would be further `ForgeLocalScope` kinds read through `localDiff`. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 770db01822..344944caf2 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -32,12 +32,7 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 ## Deferred -在左侧导航“插件”“自动化任务”旁边新增代码审查页、列出用户在所选提供方上的 pull request 或 merge request,这项工作推迟。它的接入不需要改动本包面向 Session 的界面: - -- **提供方能力**——`ForgeProvider` 增加一个可选方法,例如 `listForViewer(host, filter, signal)`,返回变更请求引用;GitHub 用 `gh search prs --author @me` 或 GraphQL `viewer` 实现,注册表汇总已启用的提供方。 -- **Remote**——一条类似 `follow` 的流,以提供方与筛选条件而不是 Session 为键,通过同一个 `ctx.forge.watch` 轮询。 -- **客户端**——在本包中以 `sidebar.panellist` 条目加一个 `main` 页面实现(与 `ui-schedule` 相同),渲染接收变更请求、其快照与可选操作的 `ChangeRequestCard`。 -- **设置**——在套件的配置页中选择提供方与主机。 +本节曾暂缓的左侧导航代码审查页已实现为[代码评审页](2026-11-11-forge-review-page.zh.md);它的列表来自可选的提供方能力,页面按 URL 读取变更请求,因此本包的会话界面没有改变。 变更视图目前还没有单个提交与上一轮的范围;两者将是经 `localDiff` 读取的更多 `ForgeLocalScope` 种类。 diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml index 0780e32ff0..21d34452cc 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.i18n.yaml @@ -12,8 +12,8 @@ en: 43298ccae4f7a6d4 zh: eb7ef46b6f290c15 /agent-note-direct-deepseek-search-and-fetch-apis/decision/protocol-selection-and-deployment: - en: 90e5031d0d2fa9e4 - zh: a9c0229b20555d9e + en: b07c0667e25927aa + zh: 45eda3e151040201 /agent-note-direct-deepseek-search-and-fetch-apis/decision/search-results-and-model-input: en: ad7b3e4fbe528cf2 zh: 8ab8779bfdaaa4fa @@ -21,14 +21,14 @@ en: 7566e400f9ab3a51 zh: 118b2e84d0030480 /agent-note-direct-deepseek-search-and-fetch-apis/decision/default-migration: - en: cb2f0910955b6730 - zh: 7df057048acd7858 + en: 9b1e46885451ada3 + zh: 0deab76a188294dd /agent-note-direct-deepseek-search-and-fetch-apis/decision/legacy-messages-search: en: 0dcc97d8105fab60 zh: d80d40ae3a0c601d /agent-note-direct-deepseek-search-and-fetch-apis/alternatives-considered: - en: e377ad3c0327300e - zh: 4b9f7f83f464e657 + en: da027a3c18b4fa0a + zh: a3f0f448a0cae63f /agent-note-direct-deepseek-search-and-fetch-apis/consequences: en: 7ec21c5b1124e5f8 zh: af769dbdb4face9f diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md index 6b535ace4f..006108d723 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.md @@ -14,7 +14,7 @@ The [DeepSeek Search and Fetch guide](https://api-docs.deepseek.com/zh-cn/guides ### Protocol selection and deployment -The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects the Search API and local HTTP fetch, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential. +The APIs register as `deepseek-search-api` and `deepseek-fetch-api`. Messages search remains separately registered as `deepseek-official`. The web service selects each provider through `web.searchProvider` and `web.fetchProvider`, which the Search and Fetch menus on the Web search and fetch page set independently; the shipped composition selects local HTTP fetch and no search provider, which runs the Search API outside the DeepSeek model routes, as the [selection decision](../architecture/2026-10-29-web-provider-selection.md) records. A saved selection takes effect on the next operation because the web service reads both selections per operation. Each operation resolves one settings snapshot, including its endpoint and credential. Both APIs read the `web-deepseek-api` namespace, and each capability resolves its own endpoint and credential. Direct retrieval appends `/search` or `/fetch` to an API base. A capability without its own YAML endpoint fields uses the origin of the conversation's DeepSeek model route base URL with `/v1/tools`, which for the public deployment is the guide's `https://api.deepseek.com/v1/tools`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that derivation and the credential each operation sends. The verified development base is `http://api-dev.deepseek.com:8031/api/v1/tools`; its prefix differs and is never inferred from the hostname, so such a deployment sets the complete base in `searchBaseURL` or `fetchBaseURL`. An unparseable base leaves that capability's provider unavailable. @@ -36,7 +36,7 @@ The HTTP provider retains its own URL validation and resource limits. Selecting ### Default migration -The shipped composition selects `deepseek-search-api`; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider. +The shipped composition fixes no search provider: a search runs Messages search for a model request on a DeepSeek model route and `deepseek-search-api` on every other route; the [selection decision](../architecture/2026-10-29-web-provider-selection.md) owns that default and its no-fallback rule. API keys and account tokens both reach the public routes. Deployments behind a gateway without `/v1/tools` routes set `searchBaseURL` to a base that serves them. A stored `web.searchProvider: deepseek-official` selects Messages search, and any other stored selection keeps its provider. ### Legacy Messages search @@ -48,7 +48,7 @@ The independent `dsh-web-search-deepseek` provider sends Messages search request **Reuse the Messages address or infer a route prefix.** The protocols and deployed prefixes differ. Separate bases preserve existing configurations and avoid sending a valid request to the wrong route. -**Require an explicit Search API base.** The Search API is the shipped search default, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base. +**Require an explicit Search API base.** The Search API is the shipped search default outside the DeepSeek model routes, and an empty default would leave it unavailable until every user enters an address that the DeepSeek model route already determines. Other deployments still set their own base. **Keep the APIs inside the Messages provider behind a provider-local switch.** A switch inside the Messages provider cannot change fetch routing, so `web_fetch` would stay on HTTP unless the user also edited `web.fetchProvider`; it also ties the APIs' lifecycle to Messages search. Separate registrations let the web service's existing selection choose each provider, without coupling either API to the Messages provider. diff --git a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md index 622195c6b6..94f06be951 100644 --- a/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md +++ b/.agents/notes/implemented/feature/2026-10-15-deepseek-search-fetch-api.zh.md @@ -14,7 +14,7 @@ Status: implemented ### 协议选择与部署 -两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择 Search API 与本地 HTTP 抓取,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。 +两个 API 注册为 `deepseek-search-api` 和 `deepseek-fetch-api`;Messages 搜索仍独立注册为 `deepseek-official`。Web 服务通过 `web.searchProvider` 和 `web.fetchProvider` 选择各个提供方,「网页搜索与获取」页上的 Search 和 Fetch 下拉框分别设置这两项;内置组合选择本地 HTTP 抓取,不选择搜索提供方,此时 DeepSeek 模型路由之外的搜索使用 Search API,见[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)。已保存的选择从下一次操作起生效,因为 Web 服务在每次操作时读取两项选择。每次操作解析一份包含端点和凭据的设置快照。两个 API 读取 `web-deepseek-api` namespace,每个能力各自解析端点与凭据。 直接检索在 API 基础地址后追加 `/search` 或 `/fetch`。没有在 YAML 中单独设置端点字段的能力,使用会话的 DeepSeek 模型路由基础地址的 origin 加 `/v1/tools`,公网部署即指南中的 `https://api.deepseek.com/v1/tools`;该推导及每次操作发送的凭据由[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责。已验证的开发地址为 `http://api-dev.deepseek.com:8031/api/v1/tools`;其前缀不同,程序不会根据主机名推断,此类部署需在 `searchBaseURL` 或 `fetchBaseURL` 中填写完整基础地址。基础地址无法解析时,该能力的提供方不可用。 @@ -36,7 +36,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek ### 默认值迁移 -内置组合选择 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。 +内置组合不固定搜索提供方:为 DeepSeek 模型路由上的模型请求发起的搜索运行 Messages 搜索,其他路由上的搜索运行 `deepseek-search-api`;[选择决策](../architecture/2026-10-29-web-provider-selection.zh.md)负责这项默认值及其不回退规则。API 密钥和账号 token 都能访问公网路由。位于没有 `/v1/tools` 路由的网关之后的部署,需把 `searchBaseURL` 设为提供这些路由的基础地址。已保存的 `web.searchProvider: deepseek-official` 会选中 Messages 搜索,其他已保存的选择保持其提供方。 ### 旧版 Messages 搜索 @@ -48,7 +48,7 @@ HTTP 提供方继续负责自身的 URL 校验和资源限制。选择 DeepSeek **复用 Messages 地址或推断路由前缀。** 协议与部署前缀不同。分别保存基础地址可保留现有配置,避免把有效请求发往错误路由。 -**要求显式填写 Search API 基础地址。** Search API 是内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。 +**要求显式填写 Search API 基础地址。** Search API 是 DeepSeek 模型路由之外内置的搜索默认值,空默认值会让它在每位用户填写一个 DeepSeek 模型路由已经确定的地址之前都不可用。其他部署仍可设置自己的基础地址。 **把两个 API 放在 Messages 提供方内部,由提供方自己的开关切换。** Messages 提供方内的开关无法改变抓取路由,因此除非用户另外修改 `web.fetchProvider`,`web_fetch` 仍会走 HTTP;它还会把两个 API 的生命周期绑在 Messages 搜索上。独立注册让 Web 服务通过现有的提供方选择机制选择各个提供方,不会把任一 API 与 Messages 提供方绑定。 diff --git a/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.i18n.yaml b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.i18n.yaml new file mode 100644 index 0000000000..0fb681452f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-09-sdk-prompt-time-zone.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-11-09-sdk-prompt-time-zone.md +/agent-note-per-prompt-sdk-time-zone: + en: 44d838b330c01b71 + zh: 322844db122f305f +/agent-note-per-prompt-sdk-time-zone/problem: + en: 225547dcc5d63b6e + zh: b62fa355a827d662 +/agent-note-per-prompt-sdk-time-zone/decision: + en: be0afd0975a15d3a + zh: 91f161bc2f7cd938 +/agent-note-per-prompt-sdk-time-zone/alternatives-considered: + en: b67b2d44aeb2dc6b + zh: 69d0356bfe3204a6 +/agent-note-per-prompt-sdk-time-zone/consequences: + en: ec0b5f4a68aaa351 + zh: 4eb09ed822f456a2 diff --git a/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.md b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.md new file mode 100644 index 0000000000..6d8a423f13 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.md @@ -0,0 +1,35 @@ +# Agent Note: Per-prompt SDK time zone + +Status: implemented + +English | [中文](2026-11-09-sdk-prompt-time-zone.zh.md) + +## Problem + +Web and Desktop prompts carry the browser zone that the Host canonicalizes and records on that user message, and [time-context](../../../../packages/context/time-context/README.md) tells the model to interpret unqualified dates and times in it. SDK prompts recorded `{ kind: 'user' }`, and time-context read a zone only from a user source that also had a Web `rpcId`. Every SDK request therefore showed `Browser time zone for this request: unavailable.`, and the model asked about dates that a Web user would never be asked about. The SDK protocol had no field through which an embedding application could report its user's zone. + +## Decision + +The zone stays request-local message source data, as in the [explicit Schedule time-zone decision](../simplification/2026-08-09-explicit-schedule-time-zone.md); the SDK supplies it per prompt. + +- `session/prompt` and `session/query` accept an optional `timeZone`. The TypeScript client accepts it in `HarnessClient.prompt()` options and `run()` options; the Python client accepts the `time_zone` keyword in `session_prompt()` and `run()`. +- The SDK server canonicalizes an explicit value with `canonicalClientTimeZone`, the check the Web Host uses. A rejected value fails that request with a `TypeError`, answered as JSON-RPC `-32603` like the server's other parameter errors, before a Session is created or input is routed. +- An omitted value samples `Intl.DateTimeFormat().resolvedOptions().timeZone` when each prompt is accepted. A sampled value that does not canonicalize, such as `+00:00` under `TZ=GMT` or `Etc/Unknown`, records no zone and does not fail the prompt. +- The prompt records the `sdk-user` message source `{ kind: 'user', clientTimeZone? }` without `rpcId`. The `rpcId` identifies a Web submission for prompt acknowledgement and attachment reclamation, which the SDK does not have. +- `reportedBrowserTimeZone` reads a string `clientTimeZone` from any `user` source. Writers canonicalize before commit, and request preparation still refuses a noncanonical value, so the Web path and the model-visible text stay unchanged. +- Native commands record no zone. Web executes slash commands through `commands.execute` without `clientTimeZone`, and SDK `session/query` routes commands to the same handlers, so `/plan ` steers a zone-less message on both paths. + +## Alternatives considered + +**Inject one runtime-wide zone into every request.** A process or configuration zone applied by time-context would also cover in-process children and plugin messages, but it would present a deployment fact as user authority. The time-context fallback display zone already exists and deliberately keeps the `unavailable` policy. + +**Write a synthetic `rpcId` on SDK prompts.** This reuses the Web source variant unchanged, but Web clients use `rpcId` to settle submissions and reclaim attachments, so a synthetic identity would claim a Web submission that never existed. + +**Fix the zone at `initialize`.** One value per connection saves a field per prompt, but a long-lived runtime can serve users in different zones and a process zone can change, so the value would become stale. A per-prompt value matches the Web browser sample. + +## Consequences + +- SDK embeddings that pass no zone now report the runtime process zone. In a container this is usually `UTC`, which may differ from the user's zone; the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md) tells consumers to pass `timeZone` or `time_zone`, or to set `TZ`. +- SDK subagent children receive prompts without a zone, so they report their own process zone; in-process children see `unavailable`, as on Web. +- A reader that predates the relaxed check ignores an SDK prompt zone; the [persistence record](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md) keeps the format version. +- `packages/sdk/server/tests/time-zone.spec.ts` pins canonical, rejected, sampled, and unusable zones, the `session/query` route, and matching `/plan` sources on the SDK and native command paths. `apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` asserts the model-visible line through the shipped `sdk` profile. The SDK snapshot driver sends `timeZone: 'UTC'` and runs with `TZ=UTC`. diff --git a/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.zh.md b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.zh.md new file mode 100644 index 0000000000..eaedf2cb51 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-09-sdk-prompt-time-zone.zh.md @@ -0,0 +1,35 @@ +# Agent Note:SDK prompt 逐条上报时区 + +Status: implemented + +[English](2026-11-09-sdk-prompt-time-zone.md) | 中文 + +## 问题 + +Web 与 Desktop 的 prompt 携带浏览器时区,Host 规范化后把它记录在该条用户消息上,[time-context](../../../../packages/context/time-context/README.zh.md) 随后让模型按该时区解释未限定时区的日期与时间。SDK prompt 记录的是 `{ kind: 'user' }`,而 time-context 只从同时带有 Web `rpcId` 的 user 来源读取时区。因此每个 SDK 请求都显示 `Browser time zone for this request: unavailable.`,模型会就 Web 用户从不会被追问的日期去询问用户。SDK 协议也没有字段让嵌入方应用上报其用户的时区。 + +## 决定 + +时区仍是请求本地的消息来源数据,与[显式定时任务时区决定](../simplification/2026-08-09-explicit-schedule-time-zone.zh.md)一致;SDK 逐条 prompt 提供它。 + +- `session/prompt` 与 `session/query` 接受可选的 `timeZone`。TypeScript 客户端在 `HarnessClient.prompt()` 选项和 `run()` 选项中接受它;Python 客户端在 `session_prompt()` 和 `run()` 中接受 `time_zone` 关键字参数。 +- SDK server 用 Web Host 所用的同一检查 `canonicalClientTimeZone` 规范化显式值。被拒的值让该请求以 `TypeError` 失败,与 server 的其他参数错误一样应答为 JSON-RPC `-32603`,发生在创建 Session 或路由输入之前。 +- 省略时,在接受每条 prompt 时采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。采样值无法规范化时(例如 `TZ=GMT` 下的 `+00:00` 或 `Etc/Unknown`),不记录时区,也不让 prompt 失败。 +- prompt 记录不带 `rpcId` 的 `sdk-user` 消息来源 `{ kind: 'user', clientTimeZone? }`。`rpcId` 标识一次 Web 提交,用于 prompt 确认和附件回收,SDK 没有这样的提交。 +- `reportedBrowserTimeZone` 从任何 `user` 来源读取字符串 `clientTimeZone`。写入方在提交前规范化,请求准备阶段仍拒绝非规范值,因此 Web 路径和模型可见文本都不变。 +- 原生命令不记录时区。Web 通过 `commands.execute` 执行 slash 命令且不带 `clientTimeZone`,SDK `session/query` 把命令路由到同一批 handler,因此两条路径上的 `/plan ` 都 steer 一条不带时区的消息。 + +## 备选方案 + +**向每个请求注入一个运行时级时区。** 由 time-context 应用的进程或配置时区也能覆盖进程内子 agent 与插件消息,但它会把部署事实当作用户依据呈现。time-context 已有回退显示时区,并且有意保留 `unavailable` 策略。 + +**在 SDK prompt 上写入合成的 `rpcId`。** 这样可以原样复用 Web 来源变体,但 Web 客户端用 `rpcId` 结算提交并回收附件,合成标识会声称存在一次从未发生的 Web 提交。 + +**在 `initialize` 时固定时区。** 每个连接一个值可以省去每条 prompt 的字段,但长期运行的运行时可能服务不同时区的用户,进程时区也可能变化,该值会过时。逐条 prompt 的值与 Web 浏览器采样一致。 + +## 影响 + +- 不传时区的 SDK 嵌入方现在上报运行时进程时区。容器中通常是 `UTC`,可能与用户时区不同;[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md)要求使用方传入 `timeZone` 或 `time_zone`,或设置 `TZ`。 +- SDK subagent 子运行时收到的 prompt 不带时区,因此上报自身进程时区;进程内子 agent 与 Web 上一样看到 `unavailable`。 +- 早于放宽检查的读取方会忽略 SDK prompt 的时区;[持久化记录](../../../../docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.zh.md)保持格式版本不变。 +- `packages/sdk/server/tests/time-zone.spec.ts` 固定规范化、拒绝、采样与不可用时区,`session/query` 路由,以及 SDK 与原生命令路径上一致的 `/plan` 来源。`apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts` 通过随发行版交付的 `sdk` profile 断言模型可见的那一行。SDK snapshot 驱动发送 `timeZone: 'UTC'` 并在 `TZ=UTC` 下运行。 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml new file mode 100644 index 0000000000..ea1862a84e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-11-forge-review-page.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-11-11-forge-review-page.md +/agent-note-code-review-page: + en: 88e0f71d0da6eda5 + zh: ff17f12fd505c772 +/agent-note-code-review-page/problem: + en: ad1da0c97cfc9c2d + zh: f4420c0b004fd189 +/agent-note-code-review-page/decision: + en: b0ba35d7c5818dc3 + zh: 5414ec6190be0726 +/agent-note-code-review-page/alternatives-considered: + en: 963b1be39a0e4bac + zh: 940b86a5e2036477 +/agent-note-code-review-page/consequences: + en: c17a96adbec69d92 + zh: 06b5f2c28a9ec331 diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md new file mode 100644 index 0000000000..205baefe8f --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.md @@ -0,0 +1,31 @@ +# Agent Note: Code review page + +Status: implemented + +English | [中文](2026-11-11-forge-review-page.zh.md) + +## Problem + +The [forge panel](2026-10-09-forge-panel.md) shows the change requests one Session created or pushed. A reviewer also needs the change requests that ask for their review, that they created, or that involve them, read and reviewed without first finding or creating the Session that owns them, and a conversation with the Agent about one of them that does not mix into an unrelated existing conversation. + +## Decision + +A left-navigation Code review page in [`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.md) lists three viewer lists and shows one change request in full. + +- **Lists** — an optional `ForgeProvider` capability (`viewer`, `listForViewer`, `countForViewer`) returns summaries of open change requests; GitHub answers each list with one GraphQL search, because one document with several searches times out. The Host reads the lists only while a page or count stream lasts, outside the forge's status polling, since a batch snapshot of dozens of change requests exceeds GitHub's query timeout; only the shown change request is polled through `ForgeService.watch`. +- **Reads by URL** — the page's `forgePanel/review*` methods name a change request by URL and no Session; they share the Session-bound methods' implementation and are reachable only by callers that may use the Host's code host credentials. +- **Description** — `readDescription` returns the Markdown body, labels, and signed addresses for private attachments, which the page substitutes before rendering with HTML omitted. +- **Changes** — the page draws the changes view itself, split from the right-sidebar tab, with a panel state that holds only the shown change request; plugin lenses, annotations, and slots stay with the Session tab, whose extension points name a Session. +- **Chat** — the chat tab embeds `conversation.content` for the blank Session `connectWorkspace` resolves in the Workspace named like the repository, and never offers an existing conversation. A Workspace picked in the Hero is handled by the page, as every owner of the content handles its own picks: the page connects that Workspace's blank and shows it in the chat tab, where the main Conversation opens it as the main Session. The change request is bound when the Session's first message enters its inbox, so a blank that is never used stays unbound. +- **Hosts** — the page lists every configured host together; choosing among hosts and accounts waits for a second provider that lists change requests. + +## Alternatives considered + +- **A Session per change request for reading** — rejected: reading the description or the diff would create Sessions nobody converses in, and bind them. +- **Reviewing in an existing conversation** — rejected by the user: the conversation's context would mix with the review. +- **Listing through the status poller** — rejected: the batch snapshot query times out at the list sizes a reviewer has. +- **Binding when the chat opens** — rejected: the blank Session is shared with New Session, so it would carry the binding into an unrelated conversation. + +## Consequences + +The forge registry gains a fifth optional capability family and a `rate-limited` failure code, recorded in the [upgrade guide](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md). A Host restart before the chat's first message forgets the staged binding. diff --git a/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md new file mode 100644 index 0000000000..3c342919a6 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-11-forge-review-page.zh.md @@ -0,0 +1,31 @@ +# Agent Note: 代码评审页 + +Status: implemented + +[English](2026-11-11-forge-review-page.md) | 中文 + +## Problem + +[forge 面板](2026-10-09-forge-panel.zh.md)显示一个会话创建或推送的变更请求。评审者还需要请自己评审的、自己创建的以及与自己有关的变更请求,不必先找到或创建拥有它们的会话就能阅读和评审;也需要就其中一个与 Agent 对话,而且这段对话不能混进无关的已有对话。 + +## Decision + +[`dsh-experimental-client-ui-forge`](../../../../packages/experimental/client-ui-forge/README.zh.md) 在左侧导航中加入“代码评审”页,列出三个登录用户列表,并完整显示一个变更请求。 + +- **列表**——可选的 `ForgeProvider` 能力(`viewer`、`listForViewer`、`countForViewer`)返回未关闭变更请求的摘要;GitHub 每个列表用一次 GraphQL 搜索回答,因为在一个文档中放多个搜索会超时。Host 只在页面流或计数流存在时读取列表,不经过 forge 的状态轮询,因为几十个变更请求的批量快照会超过 GitHub 的查询时限;只有显示中的变更请求经 `ForgeService.watch` 轮询。 +- **按 URL 读取**——页面的 `forgePanel/review*` 方法以 URL 而不是会话指定变更请求;它们与会话绑定的方法共用实现,只有可以使用 Host 代码托管凭据的调用方能访问。 +- **描述**——`readDescription` 返回 Markdown 正文、标签以及私有附件的签名地址,页面替换这些地址后以省略 HTML 的方式渲染。 +- **变更**——页面自己绘制变更视图(从右侧栏标签中拆出),面板状态只含显示中的变更请求;插件的透镜、行注释和插槽仍只在会话标签中,因为这些扩展点以会话为对象。 +- **对话**——对话标签为 `connectWorkspace` 在与仓库同名的工作区中解析出的空白会话嵌入 `conversation.content`,从不提供已有对话。在 Hero 中选择工作区由页面自己处理,这与内容的每个属主处理各自的选择一致:页面连接该工作区的空白会话并在对话标签中显示它,而主 Conversation 会把它打开为主会话。该会话的首条消息进入收件箱时才绑定变更请求,因此从未使用的空白会话保持未绑定。 +- **主机**——页面把所有已配置的主机合并列出;在主机与账号之间选择要等到第二个能列出变更请求的提供方。 + +## Alternatives considered + +- **每个变更请求用一个会话来阅读**——否决:阅读描述或 diff 会创建无人对话的会话并绑定它们。 +- **在已有对话中评审**——用户否决:对话上下文会与评审混在一起。 +- **经状态轮询列出**——否决:在评审者常见的列表规模下,批量快照查询会超时。 +- **打开对话时就绑定**——否决:空白会话与“新会话”共用,会把绑定带进无关的对话。 + +## Consequences + +forge 注册表增加第五组可选能力和 `rate-limited` 失败码,记录在[升级指南](../../../../docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md)中。在对话的首条消息之前重启 Host 会丢失暂存的绑定。 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 970eaf9557..1472ca2a1e 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: 0f3e0daee65b6510 - zh: 2e9c8000da75fb6c + en: e4ecfa61b6f71d8c + zh: a33d16e5843cf097 /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 aaa055f7b5..179bb4b807 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 @@ -10,7 +10,7 @@ The Web plugin page manages only the bundles a person installed into the profile ## Decision -The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. The [persistent-terminal bundle](../../../../packages/experimental/terminal-bundle/README.md) remains available to the Host but has no page switch, even when enabled; its existing profile selection remains intact. +The launcher names in `OPTIONAL_BUNDLES` (`packages/util/official-bundles/src/bundles.ts`, beside the profile templates) the bundles the installation ships for a person to switch on. Each must be a runtime dependency of `apps/cli` that declares `dsh.bundle.patch`, and no shipped profile template selects it. The plugin manager's `listBundles` reports such a bundle as `optional`: switched off until selected, never removable, resolved from the installation like any installation-supplied bundle. The Web plugin page presents offered optional bundles in its Official group, tagged experimental when the package is experimental, ahead of the profile's own installed bundles. 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. 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 6135f08763..0f184372ef 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 @@ -10,7 +10,7 @@ Web 插件页只管理用户装进 profile 的组合包。像 Agent Teams 这样 ## 决策 -启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。[持久终端组合包](../../../../packages/experimental/terminal-bundle/README.zh.md)仍可供 Host 使用,但即使已启用也不提供页面开关;已有的 profile 选择保持不变。 +启动器在 `OPTIONAL_BUNDLES`(`packages/util/official-bundles/src/bundles.ts`,与 profile 模板并列)里点名安装随附、供用户开启的组合包。每一个都必须是 `apps/cli` 声明了 `dsh.bundle.patch` 的运行时依赖,且不被任何随附 profile 模板选中。插件管理器的 `listBundles` 把这类组合包报告为 `optional`:选中前保持关闭、永不可卸载、像其他安装提供的组合包一样从安装目录解析。Web 插件页在「官方」分组展示可供选择的可选组合包,属于实验包的带实验性标签,排在 profile 自己已安装的组合包之前。 默认产品隔离的规则保持不变,只声明一个例外:可选组合包的依赖图在默认产品之外。静态门禁跳过从 `@deepseek-ai/dsh` 到列表中组合包的 `dependencies` 边,仍然拒绝运行时 import、随附组合、preset 或默认模板对它的引用,拒绝列表没有点名的实验依赖,也拒绝不是运行时依赖或不是组合包的列表项。workspace 约束检查接受同样的 `dependencies` 边而不接受其他运行时依赖段;发布时的 packed-install 检查对已安装入口包跳过这些边,并要求列表中的每个组合包都已安装。 diff --git a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.i18n.yaml b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.i18n.yaml index acb0275dcc..167b8a16e3 100644 --- a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.i18n.yaml +++ b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.i18n.yaml @@ -9,8 +9,8 @@ en: 4a7e52f6a16dec96 zh: d558db30801355d9 /agent-note-explicit-schedule-time-zone-boundary/decision: - en: 6f233286c95b5294 - zh: 5a1f4ba6f5ccbd36 + en: ab632daa5d687c77 + zh: b406216a5b35e5ac /agent-note-explicit-schedule-time-zone-boundary/alternatives-considered: en: 982fe0b8d24a66ce zh: e6dceee1ce776d21 @@ -18,5 +18,5 @@ en: 56dcb44f09be3713 zh: 59a6814a662458ad /agent-note-explicit-schedule-time-zone-boundary/consequences: - en: d9358667c58662e4 - zh: d536bb0fccd9f0a9 + en: 43980cd5ebdf6685 + zh: ed3051f8eb45ead4 diff --git a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.md b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.md index 2f23394e65..f85af8125a 100644 --- a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.md +++ b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.md @@ -12,9 +12,9 @@ Most of that complexity sat outside Schedule. The model already interprets natur ## Decision -The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it. +The browser zone is request-local source data. The Web client samples `Intl.DateTimeFormat().resolvedOptions().timeZone` for every prompt. The Host accepts an optional `clientTimeZone`, validates and canonicalizes `UTC` or an IANA Area/Location at the RPC boundary, and logs it on that exact `user-rpc` message. Invalid values reject prompt admission. Non-browser clients may omit it; SDK prompts report an explicit or sampled process zone on an `sdk-user` source without `rpcId`, as recorded in [per-prompt SDK time zone](../feature/2026-11-09-sdk-prompt-time-zone.md). -Time-context derives unique, mixed, or missing browser facts from original user-rpc messages in the open turn. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority. +Time-context derives unique, mixed, or missing browser facts from original user messages in the open turn that carry `clientTimeZone`. A unique zone formats the clock and tells the model to interpret otherwise-unqualified dates and times in that zone. Mixed or missing browser-zone records tell the model to ask the user. The configured or process zone is only a display fallback and is never presented as user authority. Schedule accepts no implicit local zone. `at` is either a strict offset-bearing RFC 3339 string or exact `{ date, time, time_zone }`. The structured form requires its zone even when time-context just showed the model a browser zone. Schedule does not import time-context, inspect user-message sources, read a Session header, or produce a confirmation error. Its parser validates the explicit value, rejects daylight-saving gaps, chooses the first instant in overlaps, and stores only canonical UTC `scheduledAt`. @@ -43,5 +43,5 @@ Source audits reject `SessionHeader.timeZone`, persistence `time_zone` columns, - Browser-local natural language works without a persisted Session-zone subsystem. - Schedule has one explicit, independently testable absolute-time boundary. - Travel and concurrent tabs affect only their own prompts; a turn with mixed browser-zone records asks instead of mutating shared state. -- Non-browser clients remain valid but must provide enough natural-language context or explicit tool arguments. +- Non-browser clients without a reported zone remain valid but must provide enough natural-language context or explicit tool arguments. - The model may still make an interpretation error; the tool guarantees only that the explicit calendar value is valid and deterministic. diff --git a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.zh.md b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.zh.md index aafa5d5685..b18c31542a 100644 --- a/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.zh.md +++ b/.agents/notes/implemented/simplification/2026-08-09-explicit-schedule-time-zone.zh.md @@ -12,9 +12,9 @@ Status: implemented ## 决策 -浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它。 +浏览器时区是请求本地的来源数据。Web client 会为每条提示词采样 `Intl.DateTimeFormat().resolvedOptions().timeZone`。Host 接受可选的 `clientTimeZone`,在 RPC 边界校验并规范化 `UTC` 或 IANA Area/Location,再将其记录在确切的那条 `user-rpc` 消息上。无效值会使提示词准入被拒绝。非浏览器 client 可以省略它;SDK prompt 在不带 `rpcId` 的 `sdk-user` 来源上上报显式或采样的进程时区,见 [SDK prompt 逐条上报时区](../feature/2026-11-09-sdk-prompt-time-zone.zh.md)。 -Time-context 从 open turn 中的原始 user-rpc 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。 +Time-context 从 open turn 中带 `clientTimeZone` 的原始 user 消息派生唯一、混合或缺失的浏览器事实。唯一时区会用于格式化时钟,并告诉模型把未明确限定时区的日期和时间解释为该时区。浏览器时区记录混合或缺失时,模型会被告知询问用户。配置或进程时区只作为显示 fallback,绝不会被呈现为用户权威。 Schedule 不接受隐式本地时区。`at` 要么是带显式偏移量且严格符合 RFC 3339 的字符串,要么是精确的 `{ date, time, time_zone }`。即使 time-context 刚向模型展示了浏览器时区,结构化形式仍要求自己的时区。Schedule 不导入 time-context、不检查 user message 来源、不读取 Session header,也不产生确认错误。它的 parser 会校验显式值、拒绝夏令时缺口、在重叠时选择第一个时点,并且只存储规范化后的 UTC `scheduledAt`。 @@ -43,5 +43,5 @@ Host 测试固定别名的规范化、可省略行为和进入 Agent(智能体 - 无需持久 Session 时区子系统,浏览器本地自然语言也能工作。 - Schedule 具有一个显式且可独立测试的绝对时间边界。 - 旅行与并发 tab 只影响各自的提示词;浏览器时区记录混合的 turn 会询问用户,而不是改变共享状态。 -- 非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。 +- 未上报时区的非浏览器 client 仍然有效,但必须提供足够的自然语言上下文或显式工具参数。 - 模型仍可能产生解释错误;工具只保证显式日历值有效且具有确定性。 diff --git a/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.i18n.yaml b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.i18n.yaml new file mode 100644 index 0000000000..30c52606b6 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-18-tool-reachability-and-initial-disclosure.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/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md +/agent-note-tool-reachability-and-initial-disclosure: + en: 702b42d555430e20 + zh: d94f3adf52d9d7cb +/agent-note-tool-reachability-and-initial-disclosure/problem: + en: 006eb992e4c0dd4d + zh: 530d13e4f832653b +/agent-note-tool-reachability-and-initial-disclosure/proposal: + en: 86ededd59a892229 + zh: 1ed3ac1f5b160f9d +/agent-note-tool-reachability-and-initial-disclosure/proposal/reachability: + en: 7e8256e97b924e34 + zh: be334f4469d0b5e1 +/agent-note-tool-reachability-and-initial-disclosure/proposal/initial-disclosure: + en: 1c2466dff8ba70e1 + zh: d0e2c35a0e74008f +/agent-note-tool-reachability-and-initial-disclosure/alternatives-considered: + en: 27bff0dbad805d7a + zh: be5b8d1746b5bc02 +/agent-note-tool-reachability-and-initial-disclosure/acceptance-criteria: + en: 099ebf6f7c753286 + zh: 50e29d2522d7fee9 +/agent-note-tool-reachability-and-initial-disclosure/risks: + en: 9366e2866f4b2555 + zh: 5d7b94bb85019f58 diff --git a/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md new file mode 100644 index 0000000000..9b22f0a939 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.md @@ -0,0 +1,50 @@ +# Agent Note: Tool reachability and initial disclosure + +Status: proposed + +English | [中文](2026-11-18-tool-reachability-and-initial-disclosure.zh.md) + +## Problem + +Both executors disclose every reachable tool in full at every step: `tool-executor-native` through the request `tools` field, `tool-executor-ptc` through the `tools:sdk` section. No per-tool statement exists for how the model may call a tool and how much it receives before any discovery; `ToolSchema.deferLoading` names one provider mechanism instead. + +## Proposal + +Describe every reachable tool with two model-facing dimensions, defined by what the model receives, not by what the host or provider transmits. + +### Reachability + +| Value | Meaning | +|---|---| +| `native` | Callable only as a provider tool call. | +| `program` | Callable only from inside a `run_code` program. | +| `both` | Callable either way. | + +Authorization is separate: a tool removed by `restrict()` or an inactive `when` condition is absent from this model; a guard denies one execution and changes neither dimension. + +### Initial disclosure + +| Value | What the model receives before any discovery | +|---|---| +| `none` | Nothing about this tool. | +| `name` | The tool name. | +| `summary` | A description without parameters; may be given per namespace. | +| `full` | Name, description, parameters, and for `program` reachability the return type. | + +Every reachable tool is searchable; `none` only means absent from the initial disclosure. + +## Alternatives considered + +**A visibility axis of `invisible`, `discoverable`, `injected`, `system prompt`.** `injected` is the state a tool enters after a search hit, `system prompt` is a channel, and no name-only level exists; the axis mixed policy, state, and channel. + +**A `discoverable` boolean.** Every case that seemed to need an unsearchable tool is authorization, search ranking, an alias, or a runtime builtin that is not a tool; omitting a schema is not enforcement ([packages/AGENTS.md](../../../../packages/AGENTS.md)). + +## Acceptance criteria + +- Each registered tool resolves to one value per dimension per step, and both executors read the same resolution. +- A `none` tool is found through `tool_search` and then called under each executor in a recorded snapshot; a `native` activation projects through [active tool headers](../../implemented/architecture/2026-09-20-dynamic-tool-updates.md). + +## Risks + +- Discovery adds a model round trip, and search quality depends on tool names and descriptions. +- Per-step recomputation moves tools between values and changes the declaration prefix the cache relies on. diff --git a/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.zh.md b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.zh.md new file mode 100644 index 0000000000..0cfd0ae530 --- /dev/null +++ b/.agents/notes/proposed/architecture/2026-11-18-tool-reachability-and-initial-disclosure.zh.md @@ -0,0 +1,50 @@ +# Agent Note: 工具可达性与初始披露 + +Status: proposed + +[English](2026-11-18-tool-reachability-and-initial-disclosure.md) | 中文 + +## Problem + +两个执行器在每个步骤都完整披露每个可达工具:`tool-executor-native` 通过请求的 `tools` 字段,`tool-executor-ptc` 通过 `tools:sdk` 章节。没有任何按工具的说明能表达模型可以如何调用某个工具,以及在任何发现之前它能收到多少内容;`ToolSchema.deferLoading` 只是以某一个提供方机制命名。 + +## Proposal + +用两个面向模型的维度描述每个可达工具,两者都由模型收到的内容定义,而不是由宿主或提供方传输的内容定义。 + +### 可达性 + +| 取值 | 含义 | +|---|---| +| `native` | 只能作为提供方工具调用来调用。 | +| `program` | 只能在 `run_code` 程序内部调用。 | +| `both` | 两种方式都可调用。 | + +授权是独立的:被 `restrict()` 移除或因 `when` 条件未激活而移除的工具不在此模型之内;guard 拒绝的是一次执行,不改变任何一个维度。 + +### 初始披露 + +| 取值 | 模型在任何发现之前收到的内容 | +|---|---| +| `none` | 关于该工具的任何内容都没有。 | +| `name` | 工具名称。 | +| `summary` | 不含参数的描述;可以按命名空间给出。 | +| `full` | 名称、描述、参数,以及 `program` 可达性下的返回类型。 | + +每个可达工具都可被搜索;`none` 只表示不在初始披露中。 + +## Alternatives considered + +**一个由 `invisible`、`discoverable`、`injected`、`system prompt` 构成的可见性轴。** `injected` 是工具在搜索命中后进入的状态,`system prompt` 是通道,且不存在仅名称级别;该轴混合了策略、状态和通道。 + +**一个 `discoverable` 布尔值。** 每个看似需要不可搜索工具的情形都是授权、搜索排序、别名或不是工具的运行时内建函数;省略 schema 不是强制手段([packages/AGENTS.md](../../../../packages/AGENTS.md))。 + +## Acceptance criteria + +- 每个已注册工具在每个步骤为每个维度解析出一个取值,两个执行器读取同一次解析。 +- 在录制快照中,一个 `none` 工具在每个执行器下都通过 `tool_search` 被找到并随后被调用;`native` 激活按[活跃工具请求头](../../implemented/architecture/2026-09-20-dynamic-tool-updates.zh.md)投影。 + +## Risks + +- 发现增加一次模型往返,且搜索质量取决于工具名称和描述。 +- 按步骤重新计算会在取值之间移动工具,并改变缓存所依赖的声明前缀。 diff --git a/.gitignore b/.gitignore index 6255c7081b..e3b3ba67b0 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ mise.toml dist-exe/ /dist/ apps/desktop/.desktop-build/ +apps/desktop/.desktop-dev/ python/sdk-runtime/src/deepseek_harness_runtime/runtime/ python/**/__pycache__/ python/**/.pytest_cache/ diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 70a888ec00..c62f97a8c8 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -46,6 +46,7 @@ External packages installed for runtime use or embedded in distributed Host or b | [`@joplin/turndown-plugin-gfm`](https://github.com/laurent22/joplin-turndown-plugin-gfm) | MIT | | [`@jridgewell/gen-mapping`](https://github.com/jridgewell/sourcemaps) | MIT | | [`@js-temporal/polyfill`](https://github.com/js-temporal/temporal-polyfill) | ISC | +| [`@larksuite/cli`](https://github.com/larksuite/cli) | MIT | | [`@lexical/history`](https://github.com/facebook/lexical) | MIT | | [`@lexical/plain-text`](https://github.com/facebook/lexical) | MIT | | [`@lexical/text`](https://github.com/facebook/lexical) | MIT | @@ -69,8 +70,10 @@ External packages installed for runtime use or embedded in distributed Host or b | [`@shikijs/langs`](https://github.com/shikijs/shiki) | MIT | | [`@standard-schema/spec`](https://github.com/standard-schema/standard-schema) | MIT | | [`@tanstack/react-virtual`](https://github.com/TanStack/virtual) | MIT | +| [`@tencentcloud/tmeet`](https://github.com/TencentCloud/tencentmeeting-cli) | MIT | | [`@trycua/cua-driver`](https://github.com/trycua/cua) | MIT | | [`@vscode/ripgrep`](https://github.com/microsoft/vscode-ripgrep) | MIT | +| [`@wecom/cli`](https://github.com/WecomTeam/wecom-cli) | MIT | | [`@xterm/addon-fit`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-fit) | MIT | | [`@xterm/addon-serialize`](https://github.com/xtermjs/xterm.js/tree/master/addons/addon-serialize) | MIT | | [`@xterm/headless`](https://github.com/xtermjs/xterm.js) | MIT | @@ -314,6 +317,7 @@ The [shared runtime lock](scripts/primary-runtime/lock.json) records each distri | [`openpyxl`](https://foss.heptapod.net/openpyxl/openpyxl) | 3.1.5 | MIT | | [`pandas`](https://github.com/pandas-dev/pandas) | 3.0.1 | BSD-3-Clause | | [`pillow`](https://github.com/python-pillow/Pillow) | 12.3.0 | MIT-CMU | +| [`pypdf`](https://github.com/py-pdf/pypdf) | 6.21.4 | BSD-3-Clause | | [`python-dateutil`](https://github.com/dateutil/dateutil) | 2.9.0.post0 | Apache-2.0 OR BSD-3-Clause | | [`python-docx`](https://github.com/python-openxml/python-docx) | 1.2.0 | MIT | | [`python-pptx`](https://github.com/scanny/python-pptx) | 1.0.2 | MIT | diff --git a/apps/cli/package.json b/apps/cli/package.json index 9656f7c1a2..d44314dc46 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh", "description": "dsh CLI: profile launch, plugin management, and configuration inspection", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index ea7301ee1b..cfc0807110 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -13,9 +13,9 @@ Setup and discovery: - cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp. - cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches. - cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app. +- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading accessibility state or activating the app. - app.getWindows() -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them. +- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading accessibility state. Providers reject closed or foreign windows when operating on them. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -23,9 +23,10 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current accessibility snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. +- getActionSchema(action: string) -> JSON Schema — query the parameter schema for an action. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. - setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. @@ -43,7 +44,7 @@ Use an explicit window for pointer input. Before coordinate input, including rel - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current accessibility observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts index 3b0bc2fa65..6ac211dbfc 100644 --- a/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts +++ b/apps/cli/tests/profiles/sdk/keyless-smoke.e2e.ts @@ -486,6 +486,87 @@ describe('Python SDK dsh profile keyless smoke', () => { } }, 30_000) + // TZ belongs to the spawned runtime only; GMT makes ICU report "+00:00", which is not a usable zone name. + it.each([ + { tz: 'America/New_York', sampled: 'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.' }, + { tz: 'GMT', sampled: 'Browser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.' }, + ])('shows the model the reported or sampled prompt time zone (TZ=$tz)', async ({ tz, sampled }) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-sdk-time-zone-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const modelRequests: string[] = [] + const modelServer = createServer((request, response) => { + let body = '' + request.setEncoding('utf8') + request.on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + modelRequests.push(body) + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(messagesResponse({ type: 'text', text: 'done' }, 'end_turn')) + }) + }) + onTestFinished(() => new Promise((resolve) => { modelServer.close(() => { resolve() }) })) + await new Promise(resolve => modelServer.listen(0, '127.0.0.1', resolve)) + const address = modelServer.address() + if (address === null || typeof address === 'string') throw new Error('model server did not bind a TCP port') + const child = execa(launch.command, [...launch.args, '--profile', 'sdk'], { + cwd: repoRoot, + env: { + ...launch.env, + DSH_HOME: join(root, '.dsh'), + DSH_TELEMETRY_DISABLED: '1', + DEEPSEEK_API_KEY: 'keyless-smoke-no-call', + DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}`, + TZ: tz, + }, + timeout: 35_000, + killSignal: 'SIGKILL', + reject: false, + }) + onTestFinished(async () => { child.kill('SIGKILL'); await child }) + const lines: string[] = [] + let stdoutBuffer = '' + let stderr = '' + child.stdout.on('data', (chunk: Buffer) => { + stdoutBuffer += chunk.toString('utf8') + const parts = stdoutBuffer.split('\n') + stdoutBuffer = parts.pop() ?? '' + lines.push(...parts) + }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') }) + const send = (id: number, method: string, params?: object) => { + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`) + return waitForLine(lines, value => value.id === id, () => stderr) + } + const promptRequest = async (id: number, sessionId: string, timeZone?: string): Promise => { + const requests = modelRequests.length + expect(await send(id, 'session/prompt', { + sessionId, contentBlocks: [{ type: 'text', text: 'When is noon tomorrow?' }], ...timeZone === undefined ? {} : { timeZone }, + })).toHaveProperty('result.messageId') + await waitForLine(lines, (value) => { + const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined + return value.method === 'session.event' && params?.sessionId === sessionId && params.event?.type === 'turn/end' + }, () => stderr) + expect(modelRequests).toHaveLength(requests + 1) + return modelRequests.at(-1)! + } + + await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' }) + expect(await promptRequest(2, 'explicit', 'US/Eastern')).toContain( + 'Browser time zone for this request: America/New_York. Interpret otherwise-unqualified dates and times in this zone.', + ) + expect(await promptRequest(3, 'sampled')).toContain(sampled) + expect(await send(4, 'session/prompt', { + sessionId: 'invalid', contentBlocks: [{ type: 'text', text: 'When is noon?' }], timeZone: 'CST', + })).toMatchObject({ + error: { code: -32603, message: 'timeZone must be UTC or a valid IANA Area/Location name: "CST"' }, + }) + expect(modelRequests).toHaveLength(2) + + await send(5, 'shutdown') + const exit = await child + expect(exit.exitCode, `signal=${String(exit.signal)}; stderr=${stderr}`).toBe(0) + }, 40_000) + it('rejects an invalid max-token success env value', async () => { const root = await mkdtemp(join(tmpdir(), 'dsh-python-sdk-runtime-invalid-')) try { @@ -656,3 +737,64 @@ it.each(['unset', 'empty', 'full', 'python-only', 'python-only-patched', 'wrong- expect(exit.exitCode, stderr).toBe(0) await expect(readFile(join(home, 'dsh-runtimes', 'dsh-primary-runtime', 'runtime.json'))).rejects.toMatchObject({ code: 'ENOENT' }) }) + +it.each(['standard', 'ptc'] as const)('lists and loads the packaged dsh-doc skill through the SDK profile (%s)', async (mode) => { + const root = await mkdtemp(join(tmpdir(), 'sdk-dsh-doc-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const requests: { tools: { name: string }[]; messages: unknown }[] = [] + const toolUses = mode === 'standard' ? [{ type: 'tool_use', id: 'dsh-doc', name: 'skill', input: { name: 'dsh-doc' } } as const] : [] + const server = createServer((request, response) => { + let body = '' + request.setEncoding('utf8').on('data', (chunk: string) => { body += chunk }) + request.on('end', () => { + requests.push(JSON.parse(body) as { tools: { name: string }[]; messages: unknown }) + const toolUse = toolUses[requests.length - 1] + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(toolUse === undefined ? messagesResponse({ type: 'text', text: 'done' }, 'end_turn') : messagesResponse(toolUse, 'tool_use')) + }) + }) + onTestFinished(() => new Promise((resolve) => { server.close(() => { resolve() }) })) + 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 did not bind') + const launch = resolveExampleLaunch({ + srcBin: fileURLToPath(new URL('../../../src/bin.ts', import.meta.url)), mode: 'lib', + configArgs: ['--profile', 'sdk', ...mode === 'ptc' ? ['--patch', join(repoRoot, 'apps/cli/config/examples/ptc.yml')] : []], + env: { DSH_HOME: join(root, 'home'), DSH_PRIMARY_RUNTIME: '', DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1', + DEEPSEEK_API_KEY: 'local-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${address.port}` }, + }) + const child = execa(launch.command, launch.args, { cwd: repoRoot, env: launch.env, timeout: 60_000, reject: false }) + onTestFinished(async () => { child.kill('SIGKILL'); await child }) + let buffer = '', stderr = '' + const lines: string[] = [] + child.stdout.on('data', (chunk: Buffer) => { + buffer += chunk.toString() + const parts = buffer.split('\n') + buffer = parts.pop() ?? '' + lines.push(...parts) + }) + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString() }) + const send = (id: number, method: string, params?: object) => { + child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`) + return waitForLine(lines, value => value.id === id, () => stderr) + } + expect(await send(1, 'initialize', { cwd: root, provider: 'deepseek-official', model: 'deepseek-v4-pro' })).toHaveProperty('result') + await send(2, 'session/prompt', { sessionId: 'dsh-doc', contentBlocks: [{ type: 'text', text: 'How do DSH presets work?' }] }) + await waitForLine(lines, (value) => { + const params = value.params as { sessionId?: string; event?: { type?: string } } | undefined + return value.method === 'session.event' && params?.sessionId === 'dsh-doc' && params.event?.type === 'turn/end' + }, () => stderr) + expect(requests).toHaveLength(toolUses.length + 1) + expect(JSON.stringify(requests[0]!.messages)).toMatch(/- `dsh-doc`: Use when a task needs facts about DeepSeek Harness/) + if (mode === 'ptc') expect(requests[0]!.tools.map(tool => tool.name)).toEqual(['run_code']) + else { + const messages = requests[1]!.messages as { content: { tool_use_id?: string }[] }[] + const loaded = JSON.stringify(messages.flatMap(message => message.content).find(block => block.tool_use_id === 'dsh-doc')) + const directory = join(repoRoot, 'packages/preset/agent-preset/skills/dsh-doc').split(sep).join('/') + expect(loaded).toContain(JSON.stringify(`Base directory for this skill: ${directory}`).slice(1, -1)) + expect(loaded).toContain('# DeepSeek Harness documentation') + } + await send(3, 'shutdown') + const exit = await child + expect(exit.exitCode, stderr).toBe(0) +}) diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 3adb15bf54..ce69dc6d27 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -995,6 +995,11 @@ describe('the standard preset documentation skill', () => { setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'cordis').then(() => undefined), }) expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path) + const ptc = await testCtx.agents.create({ + sessionId: brandString('standard-doc-ptc'), meta: { cwd: root }, + setup: agentCtx => testCtx.agentPresets.mount(agentCtx, 'ptc').then(() => undefined), + }) + expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: ptc.agent }))?.path).toBe(definition.path) const schemas = testCtx.tools.schemas(standardAgent.agent) expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent)) expect(schemas.map(tool => tool.name)).toContain('cordis_inspect') diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index 0d9ee81fd6..43eec44e4d 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop-host", "description": "Private Node-mode host process for the Electron desktop application", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "private": true, "license": "MIT", "type": "module", @@ -37,6 +37,8 @@ "@deepseek-ai/dsh-session-persistence": "workspace:*", "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", - "@deepseek-ai/dsh-brand": "workspace:*" + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-api-workspace-files": "workspace:*" } } diff --git a/apps/desktop-host/src/file-drag.ts b/apps/desktop-host/src/file-drag.ts index 473ab67e56..4297d804d9 100644 --- a/apps/desktop-host/src/file-drag.ts +++ b/apps/desktop-host/src/file-drag.ts @@ -1,10 +1,8 @@ /** Resolve desktop-only file references through the active Host filesystem and Session. */ import { createHash } from 'node:crypto' import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-workspace-files' import type {} from '@deepseek-ai/dsh-fs' -import type {} from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-persistence' -import type {} from '@deepseek-ai/dsh-sandbox-policy' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { parseFileAddress } from '@deepseek-ai/dsh-util-workspace-path' @@ -17,6 +15,7 @@ export interface LocalDragResource { /** * Authorize an unmodified local file through the composed filesystem's actual read operations. + * Relative paths resolve from the same workspace root the workspace file service uses for the Session. * @param ctx - booted Desktop Host. * @param address - Session-scoped resource reference. * @param cancellation - caller cancellation, combined with the read deadline. @@ -25,17 +24,14 @@ export interface LocalDragResource { export async function localDragResource(ctx: Context, address: string, cancellation?: AbortSignal): Promise { const resource = parseFileAddress(address) if (resource?.scope !== 'session') throw new Error('File drag requires a Session resource') - const sessions = ctx.get('sessions') - const persistence = ctx.get('sessionPersistence') const fs = ctx.get('fs') - const policy = ctx.get('sandboxPolicy') - if (fs === undefined || sessions === undefined || policy === undefined) throw new Error('File access unavailable') - const sessionId = resource.sessionId as SessionId - const header = sessions.get(sessionId)?.header ?? (await persistence?.stat(sessionId))?.header - if (header === undefined) throw new Error('File drag Session unavailable') + const workspaceFiles = ctx.get('workspaceFiles') + if (fs === undefined || workspaceFiles === undefined) throw new Error('File access unavailable') const signal = cancellation === undefined ? AbortSignal.timeout(10_000) : AbortSignal.any([cancellation, AbortSignal.timeout(10_000)]) signal.throwIfAborted() - const cwd = header.cwd ?? policy.workspaceRoot + const scope = await workspaceFiles.scopeOf(resource.sessionId as SessionId, signal) + if (scope === undefined) throw new Error('File drag Session unavailable') + const cwd = scope.workspaceRoot const entry = await fs.lstat(resource.path, { cwd }, signal) if (entry?.type !== 'file') return null const target = await fs.resolve(resource.path, { cwd, signal }) diff --git a/apps/desktop-host/tests/file-drag.spec.ts b/apps/desktop-host/tests/file-drag.spec.ts index dc8ee85af2..97dbf0c811 100644 --- a/apps/desktop-host/tests/file-drag.spec.ts +++ b/apps/desktop-host/tests/file-drag.spec.ts @@ -17,9 +17,13 @@ async function fixture() { onTestFinished(async () => { await ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) await ctx.plugin(LocalFileSystem, { cwd: root }) await ctx.plugin(SessionStore) - ctx.provide('sandboxPolicy', { workspaceRoot: root } as never) const id = brandString('file-drag-test') ctx.sessions.create(id, { meta: { cwd: root, origin: 'subagent' } }) + // The workspace file service resolves a live Session's root; its own tests cover that resolution. + ctx.provide('workspaceFiles', { + scopeOf: (sessionId: SessionId) => + Promise.resolve(ctx.sessions.get(sessionId) === undefined ? undefined : { sessionId, workspaceRoot: root }), + } as never) const path = join(root, '报告.pdf') const bytes = Buffer.from('%PDF-1.4\n原始内容\n%%EOF') await writeFile(path, bytes) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index 54b3afee69..6449b60f32 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -11,6 +11,7 @@ { "path": "../../packages/host/authentication-desktop" }, { "path": "../../vendor/cordis" }, { "path": "../../packages/core/agent" }, + { "path": "../../packages/api/workspace-files/tsconfig.host.json" }, { "path": "../../packages/jobs/jobs" }, { "path": "../../packages/schedule/schedule" }, { "path": "../../packages/workspace/workspace" }, diff --git a/apps/desktop-publisher/package.json b/apps/desktop-publisher/package.json index a10f0bfcb0..5867ff5f44 100644 --- a/apps/desktop-publisher/package.json +++ b/apps/desktop-publisher/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-desktop-publisher", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "description": "Private Desktop release metadata, rollout and website publisher", "private": true, "type": "module", diff --git a/apps/desktop/README.i18n.yaml b/apps/desktop/README.i18n.yaml index 3e54d0e07e..46601acbb9 100644 --- a/apps/desktop/README.i18n.yaml +++ b/apps/desktop/README.i18n.yaml @@ -42,8 +42,8 @@ en: 98cf848762482d48 zh: 74f9100a39ec8c2f /deepseek-harness-desktop/develop: - en: faf7676ba18bbf2f - zh: f1d7b75ad348c548 + en: 4e4b26cfaaa098ee + zh: e0a2965606020041 /deepseek-harness-desktop/develop/startup-onboarding: en: 67dc7ef3e293236a zh: 1b224db684a2d1d7 @@ -54,8 +54,8 @@ en: 7200a35dbed997c3 zh: 511d6961530757f1 /deepseek-harness-desktop/windows-installer-interface: - en: 3a70021830865253 - zh: 0467be8b505446cb + en: eb9d30bca4134f80 + zh: bf201d18ae5ba697 /deepseek-harness-desktop/updates: en: 8b0b9efeb83727ef zh: 5ee95de48ceab392 diff --git a/apps/desktop/README.md b/apps/desktop/README.md index 4fb011f0b6..741248a2c9 100644 --- a/apps/desktop/README.md +++ b/apps/desktop/README.md @@ -199,7 +199,7 @@ The development application menu offers Reload Page (Cmd+R on macOS, Ctrl+R else pnpm run dev:desktop ``` -Development Harness state defaults to `apps/desktop/.desktop-build/development/home`, the disposable npm project lives at `apps/desktop/.desktop-build/development/project`, and Electron browser data lives at `apps/desktop/.desktop-build/development/electron-user-data`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. An explicit `DSH_HOME` replaces only the development Harness home. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed. +Development Harness state defaults to `apps/desktop/.desktop-dev/home` and Electron browser data to `apps/desktop/.desktop-dev/electron-user-data`; `pnpm run clean` removes `.desktop-build` but keeps this directory. The disposable npm project lives at `apps/desktop/.desktop-build/development/project`. Sessions, settings, credentials, package links, and browser data therefore stay out of the user's normal Harness home. A launch moves each missing default directory from `.desktop-build/development`, and stops instead while a running Harness Dev still uses that browser data. An explicit `DSH_HOME` replaces only the development Harness home, and `DSH_DESKTOP_USER_DATA_DIR` replaces only the browser data. Renderer DevTools opens automatically; Main, Renderer, and dsh Host debugging listen on ports 9229, 9222, and 9230. `DSH_DESKTOP_MAIN_INSPECT_PORT`, `DSH_DESKTOP_RENDERER_DEBUG_PORT`, and `DSH_DESKTOP_HOST_INSPECT_PORT` replace those ports, while `DSH_DESKTOP_OPEN_DEVTOOLS=0` keeps the detached Renderer tools closed. After an explicit build, `start:desktop` reconstructs the disposable project and launches the existing artifacts without building again: @@ -261,7 +261,7 @@ During a confirmed Windows update restart, a separate process displays a draggab The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running. -The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. The finish page preserves the window position. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation. +The theme follows Windows at startup; `/THEME=light`, `/THEME=dark`, and `/THEME=auto` select a palette explicitly. The window appears after its branded controls are ready. When the welcome page first appears, the installer moves above ordinary windows once and flashes its taskbar button if another window has focus; it does not remain always on top. Progress reads the pinned 7-Zip extractor’s percentage; directory promotion, registration, and cleanup retain bounded estimates. The weighted percentage does not predict remaining time. After NSIS reports success, the bar fills over 600 ms and displays 100% briefly before the finish page appears; the transition targets 750 ms. Finish controls appear in the existing progress window while a title-bar drag or system menu remains active. Completion flashes the taskbar button three times if the installer is minimized or another window has focus. During installation, the Close button is disabled and dimmed without changing the cursor. On the finish page, Close exits without launching the application. Finish dismisses the installer before launching the installed executable; a launch failure restores the page for retry. Directory replacement and failure recovery follow the [installation checks](packaging/README.md#runtime-file-selection). First-launch profile preparation remains a separate Desktop operation. Windows packaging compiles an x86 Win32/GDI+ helper with Visual C++ Build Tools and a Windows SDK; signed builds sign this helper through the configured Windows signer. The progress page keeps one opaque pixel buffer for its lifetime, draws static artwork once, and copies repainted pixels with GDI. The preparation hook leaves production dependency collection to electron-builder on every platform. diff --git a/apps/desktop/README.zh.md b/apps/desktop/README.zh.md index db0a99cb50..6fedfb2a5e 100644 --- a/apps/desktop/README.zh.md +++ b/apps/desktop/README.zh.md @@ -199,7 +199,7 @@ macOS 和 Linux 从图形界面启动的程序只继承会话管理器提供的 pnpm run dev:desktop ``` -开发 Harness 状态默认写入 `apps/desktop/.desktop-build/development/home`,一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`,Electron 浏览器数据则位于 `apps/desktop/.desktop-build/development/electron-user-data`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home;显式 `DSH_HOME` 只会替换开发 Harness home。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。 +开发 Harness 状态默认写入 `apps/desktop/.desktop-dev/home`,Electron 浏览器数据默认写入 `apps/desktop/.desktop-dev/electron-user-data`;`pnpm run clean` 会删除 `.desktop-build`,但保留该目录。一次性 npm 项目位于 `apps/desktop/.desktop-build/development/project`。因此,会话、设置、凭据、包链接和浏览器数据都不会进入用户正常使用的 Harness home。启动时会把每个缺失的默认目录从 `.desktop-build/development` 移过来;若正在运行的 Harness Dev 仍在使用那里的浏览器数据,启动会停止而不迁移。显式 `DSH_HOME` 只会替换开发 Harness home,`DSH_DESKTOP_USER_DATA_DIR` 只会替换浏览器数据。Renderer DevTools 默认自动打开,Main、Renderer 和 dsh Host 调试端口依次为 9229、9222 和 9230。`DSH_DESKTOP_MAIN_INSPECT_PORT`、`DSH_DESKTOP_RENDERER_DEBUG_PORT` 与 `DSH_DESKTOP_HOST_INSPECT_PORT` 可以替换这些端口,`DSH_DESKTOP_OPEN_DEVTOOLS=0` 则保持 Renderer 调试窗口关闭。 显式构建完成后,`start:desktop` 会重新生成一次性项目,并跳过构建直接启动已有产物: @@ -261,7 +261,7 @@ Windows 更新确认重启后,独立进程显示可拖动的状态提示,直 Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。 -主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成页保留窗口位置。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。 +主题在启动时跟随 Windows;可用 `/THEME=light`、`/THEME=dark` 和 `/THEME=auto` 显式选择配色。窗口在品牌控件准备完成后显示。欢迎页首次出现时,安装窗口会一次性移到普通窗口前方;若焦点在其他窗口,任务栏按钮会闪烁提示,但安装窗口不会始终置顶。进度读取锁定版本的 7-Zip 解压器百分比;目录替换、注册和清理仍使用有界估算。加权百分比不代表剩余时间。NSIS 报告成功后,进度条用 600 毫秒补满并短暂显示 100%,再显示完成页;切换目标时长为 750 毫秒。完成按钮与启动复选框在原进度窗口中显示,拖动标题栏或打开系统菜单时也会更新。若安装器已最小化或焦点在其他窗口,安装完成时任务栏按钮会闪烁三次。安装中关闭按钮禁用并变灰,鼠标指针保持不变;完成页的关闭按钮退出安装器且不启动应用。点击完成后,安装程序先隐藏窗口,再启动已安装的可执行文件;启动失败会恢复页面以供重试。目录替换和失败恢复遵循[安装检查](packaging/README.zh.md#runtime-file-selection)。首次启动的配置档案准备仍属于独立的 Desktop 操作。 Windows 打包使用 Visual C++ Build Tools 和 Windows SDK 编译 x86 Win32/GDI+ 辅助库;签名构建通过已配置的 Windows 签名器对该库签名。进度页在其生命周期内保留一个不透明像素缓冲,只绘制一次静态图像,并通过 GDI 复制重绘的像素。准备钩子在所有平台上均由 electron-builder 继续负责收集生产依赖。 diff --git a/apps/desktop/docs/diagnostics/README.i18n.yaml b/apps/desktop/docs/diagnostics/README.i18n.yaml index 44994b4b1e..077c177b9d 100644 --- a/apps/desktop/docs/diagnostics/README.i18n.yaml +++ b/apps/desktop/docs/diagnostics/README.i18n.yaml @@ -24,5 +24,5 @@ en: f1c19c1516a51ab6 zh: b350f7c18086d274 /desktop-recovery-and-diagnostics/collection-and-shutdown: - en: bac4a49f63d4aaf8 - zh: df1ae908ee2148e1 + en: 67555a4116943e85 + zh: 451231cb6e28ffe9 diff --git a/apps/desktop/docs/diagnostics/README.md b/apps/desktop/docs/diagnostics/README.md index e0e72c3f1e..f50fbd139c 100644 --- a/apps/desktop/docs/diagnostics/README.md +++ b/apps/desktop/docs/diagnostics/README.md @@ -67,6 +67,8 @@ The Host announces its run ID before profile loading; reported Host errors carry Collection reads only two owned files under `userData/plugin-operations`, at most 64 KiB and 100 records; the complete appended section is limited to 64 KiB. +Only a predecessor whose handle reports the exact bigint file identity of the segment already read is deduplicated as already collected: the predecessor is skipped, so its records are not collected twice, and records appended to it after it was read are not collected. On Windows, opening a segment retries `EACCES`, `EBUSY` and `EPERM` up to four times with a 10→40 ms backoff before the segment counts as unavailable, cancellation ends those retries, and `filesRead` counts owned segments that yielded bytes. + The 500 ms collection budget reserves its final 100 ms for cooperative cancellation before requesting forced Worker termination; completion waits for its exit. Application exit, recovery exit or restart, and confirmed update installation also cancel collection and wait at most 500 ms for Worker exit. A rejected shutdown cleanup is logged without skipping the remaining cleanup waits. Shutdown prevents late basic-report saves from starting another collector. An update installation failure permits future collection again. Worker messages interrupt collection between bounded records; an in-flight file open, stat, read or close must settle, and synchronous parsing cannot be preempted within one record. The final append uses an abort signal but can leave partial bytes. Forced termination remains the fallback when cooperative cleanup does not finish. diff --git a/apps/desktop/docs/diagnostics/README.zh.md b/apps/desktop/docs/diagnostics/README.zh.md index 8e25e9721a..c593e5bdd8 100644 --- a/apps/desktop/docs/diagnostics/README.zh.md +++ b/apps/desktop/docs/diagnostics/README.zh.md @@ -67,6 +67,8 @@ Host 在加载 profile 前报告运行 ID;Host 错误中的 `hostRunId` 与该 收集只读取 `userData/plugin-operations` 下归其管理的两个文件,最多读取 64 KiB 和 100 条记录;完整追加内容不超过 64 KiB。 +只有前驱段的句柄给出与已读段完全相同的 bigint 文件身份时才判为已收集:该前驱段会被跳过,因此它的记录不会被重复收集,但在被读取之后追加到它的记录不会被收集。Windows 上打开文件段遇到 `EACCES`、`EBUSY`、`EPERM` 时最多重试四次,退避 10→40 ms,之后该段才计入不可用;取消会结束这些重试;`filesRead` 统计实际读到字节的所属文件段。 + 500 ms 收集预算中的最后 100 ms 用于协作取消,随后才请求强制终止 Worker;只有 Worker 退出后才确认收集结束。应用退出、恢复退出或重启、确认安装更新也会取消收集,并最多等待 500 ms 确认 Worker 退出。退出清理中的拒绝会被记录,但不会跳过其他清理等待。退出过程中,延迟保存完成的基本报告不会再启动收集器。更新安装失败后可再次收集。 Worker 在有界记录之间处理取消消息;已经发出的文件打开、状态读取、读取或关闭操作必须等待完成,单条记录的同步解析不能被抢占。最后的追加写入传入取消信号,但仍可能留下部分字节。协作清理未及时完成时仍需强制终止。 diff --git a/apps/desktop/installer/drawing.nsh b/apps/desktop/installer/drawing.nsh index 926e56bc97..67287b2e95 100644 --- a/apps/desktop/installer/drawing.nsh +++ b/apps/desktop/installer/drawing.nsh @@ -43,78 +43,3 @@ Function InstallerDrawEditFrame System::Call 'gdiplus::GdipDeleteGraphics(p R4)' System::Call 'gdiplus::GdipDisposeImage(p R5)' FunctionEnd - -; BS_AUTOCHECKBOX retains its native state, text, keyboard and accessibility role. -Function InstallerPaintCheckbox - Pop $R0 - Pop $R1 - Pop $R2 - ${If} $R1 != -12 - Return - ${EndIf} - System::Call '*$R2(p, p, i, i .R3, p .R4, i, i, i, i, p, i .R9)' - ${If} $R3 != 1 - Return - ${EndIf} - System::Call 'gdi32::SaveDC(p R4)' - System::Alloc 16 - Pop $R2 - System::Call 'user32::GetClientRect(p R0, p R2)' - System::Call 'gdi32::CreateSolidBrush(i $InstallerBgColorref) p.R3' - System::Call 'user32::FillRect(p R4, p R2, p R3)' - System::Call 'gdi32::DeleteObject(p R3)' - System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r2' - System::Call 'kernel32::MulDiv(i 7, i $InstallerDpi, i 96) i.r3' - System::Call 'gdi32::SetViewportOrgEx(p R4, i r2, i r3, p 0)' - System::Call 'gdiplus::GdipCreateFromHDC(p R4, *p .R5)' - System::Call 'gdiplus::GdipSetSmoothingMode(p R5, i 4)' - System::Call 'kernel32::MulDiv(i 18, i $InstallerDpi, i 96) i.R7' - StrCpy $R8 $R7 - System::Call 'kernel32::MulDiv(i 6, i $InstallerDpi, i 96) i.R3' - !insertmacro InstallerRoundPath $R6 $R7 $R8 $R3 - ${NSD_GetState} $R0 $R8 - StrCpy $R3 $InstallerBgArgb - ${If} $R8 == ${BST_CHECKED} - StrCpy $R3 $InstallerPrimary - ${EndIf} - System::Call 'gdiplus::GdipCreateSolidFill(i R3, *p .R1)' - System::Call 'gdiplus::GdipFillPath(p R5, p R1, p R6)' - System::Call 'gdiplus::GdipDeleteBrush(p R1)' - ${If} $R8 != ${BST_CHECKED} - System::Call 'gdiplus::GdipCreatePen1(i $InstallerBorder, i 0x40000000, i 2, *p .R1)' - System::Call 'gdiplus::GdipDrawPath(p R5, p R1, p R6)' - System::Call 'gdiplus::GdipDeletePen(p R1)' - ${EndIf} - System::Call 'gdiplus::GdipDeletePath(p R6)' - System::Call 'gdiplus::GdipDeleteGraphics(p R5)' - ${If} $R8 == ${BST_CHECKED} - System::Call 'kernel32::MulDiv(i 2, i $InstallerDpi, i 96) i.r0' - System::Call 'gdi32::CreatePen(i 0, i r0, i $InstallerButtonText) p.R1' - System::Call 'gdi32::SelectObject(p R4, p R1) p.R3' - System::Call 'kernel32::MulDiv(i 4, i $InstallerDpi, i 96) i.r0' - System::Call 'kernel32::MulDiv(i 9, i $InstallerDpi, i 96) i.r1' - System::Call 'gdi32::MoveToEx(p R4, i r0, i r1, p 0)' - System::Call 'kernel32::MulDiv(i 8, i $InstallerDpi, i 96) i.r0' - System::Call 'kernel32::MulDiv(i 13, i $InstallerDpi, i 96) i.r1' - System::Call 'gdi32::LineTo(p R4, i r0, i r1)' - System::Call 'kernel32::MulDiv(i 14, i $InstallerDpi, i 96) i.r0' - System::Call 'kernel32::MulDiv(i 5, i $InstallerDpi, i 96) i.r1' - System::Call 'gdi32::LineTo(p R4, i r0, i r1)' - System::Call 'gdi32::SelectObject(p R4, p R3)' - System::Call 'gdi32::DeleteObject(p R1)' - ${EndIf} - System::Call 'gdi32::SetViewportOrgEx(p R4, i 0, i 0, p 0)' - System::Call 'kernel32::MulDiv(i 34, i $InstallerDpi, i 96) i.r0' - System::Call '*$R2(i r0)' - System::Call 'gdi32::SetBkMode(p R4, i 1)' - System::Call 'gdi32::SetTextColor(p R4, i $InstallerTextColorref)' - System::Call 'gdi32::SelectObject(p R4, p $InstallerSmallFont)' - System::Call 'user32::DrawTextW(p R4, w "$(INSTALLER_LAUNCH)", i -1, p R2, i 0x24)' - IntOp $R9 $R9 & 16 - ${If} $R9 != 0 - System::Call 'user32::DrawFocusRect(p R4, p R2)' - ${EndIf} - System::Call 'gdi32::RestoreDC(p R4, i -1)' - System::Free $R2 - ${NSD_Return} 4 -FunctionEnd diff --git a/apps/desktop/installer/lifecycle.nsh b/apps/desktop/installer/lifecycle.nsh index 521bfe20fe..a75393e3e0 100644 --- a/apps/desktop/installer/lifecycle.nsh +++ b/apps/desktop/installer/lifecycle.nsh @@ -54,6 +54,7 @@ Function InstallerBeforeInstall FunctionEnd Function InstallerProgressShow + StrCpy $InstallerPhase "installing" ; Only the stock worker executes installation; this overlay runs on the UI thread. ShowWindow $mui.InstFilesPage 0 StrCpy $0 0 @@ -79,12 +80,24 @@ Function .onInstFailed Quit FunctionEnd -Function InstallerFinish - System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow) i.r0 ?c' - ${If} $0 == 0 - Quit +Function InstallerProgressLeave + IfAbort failed + ${If} $InstallerPhase == "installing" + System::Call '$PLUGINSDIR\window-frame.dll::InstallerFinishProgress(p $InstallerProgressWindow, w "$(INSTALLER_FINISH)", w "$(INSTALLER_LAUNCH)") i.r0 ?c' + ${If} $0 == 0 + MessageBox MB_OK|MB_ICONSTOP "$(INSTALLER_UI_ERROR)" + SetErrorLevel 2 + Quit + ${EndIf} + StrCpy $InstallerPhase "success" + Abort ${EndIf} - System::Call 'user32::DestroyWindow(p $InstallerProgressWindow)' - StrCpy $InstallerPhase "success" - Call InstallerCreate + System::Call '$PLUGINSDIR\window-frame.dll::InstallerTakeFinishChoice(p $InstallerProgressWindow) i.r0 ?c' + ${If} $0 < 0 + Abort + ${EndIf} + Call InstallerFinishLeave + Return +failed: + ; NSIS owns installation failure and its exit code. FunctionEnd diff --git a/apps/desktop/installer/pages.nsh b/apps/desktop/installer/pages.nsh index 1044f05324..20c1cafbdd 100644 --- a/apps/desktop/installer/pages.nsh +++ b/apps/desktop/installer/pages.nsh @@ -16,7 +16,6 @@ Var InstallerChoose Var InstallerEdit Var InstallerEditFrame Var InstallerBrowse -Var InstallerLaunch Var InstallerExpanded Var InstallerMinimizeButton Var InstallerCloseButton @@ -137,30 +136,6 @@ Function InstallerCreate !insertmacro InstallerPlace $InstallerBrowse 456 434 80 34 ${NSD_OnClick} $InstallerBrowse InstallerBrowsePath ${NSD_OnNotify} $InstallerBrowse InstallerPaintButton - ${NSD_CreateCheckbox} 0 0 0 0 "$(INSTALLER_LAUNCH)" - Pop $InstallerLaunch - SendMessage $InstallerLaunch ${WM_SETFONT} $InstallerSmallFont 1 - System::Call 'user32::GetDC(p $InstallerLaunch) p.r4' - System::Call 'gdi32::SelectObject(p r4, p $InstallerSmallFont) p.r5' - StrLen $0 "$(INSTALLER_LAUNCH)" - System::Alloc 8 - Pop $6 - System::Call 'gdi32::GetTextExtentPoint32W(p r4, w "$(INSTALLER_LAUNCH)", i r0, p r6)' - System::Call '*$6(i .r7)' - System::Free $6 - System::Call 'gdi32::SelectObject(p r4, p r5)' - System::Call 'user32::ReleaseDC(p $InstallerLaunch, p r4)' - System::Call 'kernel32::MulDiv(i 42, i $InstallerDpi, i 96) i.r2' - IntOp $2 $2 + $7 - IntOp $0 $InstallerSize - $2 - IntOp $0 $0 / 2 - System::Call 'kernel32::MulDiv(i 438, i $InstallerDpi, i 96) i.r1' - System::Call 'kernel32::MulDiv(i 32, i $InstallerDpi, i 96) i.r3' - System::Call 'user32::MoveWindow(p $InstallerLaunch, i r0, i r1, i r2, i r3, i 1)' - !insertmacro InstallerControlColors $InstallerLaunch - ${NSD_OnNotify} $InstallerLaunch InstallerPaintCheckbox - ${NSD_Check} $InstallerLaunch - ${NSD_CreateButton} 0 0 0 0 "$(INSTALLER_INSTALL)" Pop $InstallerButton !insertmacro InstallerPlace $InstallerButton ${INSTALLER_BUTTON_X} ${INSTALLER_BUTTON_Y} ${INSTALLER_BUTTON_WIDTH} ${INSTALLER_BUTTON_HEIGHT} @@ -188,20 +163,13 @@ Function InstallerRender ShowWindow $InstallerEdit 0 ShowWindow $InstallerEditFrame 0 ShowWindow $InstallerBrowse 0 - ShowWindow $InstallerLaunch 0 ShowWindow $InstallerStatus 0 - ${If} $InstallerPhase == "success" - ${NSD_SetText} $InstallerButton "$(INSTALLER_FINISH)" - ShowWindow $InstallerLaunch 5 + ${If} $InstallerExpanded == 1 + ShowWindow $InstallerEditFrame 5 + ShowWindow $InstallerEdit 5 + ShowWindow $InstallerBrowse 5 ${Else} - ${NSD_SetText} $InstallerButton "$(INSTALLER_INSTALL)" - ${If} $InstallerExpanded == 1 - ShowWindow $InstallerEditFrame 5 - ShowWindow $InstallerEdit 5 - ShowWindow $InstallerBrowse 5 - ${Else} - ShowWindow $InstallerChoose 5 - ${EndIf} + ShowWindow $InstallerChoose 5 ${EndIf} FunctionEnd @@ -220,8 +188,8 @@ Function InstallerWelcomeLeave ${EndIf} FunctionEnd +; The completed page requests exit with the user's launch choice in $0. Function InstallerFinishLeave - ${NSD_GetState} $InstallerLaunch $0 HideWindow ${If} $0 == ${BST_CHECKED} StrCpy $0 "" diff --git a/apps/desktop/installer/window-frame.cpp b/apps/desktop/installer/window-frame.cpp index 67ec64ce40..9e3c760f29 100644 --- a/apps/desktop/installer/window-frame.cpp +++ b/apps/desktop/installer/window-frame.cpp @@ -140,8 +140,14 @@ struct ProgressPage { ARGB controlHover; ARGB controlPressed; WCHAR captions[5][128]; + HWND finish, launch, minimize, close; + bool controlsVisible = false; + int finishChoice = -1; + HFONT finishFont, launchFont; ~ProgressPage() { + if (finishFont) DeleteObject(finishFont); + if (launchFont) DeleteObject(launchFont); delete buffer; delete brand; if (previousBitmap) SelectObject(bufferDc, previousBitmap); @@ -178,13 +184,16 @@ static UINT CaptionCommand(const ProgressPage& page, LPARAM position) { const int x = static_cast(LOWORD(position)); const int y = static_cast(HIWORD(position)); if (y < 0 || y >= MulDiv(48, page.dpi, 96) || x < MulDiv(504, page.dpi, 96) || x >= MulDiv(600, page.dpi, 96)) return 0; - return x >= MulDiv(548, page.dpi, 96) ? SC_CLOSE : SC_MINIMIZE; + // Installation cannot be cancelled with the progress page close button. + return x >= MulDiv(548, page.dpi, 96) ? 0 : SC_MINIMIZE; } static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) { SolidBrush background(page.dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255)); graphics.FillRectangle(&background, 504, 0, 96, 48); SolidBrush ink(page.dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21)); + // Disabled caption uses the same foreground with reduced opacity in both themes. + SolidBrush disabledInk(page.dark ? Color(96, 255, 255, 255) : Color(96, 15, 17, 21)); FontFamily family(L"Microsoft YaHei UI"); Font font(&family, 16, FontStyleRegular, UnitPixel); StringFormat centered; @@ -204,7 +213,7 @@ static void PaintCaptionButtons(Graphics& graphics, const ProgressPage& page) { graphics.FillPath(&fill, &path); } graphics.DrawString(command == SC_MINIMIZE ? L"\x2212" : L"\x00d7", -1, - &font, RectF(static_cast(x), 8, 40, 32), ¢ered, &ink); + &font, RectF(static_cast(x), 8, 40, 32), ¢ered, command == SC_CLOSE ? &disabledInk : &ink); } } @@ -213,15 +222,109 @@ static void InvalidateCaptionButtons(HWND window, const ProgressPage& page) { InvalidateRect(window, &bounds, FALSE); } +// NSIS ui.h: request that the stock instfiles page run its leave callback. +constexpr UINT WM_NOTIFY_OUTER_NEXT = WM_USER + 8; + +static void RequestFinish(HWND window, ProgressPage& page, bool launch) { + if (!page.controlsVisible || page.finishChoice >= 0) return; + if (PostMessageW(GetParent(window), WM_NOTIFY_OUTER_NEXT, 1, 0)) page.finishChoice = launch ? 1 : 0; +} + +static void RevealFinish(HWND window, ProgressPage& page) { + page.controlsVisible = true; + KillTimer(window, 1); + SetWindowTextW(window, L""); + InvalidateRect(window, nullptr, FALSE); + for (HWND child : {page.finish, page.launch, page.minimize, page.close}) ShowWindow(child, SW_SHOWNA); + HWND frame = GetParent(window); + if (GetForegroundWindow() != frame || IsIconic(frame)) { + FLASHWINFO flash = {sizeof(flash), frame, FLASHW_TRAY, 3, 0}; + FlashWindowEx(&flash); + } +} + +static LRESULT DrawFinishControl(const ProgressPage& page, NMCUSTOMDRAW& draw) { + if (draw.dwDrawStage != CDDS_PREPAINT) return CDRF_DODEFAULT; + const HWND control = draw.hdr.hwndFrom; + const bool primary = control == page.finish; + const bool checkbox = control == page.launch; + const bool pressed = (draw.uItemState & CDIS_SELECTED) != 0; + const bool hot = (draw.uItemState & CDIS_HOT) != 0; + const Color background = page.dark ? Color(255,21,21,23) : Color(255,255,255,255); + const Color foreground = page.dark ? Color(255,255,255,255) : Color(255,15,17,21); + const Color accent = page.dark ? Color(255,249,250,251) : Color(255,15,17,21); + const Color inverse = page.dark ? Color(255,15,17,21) : Color(255,255,255,255); + RECT rect; GetClientRect(control, &rect); + HDC dc = draw.hdc; + const int saved = SaveDC(dc); + { + Graphics graphics(dc); + graphics.ScaleTransform(page.dpi / 96.0f, page.dpi / 96.0f); + graphics.SetSmoothingMode(SmoothingModeAntiAlias); + graphics.Clear(background); + const bool checked = checkbox && SendMessageW(control, BM_GETCHECK, 0, 0) == BST_CHECKED; + Color fill = primary ? accent : background; + if (primary && (hot || pressed)) { + fill = page.dark ? (pressed ? Color(255,212,219,233) : Color(255,233,236,242)) + : (pressed ? Color(255,0,0,0) : Color(255,45,49,53)); + } else if (checkbox) { + fill = checked ? accent : background; + } else if (hot || pressed) { + fill = Color(pressed ? page.controlPressed : page.controlHover); + } + const REAL x = checkbox ? 8.0f : 0.0f, y = checkbox ? 7.0f : 0.0f; + const REAL w = checkbox ? 18.0f : rect.right * 96.0f / page.dpi; + const REAL h = checkbox ? 18.0f : rect.bottom * 96.0f / page.dpi; + const REAL d = checkbox ? 6.0f : 20.0f; + GraphicsPath path; + path.AddArc(x,y,d,d,180,90); path.AddArc(x+w-d,y,d,d,270,90); + path.AddArc(x+w-d,y+h-d,d,d,0,90); path.AddArc(x,y+h-d,d,d,90,90); path.CloseFigure(); + SolidBrush brush(fill); graphics.FillPath(&brush,&path); + if (checkbox && !checked) { + Pen border(page.dark ? Color(255,97,102,107) : Color(255,187,192,200)); graphics.DrawPath(&border,&path); + } else if (checked) { + Pen pen(inverse,2.0f); Point points[] = {{12,16},{16,20},{22,12}}; + graphics.DrawLines(&pen,points,3); + } + } + WCHAR caption[256]; GetWindowTextW(control,caption,ARRAYSIZE(caption)); + const Color text = primary ? inverse : foreground; + SetTextColor(dc,RGB(text.GetR(),text.GetG(),text.GetB())); SetBkMode(dc,TRANSPARENT); + SelectObject(dc,checkbox ? page.launchFont : page.finishFont); + if (checkbox) rect.left += MulDiv(34,page.dpi,96); + DrawTextW(dc,caption,-1,&rect,DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX | (checkbox ? DT_LEFT : DT_CENTER)); + if (draw.uItemState & CDIS_FOCUS) { InflateRect(&rect,-3,-3); DrawFocusRect(dc,&rect); } + RestoreDC(dc,saved); + return CDRF_SKIPDEFAULT; +} + static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { auto* page = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); if (message == WM_CREATE) { page = static_cast(reinterpret_cast(lparam)->lpCreateParams); SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(page)); - SetTimer(window, 1, 16, nullptr); } if (message == WM_ERASEBKGND) return 1; - if (message == WM_TIMER) { InvalidateRect(window, nullptr, FALSE); return 0; } + if (message == WM_TIMER && page && wparam == 1) { + if (page->controlsVisible) return 0; + InvalidateRect(window, nullptr, FALSE); + if (page->progress.succeeded && GetTickCount64() - page->progress.animationStarted >= 750) { + // A covered window may not have painted its final frame on the last tick. + UpdateWindow(window); + RevealFinish(window, *page); + } + return 0; + } + if (message == WM_NOTIFY && page && reinterpret_cast(lparam)->code == NM_CUSTOMDRAW) { + return DrawFinishControl(*page, *reinterpret_cast(lparam)); + } + if (message == WM_COMMAND && page && page->controlsVisible && HIWORD(wparam) == BN_CLICKED) { + HWND control = reinterpret_cast(lparam); + if (control == page->finish || control == page->close) { + RequestFinish(window, *page, control == page->finish && SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED); + } else if (control == page->minimize) ShowWindow(GetParent(window), SW_MINIMIZE); + return 0; + } if (message == WM_MOUSEMOVE && page) { TRACKMOUSEEVENT tracking{sizeof(tracking), TME_LEAVE, window, 0}; TrackMouseEvent(&tracking); @@ -259,10 +362,7 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L InvalidateCaptionButtons(window, *page); const bool activate = command && GetCapture() == window && CaptionCommand(*page, lparam) == command; if (GetCapture() == window) ReleaseCapture(); - if (activate) { - if (command == SC_CLOSE) PostMessageW(GetParent(window), WM_CLOSE, 0, 0); - else ShowWindow(GetParent(window), SW_MINIMIZE); - } + if (activate) ShowWindow(GetParent(window), SW_MINIMIZE); return 0; } if ((message == WM_CAPTURECHANGED || message == WM_CANCELMODE) && page) { @@ -284,23 +384,25 @@ static LRESULT CALLBACK ProgressProc(HWND window, UINT message, WPARAM wparam, L PaintCaptionButtons(graphics, *page); SolidBrush background(page->dark ? Color(255, 21, 21, 23) : Color(255, 255, 255, 255)); graphics.FillRectangle(&background, 48, 480, 504, 56); - const int stage = static_cast(reinterpret_cast(GetPropW(GetParent(window), L"HarnessInstaller.Stage"))); - const double fraction = reinterpret_cast(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0; - page->progress.Advance(stage, fraction, GetTickCount64()); - const int percent = static_cast(page->progress.value); - SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242)); - SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21)); - FillProgress(graphics, track, 472.0f); - FillProgress(graphics, ink, 472.0f * static_cast(page->progress.value) / 100); - FontFamily family(L"Microsoft YaHei UI"); - Font font(&family, 14, FontStyleRegular, UnitPixel); - StringFormat centered; - centered.SetAlignment(StringAlignmentCenter); - centered.SetLineAlignment(StringAlignmentCenter); - WCHAR caption[160]; - wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent); - SetWindowTextW(window, caption); - graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), ¢ered, &ink); + if (!page->controlsVisible) { + const int stage = static_cast(reinterpret_cast(GetPropW(GetParent(window), L"HarnessInstaller.Stage"))); + const double fraction = reinterpret_cast(GetPropW(GetParent(window), L"HarnessInstaller.ExtractProgress")) / 100.0; + page->progress.Advance(stage, fraction, GetTickCount64()); + const int percent = static_cast(page->progress.value); + SolidBrush track(page->dark ? Color(255, 97, 102, 107) : Color(255, 233, 236, 242)); + SolidBrush ink(page->dark ? Color(255, 255, 255, 255) : Color(255, 15, 17, 21)); + FillProgress(graphics, track, 472.0f); + FillProgress(graphics, ink, 472.0f * static_cast(page->progress.value) / 100); + FontFamily family(L"Microsoft YaHei UI"); + Font font(&family, 14, FontStyleRegular, UnitPixel); + StringFormat centered; + centered.SetAlignment(StringAlignmentCenter); + centered.SetLineAlignment(StringAlignmentCenter); + WCHAR caption[160]; + wsprintfW(caption, page->captions[page->progress.CaptionStage()], percent); + SetWindowTextW(window, caption); + graphics.DrawString(caption, -1, &font, RectF(48, 512, 504, 22), ¢ered, &ink); + } } BitBlt(dc, paint.rcPaint.left, paint.rcPaint.top, paint.rcPaint.right - paint.rcPaint.left, paint.rcPaint.bottom - paint.rcPaint.top, @@ -372,9 +474,10 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent, } delete page->brand; page->brand = nullptr; - HWND window = CreateWindowExW(0, type.lpszClassName, L"", WS_CHILD, + HWND window = CreateWindowExW(WS_EX_CONTROLPARENT, type.lpszClassName, L"", WS_CHILD | WS_CLIPCHILDREN, 0, 0, MulDiv(600, dpi, 96), MulDiv(600, dpi, 96), parent, nullptr, module, page); if (!window) { delete page; return nullptr; } + if (!SetTimer(window, 1, 16, nullptr)) { DestroyWindow(window); return nullptr; } // Keep the stock page available until the replacement is fully constructed. HWND stockPage = GetParent(source); if (!SetWindowSubclass(stockPage, HiddenPageProc, 1, 0)) { @@ -385,32 +488,65 @@ extern "C" __declspec(dllexport) HWND __cdecl InstallerShowProgress(HWND parent, return window; } -// NSIS has already reported success. Pump the UI for the bounded final animation, -// including a painted 100% frame, before constructing the interactive finish page. -extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window) { +// Called from the instfiles leave callback on success. Timer paints finish the +// animation while USER32 continues dispatching the current move or menu. +extern "C" __declspec(dllexport) BOOL __cdecl InstallerFinishProgress(HWND window, LPCWSTR finish, LPCWSTR launch) { auto* page = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); if (!page) return FALSE; - const ULONGLONG started = GetTickCount64(); + if (page->progress.succeeded) return TRUE; + const auto scaled = [&](int n) { return MulDiv(n,page->dpi,96); }; + page->finishFont = CreateFontW(-scaled(16),0,0,0,FW_MEDIUM,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI"); + page->launchFont = CreateFontW(-scaled(14),0,0,0,FW_NORMAL,0,0,0,DEFAULT_CHARSET,0,0,CLEARTYPE_QUALITY,0,L"Microsoft YaHei UI"); + if (!page->finishFont || !page->launchFont) return FALSE; + HDC dc = GetDC(window); + if (!dc) return FALSE; + HGDIOBJ old = SelectObject(dc,page->launchFont); + SIZE size = {}; + const BOOL measured = GetTextExtentPoint32W(dc,launch,lstrlenW(launch),&size); + SelectObject(dc,old); ReleaseDC(window,dc); + if (!measured) return FALSE; + const int launchWidth = std::min(scaled(600),static_cast(size.cx) + scaled(42)); + auto button = [&](INT_PTR id, LPCWSTR title, DWORD style, int x, int y, int w, int h, HFONT font) { + HWND child = CreateWindowW(L"BUTTON",title,WS_CHILD|WS_TABSTOP|style,x,y,w,h,window,reinterpret_cast(id),GetModuleHandleW(nullptr),nullptr); + if (child) SendMessageW(child,WM_SETFONT,reinterpret_cast(font),FALSE); + return child; + }; + page->finish = button(0x6100,finish,BS_DEFPUSHBUTTON,scaled(240),scaled(490),scaled(120),scaled(44),page->finishFont); + page->launch = button(0x6101,launch,BS_AUTOCHECKBOX,(scaled(600)-launchWidth)/2,scaled(438),launchWidth,scaled(32),page->launchFont); + page->minimize = button(0x6102,L"\x2212",BS_PUSHBUTTON,scaled(504),scaled(8),scaled(40),scaled(32),page->finishFont); + page->close = button(0x6103,L"\x00d7",BS_PUSHBUTTON,scaled(548),scaled(8),scaled(40),scaled(32),page->finishFont); + if (!page->finish || !page->launch || !page->minimize || !page->close) return FALSE; + SendMessageW(page->launch,BM_SETCHECK,BST_CHECKED,0); SetPropW(GetParent(window), L"HarnessInstaller.Succeeded", reinterpret_cast(1)); - page->progress.Complete(started); - while (IsWindow(window) && GetTickCount64() - started < 750) { - MSG message; - if (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) { - if (message.message == WM_QUIT) { PostQuitMessage(static_cast(message.wParam)); return FALSE; } - TranslateMessage(&message); - DispatchMessageW(&message); - } else { - MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE); - } - } - if (!IsWindow(window)) return FALSE; - InvalidateRect(window, nullptr, FALSE); - UpdateWindow(window); + page->progress.Complete(GetTickCount64()); return TRUE; } +// Reading consumes one explicit Finish/Close action so a failed launch can retry. +extern "C" __declspec(dllexport) int __cdecl InstallerTakeFinishChoice(HWND window) { + auto* page = reinterpret_cast(GetWindowLongPtrW(window,GWLP_USERDATA)); + if (!page) return -1; + int choice = page->finishChoice; + page->finishChoice = -1; + return choice; +} + static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam, UINT_PTR id, DWORD_PTR) { + if (message == WM_COMMAND && HIWORD(wparam) == BN_CLICKED) { + HWND progress = FindWindowExW(window, nullptr, L"HarnessInstallerProgress", nullptr); + auto* page = reinterpret_cast(GetWindowLongPtrW(progress, GWLP_USERDATA)); + HWND control = reinterpret_cast(lparam); + if (page && page->controlsVisible) { + // IsDialogMessage can route Enter to the outer NSIS dialog. + if (control && GetParent(control) == progress) + return SendMessageW(progress, WM_COMMAND, wparam, lparam); + if (LOWORD(wparam) == IDOK) { + RequestFinish(progress, *page, SendMessageW(page->launch, BM_GETCHECK, 0, 0) == BST_CHECKED); + return 0; + } + } + } if (message == WM_NCCALCSIZE && wparam) return 0; // Activation must not repaint the standard frame over the custom client area. if (message == WM_NCACTIVATE) return DefSubclassProc(window, message, wparam, -1); @@ -419,7 +555,9 @@ static LRESULT CALLBACK FrameProc(HWND window, UINT message, WPARAM wparam, // The installer has a fixed size; its page provides the drag area. return hit >= HTLEFT && hit <= HTBOTTOMRIGHT ? HTCLIENT : hit; } - if (message == WM_NCDESTROY) RemoveWindowSubclass(window, FrameProc, id); + if (message == WM_NCDESTROY) { + RemoveWindowSubclass(window, FrameProc, id); + } return DefSubclassProc(window, message, wparam, lparam); } diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 269e06a139..bb51e36dd7 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "private": true, "license": "MIT", "author": { diff --git a/apps/desktop/scripts/dev.ts b/apps/desktop/scripts/dev.ts index 37515c20b0..0753678c0a 100644 --- a/apps/desktop/scripts/dev.ts +++ b/apps/desktop/scripts/dev.ts @@ -10,6 +10,7 @@ import type { DesktopRelease } from '../src/release.ts' import { developmentRuntimeDirectory, resolveDesktopBuildTarget } from './desktop-build-paths.mjs' import { prepareDevelopmentProject } from './development-project.ts' import { prepareDevelopmentApp } from './development-app.ts' +import { prepareDevelopmentState } from './development-state.ts' import { preparePrimaryRuntime } from './prepare-primary-runtime.ts' const APP_ROOT = resolve(import.meta.dirname, '..') @@ -63,8 +64,7 @@ async function launchElectron(): Promise { const mainPort = debugPort('DSH_DESKTOP_MAIN_INSPECT_PORT', 9229) const rendererPort = debugPort('DSH_DESKTOP_RENDERER_DEBUG_PORT', 9222) const hostPort = debugPort('DSH_DESKTOP_HOST_INSPECT_PORT', 9230) - const home = resolve(process.env.DSH_HOME ?? join(DEVELOPMENT_ROOT, 'home')) - const userData = resolve(process.env.DSH_DESKTOP_USER_DATA_DIR ?? join(DEVELOPMENT_ROOT, 'electron-user-data')) + const { home, userData } = prepareDevelopmentState(APP_ROOT) const environment: NodeJS.ProcessEnv = { ...process.env, DSH_HOME: home, diff --git a/apps/desktop/scripts/development-state.ts b/apps/desktop/scripts/development-state.ts new file mode 100644 index 0000000000..6f5233d8fc --- /dev/null +++ b/apps/desktop/scripts/development-state.ts @@ -0,0 +1,69 @@ +/** Persistent Harness home and Electron browser data for unpackaged Desktop launches. */ +import { existsSync, mkdirSync, readlinkSync, renameSync } from 'node:fs' +import { join, resolve } from 'node:path' + +/** Development state locations selected for one launch. */ +export interface DevelopmentState { + readonly home: string + readonly userData: string +} + +function running(pid: number): boolean { + try { + process.kill(pid, 0) + return true + } catch (error) { + return error instanceof Error && 'code' in error && error.code === 'EPERM' + } +} + +/** Chromium links `SingletonLock` to `-` while a browser process owns the profile on macOS and Linux. */ +function profileInUse(userData: string): boolean { + let target: string + try { + target = readlinkSync(join(userData, 'SingletonLock')) + } catch (error) { + // A missing lock or a non-link lock file means no live owner records itself this way. + if (error instanceof Error && 'code' in error && (error.code === 'ENOENT' || error.code === 'EINVAL')) return false + throw error + } + const pid = /-(\d+)$/.exec(target)?.[1] + return pid !== undefined && running(Number(pid)) +} + +/** + * Resolve development state outside `.desktop-build`, which `pnpm run clean` removes. + * A default location that does not exist yet receives the state an earlier launcher left under + * `.desktop-build/development` unless a running Harness Dev still owns that browser profile; + * explicit `DSH_HOME` and `DSH_DESKTOP_USER_DATA_DIR` are used as given. + * @param appRoot - Desktop application directory. + * @param environment - Launch environment with optional location overrides. + * @returns Harness home and Electron user-data directories. + */ +export function prepareDevelopmentState(appRoot: string, environment: NodeJS.ProcessEnv = process.env): DevelopmentState { + const legacyRoot = join(appRoot, '.desktop-build', 'development') + const select = (override: string | undefined, name: string): string => { + if (override !== undefined) return resolve(override) + const path = join(appRoot, '.desktop-dev', name) + const legacy = join(legacyRoot, name) + if (!existsSync(path) && existsSync(legacy)) { + // POSIX renames a directory that a running process still writes, which would split its state. + if (profileInUse(join(legacyRoot, 'electron-user-data'))) { + throw new Error(`desktop development: a running Harness Dev still uses ${legacyRoot}; quit it and retry`) + } + try { + mkdirSync(join(appRoot, '.desktop-dev'), { recursive: true }) + renameSync(legacy, path) + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + throw new Error(`desktop development: cannot move ${legacy} to ${path}: ${reason}`, { cause: error }) + } + console.log(`desktop development: moved ${legacy} to ${path}`) + } + return path + } + return { + home: select(environment.DSH_HOME, 'home'), + userData: select(environment.DSH_DESKTOP_USER_DATA_DIR, 'electron-user-data'), + } +} diff --git a/apps/desktop/scripts/installer.nsh b/apps/desktop/scripts/installer.nsh index 219522f1ee..3c4b0f93ed 100644 --- a/apps/desktop/scripts/installer.nsh +++ b/apps/desktop/scripts/installer.nsh @@ -100,10 +100,11 @@ ManifestDPIAware true !macro customPageAfterChangeDir !define MUI_PAGE_CUSTOMFUNCTION_PRE InstallerBeforeInstall !define MUI_PAGE_CUSTOMFUNCTION_SHOW InstallerProgressShow + !define MUI_PAGE_CUSTOMFUNCTION_LEAVE InstallerProgressLeave !macroend !macro customFinishPage - Page custom InstallerFinish InstallerFinishLeave + ; The final instfiles page keeps its controls until the user dismisses it. !macroend ; Installation work publishes stage changes without disturbing the NSIS caller. diff --git a/apps/desktop/src/operation-history.ts b/apps/desktop/src/operation-history.ts index ca9584f79f..ef0cc6b370 100644 --- a/apps/desktop/src/operation-history.ts +++ b/apps/desktop/src/operation-history.ts @@ -1,9 +1,16 @@ /** Bounded, cancellable reads of Desktop-owned plugin operation history. */ -import { open } from 'node:fs/promises' +import type { BigIntStats } from 'node:fs' +import { open, type FileHandle } from 'node:fs/promises' import { join } from 'node:path' -import { setImmediate } from 'node:timers/promises' +import { setImmediate, setTimeout as wait } from 'node:timers/promises' import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic' +/** Windows reports these while another handle temporarily owns an otherwise readable file. */ +const WINDOWS_TRANSIENT_OPEN_ERRORS: ReadonlySet = new Set(['EACCES', 'EBUSY', 'EPERM']) +const WINDOWS_OPEN_RETRY_INITIAL_MS = 10 +const WINDOWS_OPEN_RETRY_MAX_MS = 40 +const WINDOWS_OPEN_RETRY_LIMIT = 4 + /** Resource budgets for auxiliary history collection, independent of basic crash report writing. */ export interface OperationHistoryReadLimits { readonly bytes: number @@ -15,7 +22,7 @@ export interface OperationHistoryReadLimits { export interface OperationHistoryReadResult { readonly records: readonly PluginOperationRecord[] readonly bytesRead: number - /** Distinct files from which at least one byte was read. */ + /** Owned history segments from which at least one byte was read. */ readonly filesRead: number readonly truncated: boolean readonly invalidRecords: number @@ -23,9 +30,53 @@ export interface OperationHistoryReadResult { readonly cancelled: boolean } +/** + * Exact two-name key for one file; BigInt stats keep a Windows 64-bit file ID at its + * value instead of the 53-bit Number form, where two adjacent IDs can coincide. + * @param info - Stats of the opened history segment. + * @returns Device and inode as one comparable string. + */ +function fileIdentity(info: BigIntStats): string { + return `${String(info.dev)}:${String(info.ino)}` +} + +/** Whether Windows reported temporary interference with opening a history segment. */ +function isTransientWindowsOpenError(error: unknown): boolean { + if (process.platform !== 'win32') return false + return WINDOWS_TRANSIENT_OPEN_ERRORS.has((error as NodeJS.ErrnoException | null)?.code ?? '') +} + +/** + * Open one segment, retrying the temporary Windows sharing and permission failures a scanner + * causes on a freshly written file. One persistent failure would otherwise drop the whole + * segment from the report. A signal aborted during the bounded wait ends the retries without + * another open. + * @param filename - Absolute path of the owned segment. + * @param signal - Caller-owned collection deadline or shutdown cancellation. + * @returns The opened read handle. + */ +async function openSegment(filename: string, signal: AbortSignal): Promise { + // A call keeps the post-wait check outside the catch's narrowing to the pre-wait value. + const aborted = (): boolean => signal.aborted + let delay = WINDOWS_OPEN_RETRY_INITIAL_MS + for (let retries = 0;; retries += 1) { + try { + return await open(filename, 'r') + } catch (error) { + if (!isTransientWindowsOpenError(error) || retries >= WINDOWS_OPEN_RETRY_LIMIT || aborted()) throw error + await wait(delay) + if (aborted()) throw error + delay = Math.min(delay * 2, WINDOWS_OPEN_RETRY_MAX_MS) + } + } +} + /** * Read only the bounded tails of the two owned history files, newest segment first. * Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing. + * A segment is deduplicated as already read when its handle reports the exact bigint identity of + * the segment already read; the predecessor is skipped, so its records are not collected twice and + * records appended to it after the read are not collected. * An already-issued OS read must settle before its handle closes. * @param directory - Desktop's operation history directory; unrelated files are never enumerated. * @param limits - Positive byte, record-size and record-count budgets. @@ -44,33 +95,35 @@ export async function readOperationHistory( const cancelled = (): boolean => signal.aborted const records: PluginOperationRecord[] = [] let bytesRead = 0 - const seenFiles = new Set() + let filesRead = 0 + let lastReadIdentity: string | undefined let truncated = false let invalidRecords = 0 let unavailableFiles = 0 for (const name of ['operations.jsonl', 'operations.previous.jsonl']) { if (cancelled()) break try { - await using handle = await open(join(directory, name), 'r') + await using handle = await openSegment(join(directory, name), signal) if (cancelled()) break - const fileStat = await handle.stat() + const fileStat = await handle.stat({ bigint: true }) if (cancelled()) break if (!fileStat.isFile()) { unavailableFiles++ continue } - const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}` - if (seenFiles.has(identity)) { + const identity = fileIdentity(fileStat) + const size = Number(fileStat.size) + if (lastReadIdentity !== undefined && identity === lastReadIdentity) { truncated = true continue } - if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) { + if (size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) { truncated = true break } - const readLength = Math.min(fileStat.size, limits.bytes - bytesRead) - const readStart = fileStat.size - readLength + const readLength = Math.min(size, limits.bytes - bytesRead) + const readStart = size - readLength const buffer = Buffer.alloc(readLength) let readOffset = 0 while (readOffset < readLength && !cancelled()) { @@ -79,7 +132,10 @@ export async function readOperationHistory( if (read.bytesRead === 0) break readOffset += read.bytesRead } - if (readOffset > 0) seenFiles.add(identity) + if (readOffset > 0) { + filesRead++ + lastReadIdentity = identity + } if (cancelled()) break truncated ||= readStart > 0 || readOffset < readLength @@ -116,5 +172,5 @@ export async function readOperationHistory( if ((error as NodeJS.ErrnoException).code !== 'ENOENT') unavailableFiles++ } } - return { records, bytesRead, filesRead: seenFiles.size, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() } + return { records, bytesRead, filesRead, truncated, invalidRecords, unavailableFiles, cancelled: cancelled() } } diff --git a/apps/desktop/tests/development-state.spec.ts b/apps/desktop/tests/development-state.spec.ts new file mode 100644 index 0000000000..b7e42bd0d2 --- /dev/null +++ b/apps/desktop/tests/development-state.spec.ts @@ -0,0 +1,75 @@ +/** Development launches keep Harness state where repository cleaning does not remove it. */ +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { expect, it, onTestFinished, vi } from 'vitest' +import { prepareDevelopmentState } from '../scripts/development-state.ts' + +function fixture(): string { + const root = mkdtempSync(join(tmpdir(), 'dsh-development-state-')) + onTestFinished(() => { rmSync(root, { recursive: true, force: true }) }) + return root +} + +it('moves state from .desktop-build into the default development state directory', () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + onTestFinished(() => { vi.restoreAllMocks() }) + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + writeFileSync(join(legacy, 'home', 'session.jsonl'), 'session') + + const state = prepareDevelopmentState(root, {}) + + expect(state).toEqual({ home: join(root, '.desktop-dev', 'home'), userData: join(root, '.desktop-dev', 'electron-user-data') }) + expect(readFileSync(join(state.home, 'session.jsonl'), 'utf8')).toBe('session') + expect(existsSync(state.userData)).toBe(true) + expect(existsSync(join(legacy, 'home'))).toBe(false) +}) + +it('keeps existing default state and leaves legacy state in place', () => { + const root = fixture() + mkdirSync(join(root, '.desktop-dev', 'home'), { recursive: true }) + mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true }) + + expect(prepareDevelopmentState(root, {}).home).toBe(join(root, '.desktop-dev', 'home')) + expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true) +}) + +it('moves only the default directory that is missing', () => { + vi.spyOn(console, 'log').mockImplementation(() => {}) + onTestFinished(() => { vi.restoreAllMocks() }) + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + + const state = prepareDevelopmentState(root, { DSH_HOME: join(root, 'h') }) + + expect(state).toEqual({ home: join(root, 'h'), userData: join(root, '.desktop-dev', 'electron-user-data') }) + expect(existsSync(state.userData)).toBe(true) + expect(existsSync(join(legacy, 'home'))).toBe(true) +}) + +it('uses explicit locations without moving legacy state', () => { + const root = fixture() + mkdirSync(join(root, '.desktop-build', 'development', 'home'), { recursive: true }) + + expect(prepareDevelopmentState(root, { DSH_HOME: join(root, 'h'), DSH_DESKTOP_USER_DATA_DIR: join(root, 'u') })) + .toEqual({ home: join(root, 'h'), userData: join(root, 'u') }) + expect(existsSync(join(root, '.desktop-build', 'development', 'home'))).toBe(true) + expect(existsSync(join(root, '.desktop-dev'))).toBe(false) +}) + +it.skipIf(process.platform === 'win32')('does not move state that a running Harness Dev still owns', () => { + const root = fixture() + const legacy = join(root, '.desktop-build', 'development') + mkdirSync(join(legacy, 'home'), { recursive: true }) + mkdirSync(join(legacy, 'electron-user-data')) + symlinkSync(`host-${String(process.pid)}`, join(legacy, 'electron-user-data', 'SingletonLock')) + + expect(() => prepareDevelopmentState(root, {})).toThrow('a running Harness Dev still uses') + expect(existsSync(join(legacy, 'home'))).toBe(true) + expect(existsSync(join(root, '.desktop-dev'))).toBe(false) +}) diff --git a/apps/desktop/tests/expected/windows-installer.json b/apps/desktop/tests/expected/windows-installer.json index c10dcfac9a..182292b9d1 100644 --- a/apps/desktop/tests/expected/windows-installer.json +++ b/apps/desktop/tests/expected/windows-installer.json @@ -8,6 +8,7 @@ "welcome-ready-before-first-show", "welcome-presented-on-first-show", "successful-install-paints-100-before-finish", + "completion-close-exits-without-launch", "locked-directory-shows-error-and-copy-control-and-preserves-installation", "registered-directory-with-trailing-separators", "registered-directory-and-checked-launch", diff --git a/apps/desktop/tests/operation-history.spec.ts b/apps/desktop/tests/operation-history.spec.ts index 237287d5b0..ba20897a17 100644 --- a/apps/desktop/tests/operation-history.spec.ts +++ b/apps/desktop/tests/operation-history.spec.ts @@ -1,7 +1,8 @@ -import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises' +import { appendFile, mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises' +import type { BigIntStats, StatOptions, Stats } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { expect, it, onTestFinished, vi } from 'vitest' +import { beforeEach, expect, it, onTestFinished, vi } from 'vitest' import { readOperationHistory } from '../src/operation-history.ts' vi.mock('node:fs/promises', async (importOriginal) => { @@ -10,6 +11,7 @@ vi.mock('node:fs/promises', async (importOriginal) => { }) const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 } +beforeEach(() => { vi.mocked(open).mockClear() }) function record(id: string | number) { return { runId: 'c254ab28-97c9-4382-95e6-2db9c66f98c8', transportDropped: 0, operation: { id: 'c254ab28-97c9-4382-95e6-2db9c66f98c9', time: '2026-10-19T00:00:00.000Z', @@ -25,11 +27,183 @@ async function fixture() { it('collects recent complete records and reports malformed and incomplete entries', async () => { const path = await fixture() - await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":') + const current = line(1) + '{broken}\n' + line(2) + '{"incomplete":' + await writeFile(join(path, 'operations.jsonl'), current) await writeFile(join(path, 'operations.previous.jsonl'), line(0)) const result = await readOperationHistory(path, limits, new AbortController().signal) - expect(result.records).toEqual([record(2), record(1), record(0)]) - expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 }) + // The whole result is asserted so a missing record also names the collection facts that caused it. + expect(result).toEqual({ + records: [record(2), record(1), record(0)], + bytesRead: Buffer.byteLength(current) + Buffer.byteLength(line(0)), + filesRead: 2, + truncated: true, + invalidRecords: 1, + unavailableFiles: 0, + cancelled: false, + }) +}) + +it('does not collect a rotated predecessor twice after it was appended', async () => { + const path = await fixture() + const current = join(path, 'operations.jsonl') + const previous = join(path, 'operations.previous.jsonl') + await writeFile(current, line(1)) + const actualFs = await vi.importActual('node:fs/promises') + const handle = await open(current, 'r') + const opener = vi.mocked(open).mockClear() + .mockImplementationOnce(async () => handle) + .mockImplementationOnce(async () => { + // The writer appends one record, then rotates: both names still denote one file. + await appendFile(current, line(2)) + await rename(current, previous) + await writeFile(current, line(3)) + return actualFs.open(previous, 'r') + }) + try { + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result).toMatchObject({ filesRead: 1, truncated: true, unavailableFiles: 0 }) + } finally { + opener.mockClear() + } +}) + +it('compares exact bigint identities so two nearby Numbers cannot collapse one segment', async () => { + const path = await fixture() + const current = join(path, 'operations.jsonl') + const previous = join(path, 'operations.previous.jsonl') + const currentText = line('current') + const previousText = line('old') + await writeFile(current, currentText) + await writeFile(previous, previousText) + const currentHandle = await open(current, 'r') + const previousHandle = await open(previous, 'r') + onTestFinished(async () => { await currentHandle.close(); await previousHandle.close() }) + const currentStat = await currentHandle.stat({ bigint: true }) + const previousStat = await previousHandle.stat({ bigint: true }) + const currentNumberStat = await currentHandle.stat() + const previousNumberStat = await previousHandle.stat() + // Adjacent 64-bit file IDs: distinct as bigints, one Number after the 53-bit mantissa. + const base = 2n ** 58n + 1000n + currentStat.dev = 0n + currentStat.ino = base + previousStat.dev = 0n + previousStat.ino = base + 1n + currentNumberStat.dev = 0 + currentNumberStat.ino = Number(base) + previousNumberStat.dev = 0 + previousNumberStat.ino = Number(base + 1n) + expect(currentNumberStat.ino).toBe(previousNumberStat.ino) + const optionAware = (exact: BigIntStats, numeric: Stats) => + async (options?: StatOptions): Promise => options?.bigint === true ? exact : numeric + const currentStats = vi.spyOn(currentHandle, 'stat').mockImplementation(optionAware(currentStat, currentNumberStat)) + const previousStats = vi.spyOn(previousHandle, 'stat').mockImplementation(optionAware(previousStat, previousNumberStat)) + const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(currentHandle).mockResolvedValueOnce(previousHandle) + try { + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record('current'), record('old')]) + expect(result).toMatchObject({ filesRead: 2, unavailableFiles: 0, truncated: false }) + } finally { + currentStats.mockRestore() + previousStats.mockRestore() + opener.mockClear() + } +}) + +it('retries transient Windows sharing failures while opening a segment', async () => { + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const actualFs = await vi.importActual('node:fs/promises') + const opener = vi.mocked(open) + onTestFinished(async () => { + platform.mockRestore() + opener.mockReset().mockImplementation(actualFs.open) + }) + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(2)) + await writeFile(join(path, 'operations.previous.jsonl'), line(1)) + opener.mockRejectedValueOnce(Object.assign(new Error('sharing violation'), { code: 'EBUSY' })) + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(2), record(1)]) + expect(result.unavailableFiles).toBe(0) + expect(opener).toHaveBeenCalledTimes(3) +}) + +it('counts a segment unavailable after bounded Windows open retries expire', async () => { + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const actualFs = await vi.importActual('node:fs/promises') + const opener = vi.mocked(open) + onTestFinished(async () => { + platform.mockRestore() + opener.mockReset().mockImplementation(actualFs.open) + }) + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(2)) + await writeFile(join(path, 'operations.previous.jsonl'), line(1)) + for (let attempt = 0; attempt <= 4; attempt++) { + opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' })) + } + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result.unavailableFiles).toBe(1) + expect(opener).toHaveBeenCalledTimes(6) +}) + +it('does not retry a Windows transient code outside Windows', async () => { + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux') + const actualFs = await vi.importActual('node:fs/promises') + const opener = vi.mocked(open) + onTestFinished(async () => { + platform.mockRestore() + opener.mockReset().mockImplementation(actualFs.open) + }) + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(2)) + await writeFile(join(path, 'operations.previous.jsonl'), line(1)) + opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' })) + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result.unavailableFiles).toBe(1) + expect(opener).toHaveBeenCalledTimes(2) +}) + +it('stops Windows open retries when the collection is already cancelled', async () => { + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const actualFs = await vi.importActual('node:fs/promises') + const opener = vi.mocked(open) + onTestFinished(async () => { + platform.mockRestore() + opener.mockReset().mockImplementation(actualFs.open) + }) + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(2)) + const controller = new AbortController() + opener.mockImplementationOnce(async () => { + controller.abort() + throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' }) + }) + const result = await readOperationHistory(path, limits, controller.signal) + expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 }) + expect(opener).toHaveBeenCalledTimes(1) +}) + +it('stops Windows open retries when cancellation lands during the retry wait', async () => { + const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32') + const actualFs = await vi.importActual('node:fs/promises') + const opener = vi.mocked(open) + onTestFinished(async () => { + platform.mockRestore() + opener.mockReset().mockImplementation(actualFs.open) + }) + const path = await fixture() + await writeFile(join(path, 'operations.jsonl'), line(2)) + const controller = new AbortController() + opener.mockImplementationOnce(async () => { + setImmediate(() => { controller.abort() }) + throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' }) + }) + const result = await readOperationHistory(path, limits, controller.signal) + expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 }) + expect(opener).toHaveBeenCalledTimes(1) }) it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => { @@ -159,6 +333,27 @@ it('does not collect the same open segment twice when it rotates during collecti } }) +it('does not re-collect a rotated segment while the current path is briefly absent', async () => { + const path = await fixture() + const current = join(path, 'operations.jsonl') + await writeFile(current, line(1)) + const handle = await open(current, 'r') + onTestFinished(async () => { await handle.close() }) + const opener = vi.mocked(open).mockClear().mockImplementationOnce(async () => { + await rename(current, join(path, 'operations.previous.jsonl')) + return handle + }) + try { + const result = await readOperationHistory(path, limits, new AbortController().signal) + expect(result.records).toEqual([record(1)]) + expect(result).toMatchObject({ filesRead: 1, truncated: true }) + expect(handle.fd).toBe(-1) + } finally { + opener.mockClear() + await handle.close() + } +}) + it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => { const path = await fixture() const current = line(1) diff --git a/apps/desktop/tests/windows-installer-progress.cpp b/apps/desktop/tests/windows-installer-progress.cpp index 6bd3de2923..e9417ad7b9 100644 --- a/apps/desktop/tests/windows-installer-progress.cpp +++ b/apps/desktop/tests/windows-installer-progress.cpp @@ -65,6 +65,8 @@ int main() { progress.Complete(done); double previous = progress.value; for (std::uint64_t elapsed = 0; elapsed < 600; elapsed += 16) { + // A repeated completion notification must not restart the final animation. + if (elapsed == 320) progress.Complete(done + elapsed); progress.Advance(4, 1, done + elapsed); assert(progress.value >= previous && progress.value < 100); previous = progress.value; diff --git a/apps/desktop/tests/windows-installer-render.cpp b/apps/desktop/tests/windows-installer-render.cpp index 8d9d8ef91e..afb38cfc09 100644 --- a/apps/desktop/tests/windows-installer-render.cpp +++ b/apps/desktop/tests/windows-installer-render.cpp @@ -11,9 +11,67 @@ extern "C" __declspec(dllimport) HRESULT __cdecl InstallerApplyFrame(HWND window extern "C" __declspec(dllimport) HWND __cdecl InstallerShowProgress(HWND parent, HWND source, BOOL dark, UINT dpi, DWORD controlHover, DWORD controlPressed, const WCHAR* brand, const WCHAR* preparing, const WCHAR* extracting, const WCHAR* copying, const WCHAR* registering, const WCHAR* cleaning); -extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window); +extern "C" __declspec(dllimport) BOOL __cdecl InstallerFinishProgress(HWND window, const WCHAR* finish, const WCHAR* launch); +extern "C" __declspec(dllimport) int __cdecl InstallerTakeFinishChoice(HWND window); + +struct CompletionProbe { + HWND progress; + ULONGLONG deadline; + RECT bounds; + bool requested = false; + bool completedDuringMove = false; +}; + +static void PollCompletion(HWND window, CompletionProbe& probe) { + const HWND finish = FindWindowExW(probe.progress, nullptr, L"Button", L"Finish"); + const HWND launch = FindWindowExW(probe.progress, nullptr, L"Button", L"Launch"); + if (finish && launch && IsWindowVisible(finish) && IsWindowVisible(launch)) { + GUITHREADINFO input{sizeof(input)}; + RECT current; + probe.completedDuringMove = GetGUIThreadInfo(GetCurrentThreadId(), &input) + && input.hwndMoveSize == window && GetWindowRect(window, ¤t) + && EqualRect(¤t, &probe.bounds) && IsWindowEnabled(finish) + && SendMessageW(launch, BM_GETCHECK, 0, 0) == BST_CHECKED + && GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast(100); + } else if (GetTickCount64() < probe.deadline) { + return; + } + SendMessageW(window, WM_CANCELMODE, 0, 0); +} + +static bool CompleteWhileMinimized(HWND window, HWND progress) { + ShowWindow(window, SW_MINIMIZE); + const HWND foreground = GetForegroundWindow(); + if (!IsIconic(window) || !InstallerFinishProgress(progress, L"Finish", L"Launch")) return false; + const ULONGLONG deadline = GetTickCount64() + 5000; + while (GetTickCount64() < deadline) { + const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish"); + if (finish && IsWindowVisible(finish)) { + return IsIconic(window) && (foreground == window || GetForegroundWindow() != window) + && GetPropW(window, L"HarnessInstaller.Succeeded") != nullptr; + } + MSG message; + while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) DispatchMessageW(&message); + MsgWaitForMultipleObjectsEx(0, nullptr, 16, QS_ALLINPUT, MWMO_INPUTAVAILABLE); + } + return false; +} static LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + auto* probe = reinterpret_cast(GetWindowLongPtrW(window, GWLP_USERDATA)); + if (probe && message == WM_ENTERSIZEMOVE) { + GetWindowRect(window, &probe->bounds); + PostMessageW(window, WM_APP, 0, 0); + } + if (probe && message == WM_APP) { + probe->requested = InstallerFinishProgress(probe->progress, L"Finish", L"Launch") != FALSE; + if (!probe->requested || !SetTimer(window, 1, 16, nullptr)) SendMessageW(window, WM_CANCELMODE, 0, 0); + return 0; + } + if (probe && message == WM_TIMER && wparam == 1) { + PollCompletion(window, *probe); + return 0; + } if (message == WM_DESTROY) { PostQuitMessage(0); return 0; } return DefWindowProcW(window, message, wparam, lparam); } @@ -68,10 +126,12 @@ int wmain(int argc, wchar_t** argv) { HWND warmup = createProgress(); if (!warmup) { DestroyWindow(window); return 5; } UpdateWindow(warmup); - ShowWindow(window, SW_MINIMIZE); + const bool minimizedCompletion = CompleteWhileMinimized(window, warmup); ShowWindow(window, SW_RESTORE); UpdateWindow(warmup); DestroyWindow(warmup); + RemovePropW(window, L"HarnessInstaller.CompletedPercent"); + RemovePropW(window, L"HarnessInstaller.Succeeded"); const DWORD initialGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); HWND progress = createProgress(); if (!progress) { DestroyWindow(window); return 5; } @@ -124,14 +184,15 @@ int wmain(int argc, wchar_t** argv) { }; bool captionStates = true; ShowWindow(progress, SW_HIDE); - for (int x : {504, 548}) { + { + constexpr int x = 504; const LPARAM point = MAKELPARAM(MulDiv(x + 20, dpi, 96), MulDiv(24, dpi, 96)); captionStates = expectPixel(x, normalColor) && captionStates; SendMessageW(progress, WM_MOUSEMOVE, 0, point); captionStates = expectPixel(x, hoverColor) && captionStates; SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, point); captionStates = expectPixel(x, pressedColor) && captionStates; - const int other = x == 504 ? 548 : 504; + constexpr int other = 548; SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, MAKELPARAM(MulDiv(other + 20, dpi, 96), MulDiv(24, dpi, 96))); captionStates = expectPixel(other, normalColor) && captionStates; captionStates = expectPixel(x, normalColor) && captionStates; @@ -167,12 +228,15 @@ int wmain(int argc, wchar_t** argv) { const LPARAM closePoint = MAKELPARAM(MulDiv(568, dpi, 96), MulDiv(24, dpi, 96)); MSG closeMessage; SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint); - bool closeRelease = !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE); + bool closeDisabled = GetCapture() != progress && expectPixel(548, normalColor) + && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE); + SendMessageW(progress, WM_MOUSEMOVE, MK_LBUTTON, closePoint); + closeDisabled = closeDisabled && expectPixel(548, normalColor); SendMessageW(progress, WM_LBUTTONUP, 0, minimizePoint); - closeRelease = closeRelease && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE); + closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE); SendMessageW(progress, WM_LBUTTONDOWN, MK_LBUTTON, closePoint); SendMessageW(progress, WM_LBUTTONUP, 0, closePoint); - closeRelease = closeRelease && PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE); + closeDisabled = closeDisabled && !PeekMessageW(&closeMessage, window, WM_CLOSE, WM_CLOSE, PM_REMOVE) && GetCapture() != progress; LARGE_INTEGER frequency, started, finished; QueryPerformanceFrequency(&frequency); std::vector samples; @@ -196,15 +260,45 @@ int wmain(int argc, wchar_t** argv) { std::printf("fixture=standalone-progress dpi=%d dark=%d frames=%d screen=%dx%d foreground=%d mean_ms=%.3f p50_ms=%.3f p95_ms=%.3f max_ms=%.3f\n", dpi, dark, frameCount, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), GetForegroundWindow() == window, total / samples.size(), samples[samples.size() / 2], samples[samples.size() * 95 / 100], samples.back()); - const bool completed = InstallerFinishProgress(progress) && - GetPropW(window, L"HarnessInstaller.CompletedPercent") == reinterpret_cast(100); - WCHAR caption[160] = {}; - GetWindowTextW(progress, caption, ARRAYSIZE(caption)); - const bool finalCaption = wcscmp(caption, L"Extracting 100%") == 0; + CompletionProbe probe{progress, GetTickCount64() + 5000, {}}; + POINT originalCursor{}; + const bool restoreCursor = GetCursorPos(&originalCursor) != FALSE; + SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast(&probe)); + SendMessageW(window, WM_SYSCOMMAND, SC_MOVE, 0); + if (restoreCursor) SetCursorPos(originalCursor.x, originalCursor.y); + KillTimer(window, 1); + SetWindowLongPtrW(window, GWLP_USERDATA, 0); + const bool completed = probe.requested && probe.completedDuringMove; + bool finishActions = completed && InstallerTakeFinishChoice(progress) == -1; + bool finishInTabOrder = false, launchInTabOrder = false; + if (finishActions) { + const HWND finish = FindWindowExW(progress, nullptr, L"Button", L"Finish"); + const HWND launch = FindWindowExW(progress, nullptr, L"Button", L"Launch"); + const HWND close = FindWindowExW(progress, nullptr, L"Button", L"\x00d7"); + const HWND first = GetNextDlgTabItem(window, nullptr, FALSE); + HWND tab = first; + for (int next = 0; tab && next < 4; ++next) { + finishInTabOrder |= tab == finish; + launchInTabOrder |= tab == launch; + tab = GetNextDlgTabItem(window, tab, FALSE); + if (tab == first) break; + } + SendMessageW(finish, BM_CLICK, 0, 0); + finishActions = InstallerTakeFinishChoice(progress) == 1 && InstallerTakeFinishChoice(progress) == -1; + SendMessageW(close, BM_CLICK, 0, 0); + finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0; + SendMessageW(launch, BM_CLICK, 0, 0); + SendMessageW(window, WM_COMMAND, MAKEWPARAM(IDOK, BN_CLICKED), 0); + finishActions = finishActions && InstallerTakeFinishChoice(progress) == 0; + } DestroyWindow(progress); const DWORD finalGdi = GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS); DestroyWindow(window); - std::printf("client_frame=%d stock_preserved=%d completed=%d final_caption=%d caption_states=%d button_release=%d close_release=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n", - clientFrame, failurePreservesStock, completed, finalCaption, captionStates, buttonRelease, closeRelease, minimized, restored, initialGdi, finalGdi); - return clientFrame && failurePreservesStock && completed && finalCaption && captionStates && buttonRelease && closeRelease && minimized && restored && finalGdi <= initialGdi ? 0 : 6; + std::printf("client_frame=%d stock_preserved=%d completed_during_move=%d caption_states=%d button_release=%d close_disabled=%d minimized=%d restored=%d gdi_before=%lu gdi_after=%lu\n", + clientFrame, failurePreservesStock, completed, captionStates, buttonRelease, closeDisabled, minimized, restored, initialGdi, finalGdi); + std::printf("minimized_completion=%d finish_actions=%d finish_tab=%d launch_tab=%d\n", + minimizedCompletion, finishActions, finishInTabOrder, launchInTabOrder); + return clientFrame && failurePreservesStock && completed && minimizedCompletion && finishActions + && finishInTabOrder && launchInTabOrder && captionStates && buttonRelease && closeDisabled + && minimized && restored && finalGdi <= initialGdi ? 0 : 6; } diff --git a/apps/desktop/tests/windows-installer-smoke.ps1 b/apps/desktop/tests/windows-installer-smoke.ps1 index ea917263b9..ea061c8356 100644 --- a/apps/desktop/tests/windows-installer-smoke.ps1 +++ b/apps/desktop/tests/windows-installer-smoke.ps1 @@ -157,6 +157,14 @@ try { $results.Add('welcome-ready-before-first-show') $results.Add('successful-install-paints-100-before-finish') + $process = Start-Setup light + Click-Control $process $copy.INSTALLER_INSTALL + [void](Wait-Control $process $copy.INSTALLER_FINISH) + Click-Control $process ([string][char]0xD7) + if (-not $process.WaitForExit(10000) -or $process.ExitCode -ne 0) { throw 'Completion close did not exit successfully' } + if (Test-Path -LiteralPath (Join-Path $installPath 'launched.txt')) { throw 'Completion close launched the application' } + $results.Add('completion-close-exits-without-launch') + $lockedFile = [IO.File]::Open($appPath, 'Open', 'Read', 'Read') try { $process = Start-Setup light diff --git a/apps/plugin-market-generator/package.json b/apps/plugin-market-generator/package.json index 1378585bf9..77eb12e8cd 100644 --- a/apps/plugin-market-generator/package.json +++ b/apps/plugin-market-generator/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market-generator", "description": "Reference generator of plugin market index files from a list of npm packages and Git repositories", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "private": true, "type": "module", "scripts": { diff --git a/apps/web/package.json b/apps/web/package.json index edd7bb580a..1c07f6cbee 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-frontend", "description": "Web application entry: vite build over the @deepseek-ai/dsh-client-web shell library; dist/ served by apps/cli's dsh web", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index bd4f463f3b..3957b28a75 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -82,7 +82,11 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' await dialog.getByRole('button', { name: '模型', exact: true }).click() const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true }) await edit.click() - const key = dialog.getByLabel('API 密钥', { exact: true }) + // This row's card alone. Between the credential delete and the profile + // write that restores native auth, google's row reports no usable + // provider and the page mounts the DeepSeek first-run setup card, whose + // key field would answer a dialog-wide count. + const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true }) await key.press('Delete') expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor() @@ -94,7 +98,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' await edit.click() await key.press('Delete') await dialog.getByRole('button', { name: '保存', exact: true }).click() - await expect.poll(() => key.count()).toBe(0) + await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0) await generate() expect(calls).toHaveLength(2) expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key') @@ -134,7 +138,9 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki await dialog.getByRole('button', { name: '模型', exact: true }).click() const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }) await edit.click() - const key = dialog.getByLabel('API 密钥', { exact: true }) + // This row's card alone: the dialog can show another provider's card, + // with its own key field, beside this row. + const key = edit.locator('xpath=ancestor::li').getByLabel('API 密钥', { exact: true }) expect(await key.getAttribute('placeholder')).toBe(`fixture-prote${'•'.repeat(8)}-key`) expect(await key.inputValue()).toBe('') expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) @@ -155,7 +161,12 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki await expect.poll(() => key.inputValue()).toBe('') await key.fill('fixture-new-key') await dialog.getByRole('button', { name: '保存', exact: true }).click() - await expect.poll(() => key.count()).toBe(0) + // The editor closes before the save's reload lands, and an Edit press + // while the settings snapshot is loading is dropped. The saved notice is + // published by that reload's completion, so waiting for it also makes the + // reopen below deterministic. + await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor() + await expect.poll(() => key.count(), { timeout: 10_000 }).toBe(0) await edit.click() expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length)) expect(await key.inputValue()).toBe('') diff --git a/apps/web/tests/expected/plugin-manager/terminal.expected.md b/apps/web/tests/expected/plugin-manager/terminal.expected.md new file mode 100644 index 0000000000..d7b7b99036 --- /dev/null +++ b/apps/web/tests/expected/plugin-manager/terminal.expected.md @@ -0,0 +1,5 @@ +- listitem: + - button "查看 持久终端": 持久终端 + - text: 实验性 为智能体提供以侧栏标签页打开的终端,你可以旁观,也可以直接在其中键入来接管。进程在多次工具调用之间持续运行,因此它可以启动开发服务器或 REPL,稍后再读取输出;它也能读取你自己打开的终端。 + - status + - switch "启用 持久终端" diff --git a/apps/web/tests/feishu-connection.e2e.ts b/apps/web/tests/feishu-connection.e2e.ts new file mode 100644 index 0000000000..fec80f5b04 --- /dev/null +++ b/apps/web/tests/feishu-connection.e2e.ts @@ -0,0 +1,144 @@ +// Feishu setup failures and recovery through the real Host/Remote/browser composition. +// A stand-in CLI waits for each authorization page visit and keeps account state on disk. +import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const FEISHU_DIR = fileURLToPath(new URL('../../../packages/connector/feishu', import.meta.url)) +const SETUP_URL = 'https://open.feishu.cn/page/cli?e2e=1' +const SETUP_RETRY_URL = `${SETUP_URL}&retry=1` +const SIGN_IN_URL = 'https://accounts.feishu.cn/oauth/device?e2e=1' + +// The stand-in keeps its account in state.json beside itself; app setup and +// sign-in wait until the test marks their page visited. +const LARK_CLI = `#!/usr/bin/env node +const { existsSync, readFileSync, writeFileSync } = require('node:fs') +const { join } = require('node:path') +const dir = __dirname +const statePath = join(dir, 'state.json') +const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { app: false, user: false } +const save = () => { writeFileSync(statePath, JSON.stringify(state)) } +const visited = (name, done) => { + const poll = setInterval(() => { + if (!existsSync(join(dir, name))) return + clearInterval(poll) + done() + }, 50) +} +const line = (value) => { process.stdout.write(JSON.stringify(value) + '\\n') } +switch (process.argv.slice(2).join(' ')) { + case 'auth status --verify --json': + if (!state.app) { + process.stderr.write(JSON.stringify({ ok: false, error: { type: 'config', subtype: 'not_configured' } })) + process.exitCode = 3 + } else if (!state.user) line({ appId: 'cli_e2e', identities: { user: { status: 'missing', available: false } } }) + else line({ appId: 'cli_e2e', identities: { user: { status: 'ready', available: true, verified: true, userName: '测试用户', openId: 'ou_e2e' } } }) + break + case 'config init --new': + process.stderr.write('Open this link to create an app:\\n ' + (existsSync(join(dir, 'setup-fails')) ? '${SETUP_URL}' : '${SETUP_RETRY_URL}') + '\\n') + visited('setup-visited', () => { + if (existsSync(join(dir, 'setup-fails'))) { + process.stderr.write('OK: App configured!\\n' + JSON.stringify({ ok: false, error: { + type: 'internal', subtype: 'sdk_error', + message: 'keychain Set failed: /private/user/appsecret.enc.tmp: operation not permitted; token=fixture-secret', + hint: 'https://open.feishu.cn/page/cli?user_code=fixture-code', + } }, null, 2) + '\\n') + process.exitCode = 5 + } else { state.app = true; save() } + }) + break + case 'auth login --json': + line({ event: 'device_authorization', verification_uri_complete: '${SIGN_IN_URL}' }) + visited('sign-in-visited', () => { state.user = true; save(); line({ event: 'authorization_complete', user_open_id: 'ou_e2e', missing: [] }) }) + break + case 'auth logout --json': state.user = false; save(); line({ ok: true }); break + default: + process.stderr.write('unexpected lark-cli arguments: ' + process.argv.slice(2).join(' ') + '\\n') + process.exitCode = 1 +} +` + +// The stand-in runs through its shebang, which Windows cannot execute. +describe.skipIf(process.platform === 'win32')('web e2e: Feishu plugin connection', () => { + let binDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + binDir = await mkdtemp(join(tmpdir(), 'dsh-feishu-e2e-')) + await writeFile(join(binDir, 'lark-cli'), LARK_CLI) + await chmod(join(binDir, 'lark-cli'), 0o755) + const overlay = join(binDir, 'feishu.overlay.yml') + await writeFile(overlay, `- id: feishu\n config:\n binDir: ${JSON.stringify(binDir)}\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: FEISHU_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + for (const [url, marker] of [[SETUP_URL, 'setup-visited'], [SETUP_RETRY_URL, 'setup-visited'], [SIGN_IN_URL, 'sign-in-visited']] as const) { + await context.route(url, async (route) => { + await writeFile(join(binDir, marker), '') + await route.fulfill({ contentType: 'text/html; charset=utf-8', body: 'Feishu

Feishu stand-in page

' }) + }) + } + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (binDir !== undefined) await rm(binDir, { recursive: true, force: true }) + }) + + it('reports failed local setup, then links an existing app, signs in, and signs out', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-feishu-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 飞书插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-feishu"]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2) + + const opened: Page[] = [] + context.on('page', (popup) => { opened.push(popup) }) + await writeFile(join(binDir, 'setup-fails'), '') + await section.getByRole('button', { name: '关联飞书应用', exact: true }).click() + await section.getByRole('alert').waitFor({ timeout: 20_000 }) + expect(await section.getAttribute('data-connector-account')).toBe('disconnected') + expect(await section.getByRole('alert').innerText()).toContain('config-init · exit 5') + expect(await section.getByRole('alert').innerText()).toContain('已有应用') + expect(await section.innerText()).not.toContain('fixture-secret') + expect(await section.innerText()).not.toContain('fixture-code') + expect(await section.innerText()).not.toContain('/private/user') + await expect(readFile(join(binDir, 'state.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' }) + await rm(join(binDir, 'setup-fails')) + await rm(join(binDir, 'setup-visited')) + await section.getByRole('button', { name: '关联飞书应用', exact: true }).click() + await page.getByText('飞书应用已关联,下一步登录飞书账号', { exact: true }).waitFor({ timeout: 20_000 }) + expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL]) + await section.getByRole('button', { name: '登录飞书账号', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SETUP_RETRY_URL, SIGN_IN_URL]) + await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用飞书。', { exact: true }).waitFor({ timeout: 10_000 }) + await page.getByText('飞书已连接', { exact: true }).waitFor({ timeout: 10_000 }) + + await section.getByRole('button', { name: '退出登录', exact: true }).click() + await page.getByRole('dialog', { name: '退出飞书登录?' }).getByRole('button', { name: '退出登录', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + await page.getByText('已退出飞书登录', { exact: true }).waitFor({ timeout: 10_000 }) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 502e64ea33..df85abc053 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -1142,6 +1142,14 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd), MODE) expect((await readPersistedEvents(scaffold, sessionId)).some(event => event.type === 'user/message' && event.data.content.some(block => block.type === 'text' && block.text.includes('## User Comment')))).toBe(false) + // Removing a reference card leaves its quote in the composer, and the notice's Undo puts the card back at its line. + const extra = local.locator('[data-forge-diff-file="src/extra.ts"]') + await extra.getByRole('button', { name: '评论 R1 的操作', exact: true }).click() + await page.getByRole('menuitem', { name: '移除', exact: true }).click() + await expect.poll(() => extra.locator('[data-forge-review-thread]').count()).toBe(0) + expect(await page.locator('[data-composer-input]').first().innerText()).toContain('请检查这项修改') + await page.getByRole('alert').filter({ hasText: '已移除' }).getByRole('button', { name: '撤销', exact: true }).click() + await extra.locator('[data-forge-review-thread="agent"]').getByText('请检查这项修改', { exact: true }).waitFor() const reviewed = scaffold.whenTurnSettled() await page.locator('[data-composer-input]').first().press('Enter') await reviewed diff --git a/apps/web/tests/linear-connection.e2e.ts b/apps/web/tests/linear-connection.e2e.ts new file mode 100644 index 0000000000..25f3b1f6a7 --- /dev/null +++ b/apps/web/tests/linear-connection.e2e.ts @@ -0,0 +1,77 @@ +// Web e2e scenario: connecting the Linear plugin from its page on the Plugins +// page. The section reads the MCP manager's real entry, the browser opens the +// loopback authorization server's page, the Host callback answers with its +// completion page, the connection reaches the manager, and sign-out returns the +// section to disconnected. Zero model calls. +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { startLinearOAuthFixture, type LinearOAuthFixture } from './linear-oauth-fixture.ts' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const LINEAR_DIR = fileURLToPath(new URL('../../../packages/connector/linear', import.meta.url)) + +describe('web e2e: Linear plugin connection', () => { + let fixture: LinearOAuthFixture + let overlayDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + fixture = await startLinearOAuthFixture() + overlayDir = await mkdtemp(join(tmpdir(), 'dsh-linear-e2e-')) + const overlay = join(overlayDir, 'linear.overlay.yml') + await writeFile(overlay, `- id: linear\n config:\n url: ${fixture.origin}/mcp\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: LINEAR_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await fixture?.close() + if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true }) + }) + + it('connects the account from the plugin page and signs out after confirmation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-linear-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 Linear 插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2) + + const opened = context.waitForEvent('page') + await section.getByRole('button', { name: '连接 Linear', exact: true }).click() + const authorization = await opened + await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 }) + .toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + await page.getByText('Linear 已连接', { exact: true }).waitFor({ timeout: 10_000 }) + expect(fixture.authorizations()).toBe(1) + await authorization.close() + + await section.getByRole('button', { name: '退出登录', exact: true }).click() + await page.getByRole('dialog', { name: '退出 Linear 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(tripwire.pageErrors).toEqual([]) + expect(fixture.failures()).toEqual([]) + }) +}) diff --git a/apps/web/tests/linear-oauth-fixture.ts b/apps/web/tests/linear-oauth-fixture.ts new file mode 100644 index 0000000000..faab11ad76 --- /dev/null +++ b/apps/web/tests/linear-oauth-fixture.ts @@ -0,0 +1,118 @@ +/** + * Loopback stand-in for Linear's hosted MCP server: OAuth protected-resource + * and authorization-server metadata, dynamic client registration, an + * authorization endpoint that approves every request by redirecting straight + * back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint + * that requires a bearer token this fixture issued and answers JSON-RPC with + * plain JSON. The `initialize`, `tools/list`, and `ping` answers are written + * by hand because `apps/web` carries no MCP SDK dependency; the scenario only + * needs the handshake and the tool listing to succeed. + */ +import { once } from 'node:events' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' + +/** The running fixture and what the browser and Host asked of it. */ +export interface LinearOAuthFixture { + /** `http://127.0.0.1:`; the MCP endpoint is `/mcp`. */ + readonly origin: string + /** Authorization pages the browser opened. */ + authorizations(): number + /** Errors thrown while answering requests, each answered with a 500; the scenario expects none. */ + failures(): readonly unknown[] + /** Stop listening and close open connections. */ + close(): Promise +} + +/** + * Listen on an OS-assigned loopback port. + * @returns the running fixture. + */ +export async function startLinearOAuthFixture(): Promise { + let origin = '', authorizations = 0, tokens = 0, registrations = 0 + const issued = new Set() + const failures: unknown[] = [] + const json =(response: ServerResponse, value: unknown, status = 200): void => { + response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value)) + } + async function text(request: IncomingMessage): Promise { + const chunks: Buffer[] = [] + for await (const chunk of request) { + if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes') + chunks.push(Buffer.from(chunk)) + } + return Buffer.concat(chunks).toString() + } + async function handle(request: IncomingMessage, response: ServerResponse): Promise { + const url = new URL(request.url!, origin) + if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) { + json(response, { resource: origin + '/mcp', authorization_servers: [origin] }) + } else if (url.pathname === '/.well-known/oauth-authorization-server') { + json(response, { + issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token', + registration_endpoint: origin + '/register', response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true, + }) + } else if (url.pathname === '/register') { + registrations++ + const metadata = JSON.parse(await text(request)) as Record + json(response, { ...metadata, client_id: 'linear-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201) + } else if (url.pathname === '/authorize') { + authorizations++ + const callback = new URL(url.searchParams.get('redirect_uri')!) + callback.searchParams.set('code', 'linear-code-' + String(authorizations)) + callback.searchParams.set('state', url.searchParams.get('state')!) + callback.searchParams.set('iss', origin) + response.writeHead(302, { location: callback.href }).end() + } else if (url.pathname === '/token') { + await text(request) + tokens++ + const token = 'linear-access-' + String(tokens) + issued.add(token) + json(response, { access_token: token, refresh_token: 'linear-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 }) + } else if (url.pathname === '/mcp') { + const token = request.headers.authorization?.replace(/^Bearer /u, '') + if (token === undefined || !issued.has(token)) { + response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end() + } else await answerMcp(request, response) + } else response.writeHead(404).end() + } + async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise { + if (request.method !== 'POST') { response.writeHead(405).end(); return } + const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } } + if (message.id === undefined) { response.writeHead(202).end(); return } + const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) } + switch (message.method) { + case 'initialize': + reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'linear-fixture', version: '1.0.0' } }) + break + case 'tools/list': + reply({ tools: [{ name: 'linear-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] }) + break + case 'ping': reply({}); break + default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }) + } + } + const server = createServer((request, response) => { + handle(request, response).catch((error: unknown) => { + failures.push(error) + if (!response.headersSent) response.writeHead(500).end() + }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Linear OAuth fixture did not bind TCP') + origin = `http://127.0.0.1:${String(address.port)}` + return { + origin, + authorizations: () => authorizations, + failures: () => failures, + close: async () => { + await new Promise((resolve, reject) => { + server.close((error) => { if (error === undefined) resolve(); else reject(error) }) + server.closeAllConnections() + }) + }, + } +} diff --git a/apps/web/tests/notion-connection.e2e.ts b/apps/web/tests/notion-connection.e2e.ts new file mode 100644 index 0000000000..eccc2bb6b5 --- /dev/null +++ b/apps/web/tests/notion-connection.e2e.ts @@ -0,0 +1,76 @@ +// Web e2e scenario: connecting the Notion plugin from its page on the Plugins +// page. The section reads the MCP manager's real entry, the browser opens the +// loopback authorization server's page, the Host callback answers with its +// completion page, the connection reaches the manager, and sign-out returns the +// section to disconnected. Zero model calls. +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { startNotionOAuthFixture, type NotionOAuthFixture } from './notion-oauth-fixture.ts' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const NOTION_DIR = fileURLToPath(new URL('../../../packages/connector/notion', import.meta.url)) + +describe('web e2e: Notion plugin connection', () => { + let fixture: NotionOAuthFixture + let overlayDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + fixture = await startNotionOAuthFixture() + overlayDir = await mkdtemp(join(tmpdir(), 'dsh-notion-e2e-')) + const overlay = join(overlayDir, 'notion.overlay.yml') + await writeFile(overlay, `- id: notion\n config:\n url: ${fixture.origin}/mcp\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: NOTION_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await fixture?.close() + if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true }) + }) + + it('connects the account from the plugin page and signs out after confirmation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-notion-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 Notion 插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2) + + const opened = context.waitForEvent('page') + await section.getByRole('button', { name: '连接 Notion', exact: true }).click() + const authorization = await opened + await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 }) + .toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + await page.getByText('Notion 已连接', { exact: true }).waitFor({ timeout: 10_000 }) + expect(fixture.authorizations()).toBe(1) + await authorization.close() + + await section.getByRole('button', { name: '退出登录', exact: true }).click() + await page.getByRole('dialog', { name: '退出 Notion 登录?' }).getByRole('button', { name: '退出登录', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/notion-oauth-fixture.ts b/apps/web/tests/notion-oauth-fixture.ts new file mode 100644 index 0000000000..87359301fa --- /dev/null +++ b/apps/web/tests/notion-oauth-fixture.ts @@ -0,0 +1,104 @@ +/** + * Loopback stand-in for Notion's hosted MCP server: OAuth protected-resource + * and authorization-server metadata, dynamic client registration, an + * authorization endpoint that approves every request by redirecting straight + * back to the caller, a token endpoint, and a Streamable HTTP MCP endpoint + * that requires the issued bearer token and answers JSON-RPC with plain JSON. + */ +import { once } from 'node:events' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' + +/** The running fixture and what the browser and Host asked of it. */ +export interface NotionOAuthFixture { + /** `http://127.0.0.1:`; the MCP endpoint is `/mcp`. */ + readonly origin: string + /** Authorization pages the browser opened. */ + authorizations(): number + /** Stop listening and close open connections. */ + close(): Promise +} + +/** + * Listen on an OS-assigned loopback port. + * @returns the running fixture. + */ +export async function startNotionOAuthFixture(): Promise { + let origin = '', authorizations = 0, tokens = 0, registrations = 0 + const json = (response: ServerResponse, value: unknown, status = 200): void => { + response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value)) + } + async function text(request: IncomingMessage): Promise { + const chunks: Buffer[] = [] + for await (const chunk of request) { + if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes') + chunks.push(Buffer.from(chunk)) + } + return Buffer.concat(chunks).toString() + } + async function handle(request: IncomingMessage, response: ServerResponse): Promise { + const url = new URL(request.url!, origin) + if (url.pathname.startsWith('/.well-known/oauth-protected-resource')) { + json(response, { resource: origin + '/mcp', authorization_servers: [origin] }) + } else if (url.pathname === '/.well-known/oauth-authorization-server') { + json(response, { + issuer: origin, authorization_endpoint: origin + '/authorize', token_endpoint: origin + '/token', + registration_endpoint: origin + '/register', response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], authorization_response_iss_parameter_supported: true, + }) + } else if (url.pathname === '/register') { + registrations++ + const metadata = JSON.parse(await text(request)) as Record + json(response, { ...metadata, client_id: 'notion-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201) + } else if (url.pathname === '/authorize') { + authorizations++ + const callback = new URL(url.searchParams.get('redirect_uri')!) + callback.searchParams.set('code', 'notion-code-' + String(authorizations)) + callback.searchParams.set('state', url.searchParams.get('state')!) + callback.searchParams.set('iss', origin) + response.writeHead(302, { location: callback.href }).end() + } else if (url.pathname === '/token') { + await text(request) + tokens++ + json(response, { access_token: 'notion-access-' + String(tokens), refresh_token: 'notion-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 3600 }) + } else if (url.pathname === '/mcp') { + if (request.headers.authorization === undefined) { + response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/mcp"` }).end() + } else await answerMcp(request, response) + } else response.writeHead(404).end() + } + async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise { + if (request.method !== 'POST') { response.writeHead(405).end(); return } + const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } } + if (message.id === undefined) { response.writeHead(202).end(); return } + const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) } + switch (message.method) { + case 'initialize': + reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'notion-fixture', version: '1.0.0' } }) + break + case 'tools/list': + reply({ tools: [{ name: 'notion-search', description: 'Search the fixture workspace.', inputSchema: { type: 'object', properties: {} } }] }) + break + case 'ping': reply({}); break + default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }) + } + } + const server = createServer((request, response) => { + handle(request, response).catch(() => { if (!response.headersSent) response.writeHead(500).end() }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Notion OAuth fixture did not bind TCP') + origin = `http://127.0.0.1:${String(address.port)}` + return { + origin, + authorizations: () => authorizations, + close: async () => { + await new Promise((resolve, reject) => { + server.close((error) => { if (error === undefined) resolve(); else reject(error) }) + server.closeAllConnections() + }) + }, + } +} diff --git a/apps/web/tests/plugin-config.e2e.ts b/apps/web/tests/plugin-config.e2e.ts index b2bc6de81b..b0c6131848 100644 --- a/apps/web/tests/plugin-config.e2e.ts +++ b/apps/web/tests/plugin-config.e2e.ts @@ -167,18 +167,33 @@ describe('web e2e: plugin configuration pages', () => { await expect.poll(() => page.getByRole('menuitem').count()).toBe(0) return items } - // The shipped composition selects the DeepSeek Search API and local fetch, and the page writes nothing on mount. - expect(await searchMenu.textContent()).toBe('DeepSeek Search API') + // The shipped composition selects no search provider and local fetch, and the page writes nothing on mount. + expect(await searchMenu.textContent()).toBe('自动选择') expect(await fetchMenu.textContent()).toBe('本机直接获取') - expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1) + expect(await panel.getByRole('button', { name: '网页搜索提供方 自动选择', exact: true }).count()).toBe(1) expect(await panel.getByRole('button', { name: '网页获取提供方 本机直接获取', exact: true }).count()).toBe(1) - expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)']) + expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索']) expect(await entries(fetchMenu)).toEqual(['本机直接获取', 'DeepSeek Fetch API']) expect(await settingsDocument()).not.toContain('searchProvider:') // The page fixes the menu order itself; the Loader imports plugins concurrently, so the // Host's registration order is not the YAML row order and only its membership is checked here. const hostWeb = scaffold.ctx.get('web') as { listProviders(): Record<'search' | 'fetch', { id: string }[]> } | undefined expect(hostWeb?.listProviders().search.map(provider => provider.id).sort()).toEqual(['deepseek-official', 'deepseek-search-api']) + // Automatic selection states which provider the Host runs for each model and shows no provider panel. + expect(await searchSection.getByText( + '跟随当前会话的模型:DeepSeek 模型使用 DeepSeek 服务端搜索,搜索不按次收费;其他模型使用 DeepSeek Search API。', { exact: true }, + ).count()).toBe(1) + expect(await searchSection.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href')) + .toBe('https://api-docs.deepseek.com/zh-cn/guides/search') + expect(await searchSection.getByRole('textbox').count()).toBe(0) + expect(await save.isDisabled()).toBe(true) + + // The composition names no search provider, so a selected one is stored. + await choose(searchMenu, 'DeepSeek Search API') + await save.click() + await expect.poll(() => save.isDisabled()).toBe(true) + await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api') + expect(await panel.getByRole('button', { name: '网页搜索提供方 DeepSeek Search API', exact: true }).count()).toBe(1) expect(await panel.getByRole('link', { name: '网页搜索与获取指南', exact: true }).getAttribute('href')) .toBe('https://api-docs.deepseek.com/zh-cn/guides/search') // Each section shows the description its selected provider registered with the Host, in the active language. @@ -230,7 +245,7 @@ describe('web e2e: plugin configuration pages', () => { await expect.poll(() => save.isDisabled()).toBe(true) await expect.poll(settingsDocument).not.toContain('fetchProvider: deepseek-fetch-api') - await choose(searchMenu, 'DeepSeek(旧版)') + await choose(searchMenu, 'DeepSeek 服务端搜索') const messagesEndpoint = panel.locator('#plugin-config-web-search-endpoint') expect(await panel.getByLabel('单次请求最多搜索次数', { exact: true }).inputValue()).toBe('5') await messagesEndpoint.fill('https://messages.test/anthropic/v1') @@ -241,17 +256,23 @@ describe('web e2e: plugin configuration pages', () => { await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) await openPlugins() await openPage(panel, '网页搜索与获取') - expect(await searchMenu.textContent()).toBe('DeepSeek(旧版)') + expect(await searchMenu.textContent()).toBe('DeepSeek 服务端搜索') expect(await messagesEndpoint.inputValue()).toBe('https://messages.test/anthropic/v1') - expect(await entries(searchMenu)).toEqual(['DeepSeek Search API', 'DeepSeek(旧版)']) + expect(await entries(searchMenu)).toEqual(['自动选择', 'DeepSeek Search API', 'DeepSeek 服务端搜索']) expect(await save.isDisabled()).toBe(true) expect(await settingsDocument()).toContain('searchProvider: deepseek-official') await choose(searchMenu, 'DeepSeek Search API') await count.fill('20') await save.click() await expect.poll(() => save.isDisabled()).toBe(true) - await expect.poll(settingsDocument).not.toContain('searchProvider:') + await expect.poll(settingsDocument).toContain('searchProvider: deepseek-search-api') expect(await settingsDocument()).toContain('count: 20') + // Automatic selection clears the stored provider. + await choose(searchMenu, '自动选择') + await save.click() + await expect.poll(() => save.isDisabled()).toBe(true) + await expect.poll(settingsDocument).not.toContain('searchProvider:') + expect(await searchMenu.textContent()).toBe('自动选择') expect(await settingsDocument()).not.toMatch(/ApiKeyEnv:|searchBaseURL:|fetchBaseURL:/) expect(tripwire.pageErrors).toEqual([]) }) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index 577beee782..f1d6569cbf 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -23,6 +23,7 @@ import { const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/plugin-manager', import.meta.url)) const MANAGER_EXPECTED = join(SNAPSHOT_DIR, 'manager.expected.md') +const TERMINAL_EXPECTED = join(SNAPSHOT_DIR, 'terminal.expected.md') const LIVE_EXPECTED = join(SNAPSHOT_DIR, 'live-enabled.expected.md') const EXPORTS_EXPECTED = join(SNAPSHOT_DIR, 'exports.expected.md') const EXPORTS_EN_EXPECTED = join(SNAPSHOT_DIR, 'exports-en.expected.md') @@ -849,7 +850,10 @@ describe('web e2e: plugin manager', () => { expect(await panel.getByText(experimentalBundleDescription('inspector-profile', 'zh'), { exact: true }).count()).toBe(1) const bundles = await scaffold.ctx.pluginManager.listBundles() expect(bundles.some(bundle => bundle.name === '@deepseek-ai/dsh-experimental-terminal-bundle')).toBe(true) - expect(await panel.getByRole('switch', { name: '启用 持久终端', exact: true }).count()).toBe(0) + expect(await panel.getByRole('switch', { name: '启用 持久终端', exact: true }).getAttribute('aria-checked')).toBe('false') + await compareOrRefreshGolden(TERMINAL_EXPECTED, await captureStableAria( + page, '[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-experimental-terminal-bundle"]', scaffold.workspaceCwd, + ), MODE) // The More list also omits LiveShare until its rows run, so the offered count is one lower than // the eligible installed optional-bundle list. expect(await panel.locator('[data-plugin-group="more"] [data-plugin-package="@deepseek-ai/dsh-experimental-liveshare"]').count()).toBe(0) @@ -881,6 +885,7 @@ describe('web e2e: plugin manager', () => { ['@deepseek-ai/dsh-experimental-inspector-profile', 1], ...cuaSupported ? [['@deepseek-ai/dsh-cua-bundle', 1]] : [], ['@deepseek-ai/dsh-timeline', 1], + ['@deepseek-ai/dsh-experimental-terminal-bundle', 1], ['@deepseek-ai/dsh-experimental-cot-translation-bundle', 1], ['@deepseek-ai/dsh-experimental-session-titles-bundle', 1], ['@deepseek-ai/dsh-experimental-badge-skill-bundle', 1], @@ -1665,7 +1670,7 @@ describe('web e2e: plugin manager', () => { it.skipIf(MODE === 'record')('keeps the fixture inventory closed', async () => { expect(tripwire.warnings).toEqual([]) await assertFixtureInventory(SNAPSHOT_DIR, [ - 'manager.expected.md', 'live-enabled.expected.md', 'missing-bundle.expected.md', 'exports.expected.md', 'exports-en.expected.md', 'icons.expected.md', 'loading.expected.md', 'refresh.expected.md', + 'manager.expected.md', 'terminal.expected.md', 'live-enabled.expected.md', 'missing-bundle.expected.md', 'exports.expected.md', 'exports-en.expected.md', 'icons.expected.md', 'loading.expected.md', 'refresh.expected.md', 'ime-enter.expected.md', 'header-responsive.expected.md', 'header-natural-motion.expected.md', 'preview.expected.md', 'touch-tooltips.expected.md', 'forge-preview.expected.md', 'timeline-tracking.expected.md', ]) diff --git a/apps/web/tests/search-api-provider.overlay.yml b/apps/web/tests/search-api-provider.overlay.yml new file mode 100644 index 0000000000..3de0016a01 --- /dev/null +++ b/apps/web/tests/search-api-provider.overlay.yml @@ -0,0 +1,6 @@ +# The replayed conversation runs on a DeepSeek model route, where an unconfigured search selects +# legacy Messages search. This scenario exercises the DeepSeek Search API. +- id: web + config: + searchProvider: deepseek-search-api + fetchProvider: http diff --git a/apps/web/tests/session-drag-scroll.e2e.ts b/apps/web/tests/session-drag-scroll.e2e.ts index 2059d10b16..51a6fbf26f 100644 --- a/apps/web/tests/session-drag-scroll.e2e.ts +++ b/apps/web/tests/session-drag-scroll.e2e.ts @@ -89,17 +89,21 @@ describe('web e2e: session drag scrolling', () => { // Drop onto a row that was out of view when the drag started. const middle = (await listEdges()).top + 200 await page.mouse.move(x, middle, { steps: 3 }) - await page.mouse.move(x + 1, middle) - await page.mouse.move(x, middle) - const target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y)! - .closest('[role="treeitem"]')!.querySelector('[class*="title"]')!.textContent, { x, y: middle }) - expect(target).toMatch(/^Conversation (\d{2}|[89])$/) + // The point can rest on the gap between rows while the drop indicator settles, so read again until it names a row. + let target = '' + await expect.poll(async () => { + await page.mouse.move(x + 1, middle) + await page.mouse.move(x, middle) + target = await page.evaluate(({ x, y }) => document.elementFromPoint(x, y) + ?.closest('[role="treeitem"]')?.querySelector('[class*="title"]')?.textContent ?? '', { x, y: middle }) + return target + }, { timeout: 15_000 }).toMatch(/^Conversation (\d{2}|[89])$/) await page.mouse.up() const titles = () => rows.locator('[class*="title"]').allTextContents() await expect.poll(async () => { const order = await titles() return Math.abs(order.indexOf('Conversation 0') - order.indexOf(target)) - }).toBe(1) + }, { timeout: 10_000 }).toBe(1) expect(tripwire.pageErrors).toEqual([]) expect(tripwire.warnings).toEqual([]) }) diff --git a/apps/web/tests/sidebar-terminal.e2e.ts b/apps/web/tests/sidebar-terminal.e2e.ts index 6ca14145f2..b44c925906 100644 --- a/apps/web/tests/sidebar-terminal.e2e.ts +++ b/apps/web/tests/sidebar-terminal.e2e.ts @@ -247,7 +247,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => { expect(tripwire.pageErrors).toEqual([]) }) - it('starts in the current directory while earlier terminals and sandbox roots stay independent', async () => { + it('starts in the current directory while earlier terminals keep theirs and the sandbox root follows the directory', async () => { onTestFailed(() => saveFailureShot(page, 'sidebar-terminal-directory')) const agent = scaffold.ctx.agents.list()[0]! const directories = agent.ctx.get('workingDirectory') @@ -262,6 +262,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => { if (sandbox === undefined) throw new Error('Session sandbox provider is missing') const confine = vi.spyOn(sandbox, 'confine') const selected = await directories.set(agent, child) + expect(sandboxPolicy.resolve({ session: agent.session })).toEqual({ ...policy, workspaceRoot: selected }) await openTerminal(page) const firstProcess = processIdentity(0) diff --git a/apps/web/tests/tencent-docs-connection.e2e.ts b/apps/web/tests/tencent-docs-connection.e2e.ts new file mode 100644 index 0000000000..adcc9c4f10 --- /dev/null +++ b/apps/web/tests/tencent-docs-connection.e2e.ts @@ -0,0 +1,79 @@ +// Web e2e scenario: connecting the Tencent Docs plugin from its page on the Plugins +// page. The section reads the MCP manager's real entry, the browser opens the +// loopback authorization server's page with the `docs:*` scopes and the +// endpoint's own query, the Host callback answers with its +// completion page, the connection reaches the manager, and sign-out returns the +// section to disconnected. Zero model calls. +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { startTencentDocsOAuthFixture, type TencentDocsOAuthFixture } from './tencent-docs-oauth-fixture.ts' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const TENCENT_DOCS_DIR = fileURLToPath(new URL('../../../packages/connector/tencent-docs', import.meta.url)) + +describe('web e2e: Tencent Docs plugin connection', () => { + let fixture: TencentDocsOAuthFixture + let overlayDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + fixture = await startTencentDocsOAuthFixture() + overlayDir = await mkdtemp(join(tmpdir(), 'dsh-tencent-docs-e2e-')) + const overlay = join(overlayDir, 'tencent-docs.overlay.yml') + await writeFile(overlay, `- id: tencent-docs\n config:\n url: ${fixture.origin}/mcp\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: TENCENT_DOCS_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + await fixture?.close() + if (overlayDir !== undefined) await rm(overlayDir, { recursive: true, force: true }) + }) + + it('connects the account from the plugin page and signs out after confirmation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-tencent-docs-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 腾讯文档插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2) + + const opened = context.waitForEvent('page') + await section.getByRole('button', { name: '连接腾讯文档', exact: true }).click() + const authorization = await opened + await expect.poll(async () => await authorization.locator('body').textContent(), { timeout: 20_000 }) + .toContain('已收到授权。可以关闭此页,回到 DSH 查看连接结果。') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + await page.getByText('腾讯文档已连接', { exact: true }).waitFor({ timeout: 10_000 }) + expect(fixture.authorizations()).toBe(1) + expect(fixture.authorizationQuery()?.get('authType')).toBe('2') + expect(fixture.authorizationQuery()?.get('scope')).toBe('docs:read docs:write docs:manage') + await authorization.close() + + await section.getByRole('button', { name: '退出登录', exact: true }).click() + await page.getByRole('dialog', { name: '退出腾讯文档登录?' }).getByRole('button', { name: '退出登录', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/tencent-docs-oauth-fixture.ts b/apps/web/tests/tencent-docs-oauth-fixture.ts new file mode 100644 index 0000000000..49babc5ddb --- /dev/null +++ b/apps/web/tests/tencent-docs-oauth-fixture.ts @@ -0,0 +1,113 @@ +/** + * Loopback stand-in for Tencent Docs' hosted MCP server, laid out like the + * hosted metadata: the 401 challenge names protected-resource metadata under + * the MCP path, that metadata lists the `docs:*` scopes, and the + * authorization endpoint already carries a query string. Dynamic client + * registration, an authorization endpoint that approves every request by + * redirecting straight back without an `iss` parameter, a token endpoint, and + * a Streamable HTTP MCP endpoint that requires the issued bearer token and + * answers JSON-RPC with plain JSON complete the flow. + */ +import { once } from 'node:events' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' + +const SCOPES = ['docs:read', 'docs:write', 'docs:manage'] + +/** The running fixture and what the browser and Host asked of it. */ +export interface TencentDocsOAuthFixture { + /** `http://127.0.0.1:`; the MCP endpoint is `/mcp`. */ + readonly origin: string + /** Authorization pages the browser opened. */ + authorizations(): number + /** Query of the latest authorization page the browser opened. */ + authorizationQuery(): URLSearchParams | undefined + /** Stop listening and close open connections. */ + close(): Promise +} + +/** + * Listen on an OS-assigned loopback port. + * @returns the running fixture. + */ +export async function startTencentDocsOAuthFixture(): Promise { + let origin = '', authorizations = 0, tokens = 0, registrations = 0 + let authorizationQuery: URLSearchParams | undefined + const json = (response: ServerResponse, value: unknown, status = 200): void => { + response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(value)) + } + async function text(request: IncomingMessage): Promise { + const chunks: Buffer[] = [] + for await (const chunk of request) { + if (!(chunk instanceof Uint8Array)) throw new Error('Expected request bytes') + chunks.push(Buffer.from(chunk)) + } + return Buffer.concat(chunks).toString() + } + async function handle(request: IncomingMessage, response: ServerResponse): Promise { + const url = new URL(request.url!, origin) + if (url.pathname === '/mcp/.well-known/oauth-protected-resource') { + json(response, { resource: origin + '/mcp', authorization_servers: [origin], scopes_supported: SCOPES, bearer_methods_supported: ['header'] }) + } else if (url.pathname === '/.well-known/oauth-authorization-server') { + json(response, { + issuer: origin, authorization_endpoint: origin + '/authorize?authType=2', token_endpoint: origin + '/token', + registration_endpoint: origin + '/register', scopes_supported: SCOPES, response_types_supported: ['code'], + grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['none'], + }) + } else if (url.pathname === '/register') { + registrations++ + const metadata = JSON.parse(await text(request)) as Record + json(response, { ...metadata, client_id: 'tencent-docs-client-' + String(registrations), token_endpoint_auth_method: 'none' }, 201) + } else if (url.pathname === '/authorize') { + authorizations++ + authorizationQuery = url.searchParams + const callback = new URL(url.searchParams.get('redirect_uri')!) + callback.searchParams.set('code', 'tencent-docs-code-' + String(authorizations)) + callback.searchParams.set('state', url.searchParams.get('state')!) + response.writeHead(302, { location: callback.href }).end() + } else if (url.pathname === '/token') { + await text(request) + tokens++ + json(response, { access_token: 'tencent-docs-access-' + String(tokens), refresh_token: 'tencent-docs-refresh-' + String(tokens), token_type: 'Bearer', expires_in: 31535999, scope: SCOPES.join(' ') }) + } else if (url.pathname === '/mcp') { + if (request.headers.authorization === undefined) { + response.writeHead(401, { 'www-authenticate': `Bearer resource_metadata="${origin}/mcp/.well-known/oauth-protected-resource"` }).end() + } else await answerMcp(request, response) + } else response.writeHead(404).end() + } + async function answerMcp(request: IncomingMessage, response: ServerResponse): Promise { + if (request.method !== 'POST') { response.writeHead(405).end(); return } + const message = JSON.parse(await text(request)) as { id?: number | string; method: string; params?: { protocolVersion?: string } } + if (message.id === undefined) { response.writeHead(202).end(); return } + const reply = (result: unknown): void => { json(response, { jsonrpc: '2.0', id: message.id, result }) } + switch (message.method) { + case 'initialize': + reply({ protocolVersion: message.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'tencent-docs-fixture', version: '1.0.0' } }) + break + case 'tools/list': + reply({ tools: [{ name: 'search', description: 'Search the fixture documents.', inputSchema: { type: 'object', properties: {} } }] }) + break + case 'ping': reply({}); break + default: json(response, { jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }) + } + } + const server = createServer((request, response) => { + handle(request, response).catch(() => { if (!response.headersSent) response.writeHead(500).end() }) + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Tencent Docs OAuth fixture did not bind TCP') + origin = `http://127.0.0.1:${String(address.port)}` + return { + origin, + authorizations: () => authorizations, + authorizationQuery: () => authorizationQuery, + close: async () => { + await new Promise((resolve, reject) => { + server.close((error) => { if (error === undefined) resolve(); else reject(error) }) + server.closeAllConnections() + }) + }, + } +} diff --git a/apps/web/tests/tencent-meeting-connection.e2e.ts b/apps/web/tests/tencent-meeting-connection.e2e.ts new file mode 100644 index 0000000000..573c4d496e --- /dev/null +++ b/apps/web/tests/tencent-meeting-connection.e2e.ts @@ -0,0 +1,128 @@ +// Tencent Meeting sign-in, failure, and sign-out through the real Host/Remote/browser composition. +// A stand-in CLI waits for each authorization page visit and keeps the sign-in on disk. +import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const TENCENT_MEETING_DIR = fileURLToPath(new URL('../../../packages/connector/tencent-meeting', import.meta.url)) +const AUTH_PAGE = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html' +const authUrl = (attempt: number) => `${AUTH_PAGE}?e2e=${String(attempt)}&code=fixture-code` + +// The stand-in keeps its sign-in in state.json beside itself; auth login prints +// a new authorization link on its `authorize url:` line for each attempt and +// waits until the test marks the page visited. +const TMEET = `#!/usr/bin/env node +const { existsSync, readFileSync, writeFileSync } = require('node:fs') +const { join } = require('node:path') +const dir = __dirname +const statePath = join(dir, 'state.json') +const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { signedIn: false, attempts: 0 } +const save = () => { writeFileSync(statePath, JSON.stringify(state)) } +switch (process.argv.slice(2).join(' ')) { + case 'auth status': + process.stdout.write(state.signedIn + ? 'Logged in\\n OpenId: ou_e2e\\n UserName: 测试用户\\n' + : "Not logged in. Please use 'tmeet auth login' to authenticate.\\n") + break + case 'auth login --no-browser': { + state.attempts += 1 + save() + process.stdout.write('\\nPlease open the following URL in your browser to authorize\\n\\nauthorize url: ${AUTH_PAGE}?e2e=' + state.attempts + '&code=fixture-code\\n\\nwaiting for authorization...\\n') + const poll = setInterval(() => { + if (!existsSync(join(dir, 'auth-visited'))) return + clearInterval(poll) + if (existsSync(join(dir, 'login-fails'))) { + process.stderr.write('Error: authorization failed; code=fixture-code\\n') + process.exitCode = 1 + } else { + state.signedIn = true + save() + process.stdout.write('Login successful. Start managing your meetings using tmeet.\\n') + } + }, 50) + break + } + case 'auth logout': state.signedIn = false; save(); process.stdout.write('Logout success, welcome to use it again.\\n'); break + default: + process.stderr.write('unexpected tmeet arguments: ' + process.argv.slice(2).join(' ') + '\\n') + process.exitCode = 1 +} +` + +// The stand-in runs through its shebang, which Windows cannot execute. +describe.skipIf(process.platform === 'win32')('web e2e: Tencent Meeting plugin account', () => { + let binDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + binDir = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-e2e-')) + await writeFile(join(binDir, 'tmeet'), TMEET) + await chmod(join(binDir, 'tmeet'), 0o755) + await mkdir(join(binDir, 'skills')) + const overlay = join(binDir, 'tencent-meeting.overlay.yml') + await writeFile(overlay, `- id: tencent-meeting\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(join(binDir, 'skills'))}\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: TENCENT_MEETING_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + await context.route(url => url.href.startsWith(AUTH_PAGE), async (route) => { + await writeFile(join(binDir, 'auth-visited'), '') + await route.fulfill({ contentType: 'text/html; charset=utf-8', body: 'Tencent Meeting

Tencent Meeting stand-in page

' }) + }) + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (binDir !== undefined) await rm(binDir, { recursive: true, force: true }) + }) + + it('reports a failed sign-in without its output, signs in, and signs out after confirmation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-tencent-meeting-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 腾讯会议插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-tencent-meeting"]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未连接', { exact: true }).count()).toBe(2) + + const opened: Page[] = [] + context.on('page', (popup) => { opened.push(popup) }) + await writeFile(join(binDir, 'login-fails'), '') + await section.getByRole('button', { name: '连接腾讯会议', exact: true }).click() + await section.getByRole('alert').waitFor({ timeout: 20_000 }) + expect(await section.getAttribute('data-connector-account')).toBe('disconnected') + expect(await section.getByRole('alert').innerText()).toContain('auth-login · exit 1') + expect(await section.innerText()).not.toContain('fixture-code') + + await rm(join(binDir, 'login-fails')) + await rm(join(binDir, 'auth-visited')) + await section.getByRole('button', { name: '连接腾讯会议', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + expect(opened.map(popup => popup.url())).toEqual([authUrl(1), authUrl(2)]) + await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用腾讯会议。', { exact: true }).waitFor({ timeout: 10_000 }) + await page.getByText('腾讯会议已连接', { exact: true }).waitFor({ timeout: 10_000 }) + + await section.getByRole('button', { name: '退出登录', exact: true }).click() + await page.getByRole('dialog').getByRole('button', { name: '退出登录', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + await page.getByText('已退出腾讯会议登录', { exact: true }).waitFor({ timeout: 10_000 }) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tests/web-search-round.e2e.ts b/apps/web/tests/web-search-round.e2e.ts index a4cbfc5207..9c04d18de6 100644 --- a/apps/web/tests/web-search-round.e2e.ts +++ b/apps/web/tests/web-search-round.e2e.ts @@ -1,5 +1,5 @@ -// Web e2e scenario for the shipped default search provider, the DeepSeek -// Search API, with no provider selection patched. A real browser drives +// Web e2e scenario for the DeepSeek Search API, selected for a conversation +// on a DeepSeek model route. A real browser drives // `web_search`; the model stream is replayed while the real DeepSeek provider // calls a deterministic local Search API endpoint through the real // credentials service. @@ -141,7 +141,7 @@ async function startSearchServer(captured: CapturedSearchRequest[]): Promise<{ s return { server, baseURL: `http://127.0.0.1:${address.port}` } } -describe('web e2e: default Search API web search', () => { +describe('web e2e: Search API web search', () => { let scaffold: WebScaffold let browser: Browser let page: Page @@ -154,7 +154,8 @@ describe('web e2e: default Search API web search', () => { const search = await startSearchServer(searchRequests) searchServer = search.server scaffold = await launchWebScaffold({ - extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + extraOverlayPath: ['./pin-browse-picker.overlay.yml', './search-api-provider.overlay.yml'] + .map(path => fileURLToPath(new URL(path, import.meta.url))), compareReplaySession: true, // Own YAML endpoint settings pin Search to the local endpoint and a dedicated key. deepSeekWebApi: { diff --git a/apps/web/tests/wecom-connection.e2e.ts b/apps/web/tests/wecom-connection.e2e.ts new file mode 100644 index 0000000000..c6f422b753 --- /dev/null +++ b/apps/web/tests/wecom-connection.e2e.ts @@ -0,0 +1,123 @@ +// WeCom QR-code authorization failures and recovery through the real Host/Remote/browser composition. +// A stand-in CLI waits for each QR-code page visit and keeps the authorization on disk. +import { chmod, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Browser, BrowserContext, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { launchWebScaffold, watchConsole, type WebScaffold } from './scaffold.ts' +import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts' + +const WECOM_DIR = fileURLToPath(new URL('../../../packages/connector/wecom', import.meta.url)) +const QR_PAGE = 'https://work.weixin.qq.com/ai/qc/gen' +const qrUrl = (attempt: number) => `${QR_PAGE}?e2e=${String(attempt)}&scode=fixture-scode` + +// The stand-in keeps its authorization in state.json beside itself; auth init +// prints a new QR-code link alone on its third stdout line for each attempt and +// waits until the test marks the page visited. +const WECOM_CLI = `#!/usr/bin/env node +const { existsSync, readFileSync, writeFileSync } = require('node:fs') +const { join } = require('node:path') +const dir = __dirname +const statePath = join(dir, 'state.json') +const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')) : { authorized: false, attempts: 0, bots: 0 } +const save = () => { writeFileSync(statePath, JSON.stringify(state)) } +switch (process.argv.slice(2).join(' ')) { + case 'auth show': process.stdout.write(state.authorized ? 'Status: authorized\\nBot ID: bot-e2e-' + state.bots + '\\n' : 'Status: unauthorized\\n'); break + case 'auth init --noninteractive --no-browser': { + state.attempts += 1 + save() + process.stdout.write('Scan the QR code with WeCom to bind a bot.\\nOpen this link if the QR code does not display:\\n${QR_PAGE}?e2e=' + state.attempts + '&scode=fixture-scode\\n') + const poll = setInterval(() => { + if (!existsSync(join(dir, 'qr-visited'))) return + clearInterval(poll) + if (existsSync(join(dir, 'init-fails'))) { + process.stdout.write('bind failed; scode=fixture-scode\\n') + process.exitCode = 4 + } else { state.authorized = true; state.bots += 1; save() } + }, 50) + break + } + default: + process.stderr.write('unexpected wecom-cli arguments: ' + process.argv.slice(2).join(' ') + '\\n') + process.exitCode = 1 +} +` + +// The stand-in runs through its shebang, which Windows cannot execute. +describe.skipIf(process.platform === 'win32')('web e2e: WeCom plugin authorization', () => { + let binDir: string + let scaffold: WebScaffold + let browser: Browser + let context: BrowserContext + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + binDir = await mkdtemp(join(tmpdir(), 'dsh-wecom-e2e-')) + await writeFile(join(binDir, 'wecom-cli'), WECOM_CLI) + await chmod(join(binDir, 'wecom-cli'), 0o755) + await mkdir(join(binDir, 'skills')) + const overlay = join(binDir, 'wecom.overlay.yml') + await writeFile(overlay, `- id: wecom\n config:\n binDir: ${JSON.stringify(binDir)}\n skillsDir: ${JSON.stringify(join(binDir, 'skills'))}\n`) + scaffold = await launchWebScaffold({ + extraOverlayPath: [fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), overlay], + profile: { packages: [{ dir: WECOM_DIR, enabled: true }] }, + }) + browser = await chromium.launch() + context = await browser.newContext({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE }) + await context.route(url => url.href.startsWith(QR_PAGE), async (route) => { + await writeFile(join(binDir, 'qr-visited'), '') + await route.fulfill({ contentType: 'text/html; charset=utf-8', body: 'WeCom

WeCom stand-in page

' }) + }) + page = await context.newPage() + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + if (binDir !== undefined) await rm(binDir, { recursive: true, force: true }) + }) + + it('reports a failed QR-code authorization without its output, connects, and changes the bot after confirmation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-wecom-connection')) + await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() + const panel = page.locator('[data-plugin-panel]') + await panel.getByRole('button', { name: '查看 企业微信插件', exact: true }).click({ timeout: 20_000 }) + const section = panel.locator('[data-connector-account-key="@deepseek-ai/dsh-wecom"]') + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('disconnected') + expect(await panel.locator('[data-plugin-detail]').getByText('未授权', { exact: true }).count()).toBe(2) + + const opened: Page[] = [] + context.on('page', (popup) => { opened.push(popup) }) + await writeFile(join(binDir, 'init-fails'), '') + await section.getByRole('button', { name: '连接企业微信', exact: true }).click() + await section.getByRole('alert').waitFor({ timeout: 20_000 }) + expect(await section.getAttribute('data-connector-account')).toBe('disconnected') + expect(await section.getByRole('alert').innerText()).toContain('auth-init · exit 4') + expect(await section.innerText()).not.toContain('fixture-scode') + + await rm(join(binDir, 'init-fails')) + await rm(join(binDir, 'qr-visited')) + await section.getByRole('button', { name: '连接企业微信', exact: true }).click() + await expect.poll(() => section.getAttribute('data-connector-account'), { timeout: 20_000 }).toBe('connected') + expect(opened.map(popup => popup.url())).toEqual([qrUrl(1), qrUrl(2)]) + await section.getByText('可以在对话中直接请 Agent 使用企业微信。', { exact: true }).waitFor({ timeout: 10_000 }) + await page.getByText('企业微信已授权', { exact: true }).waitFor({ timeout: 10_000 }) + await section.getByText('已绑定机器人:bot-e2e-1', { exact: true }).waitFor({ timeout: 10_000 }) + + // Changing the bot asks first, then runs the same QR-code binding; the stand-in reports the next bot afterwards. + await rm(join(binDir, 'qr-visited')) + await section.getByRole('button', { name: '更换机器人', exact: true }).click() + await page.getByRole('dialog', { name: '更换机器人?' }).getByRole('button', { name: '更换机器人', exact: true }).click() + await section.getByText('已绑定机器人:bot-e2e-2', { exact: true }).waitFor({ timeout: 20_000 }) + expect(await section.getAttribute('data-connector-account')).toBe('connected') + expect(opened.map(popup => popup.url())).toEqual([qrUrl(1), qrUrl(2), qrUrl(3)]) + expect(tripwire.pageErrors).toEqual([]) + }) +}) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 35819fad23..7709bf5daf 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -271,7 +271,16 @@ "tests/complex-history.perf.ts", "tests/dingtalk-connection.e2e.ts", "tests/pwsh-terminal.e2e.ts", - "tests/workflow-run.e2e.ts" + "tests/wecom-connection.e2e.ts", + "tests/tencent-meeting-connection.e2e.ts", + "tests/workflow-run.e2e.ts", + "tests/linear-connection.e2e.ts", + "tests/linear-oauth-fixture.ts", + "tests/notion-connection.e2e.ts", + "tests/notion-oauth-fixture.ts", + "tests/tencent-docs-connection.e2e.ts", + "tests/tencent-docs-oauth-fixture.ts", + "tests/feishu-connection.e2e.ts" ], "references": [ { "path": "../../packages/experimental/auto-review" }, diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 796ade9065..9e9bb28cd6 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: b8a43c17719d548b - zh: 3335f8c8fa696bae + en: e9a1a23c885fbae2 + zh: 95137339b7fe8268 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index d2fdbf68c4..0e830ba85f 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -62,6 +62,14 @@ flowchart LR pkg_tool_pwsh["tool-pwsh"] pkg_subagent["subagent"] pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"] + pkg_sandbox_policy["sandbox-policy"] + pkg_api_workspace_files["api-workspace-files"] + pkg_api_terminal_controller["api-terminal-controller"] + pkg_workspace_changes["workspace-changes"] + pkg_file_reference_local["file-reference-local"] + pkg_tool_skill["tool-skill"] + pkg_agent_instructions["agent-instructions"] + pkg_tool_lsp["tool-lsp"] pkg_mcp_resources["mcp-resources"] svc_mcpResources["ctx.mcpResources
Scoped MCP resource access"] pkg_mcp_client["mcp-client"] @@ -123,11 +131,8 @@ flowchart LR pkg_api_settings_controller["api-settings-controller"] svc_credentialsController["ctx.credentialsController
Host credential-surface Remote controller"] svc_settingsController["ctx.settingsController
Host settings-surface Remote controller"] - pkg_api_workspace_files["api-workspace-files"] svc_workspaceFiles["ctx.workspaceFiles
Host workspace file Remote service"] - pkg_workspace_changes["workspace-changes"] svc_workspaceChanges["ctx.workspaceChanges
Host per-turn changed-file summaries"] - pkg_api_terminal_controller["api-terminal-controller"] svc_terminalController["ctx.terminalController
Session interactive terminal Remote controller"] pkg_api_workspace_controller["api-workspace-controller"] svc_workspaceController["ctx.workspaceController
Host Workspace Remote controller"] @@ -187,7 +192,6 @@ flowchart LR pkg_tool_session_query["tool-session-query"] pkg_file_reference["file-reference"] svc_fileReferences["ctx.fileReferences
File reference discovery"] - pkg_file_reference_local["file-reference-local"] svc_sessionReferenceResolver["ctx.sessionReferenceResolver
Cross-session snapshot preparation"] pkg_session_title["session-title"] svc_sessionTitle["ctx.sessionTitle
Log-backed session titles"] @@ -201,7 +205,6 @@ flowchart LR svc_tools["ctx.tools
Scoped tool registry and executor selection"] pkg_tool_ask_user["tool-ask-user"] pkg_tool_cordis["tool-cordis"] - pkg_tool_skill["tool-skill"] pkg_tool_todo["tool-todo"] pkg_user_questions["user-questions"] svc_userQuestions["ctx.userQuestions
Human question/answer seam"] @@ -264,7 +267,6 @@ flowchart LR pkg_sandbox["sandbox"] svc_sandbox["ctx.sandbox
Process-sandbox seam"] pkg_sandbox_local["sandbox-local"] - pkg_sandbox_policy["sandbox-policy"] svc_sandboxPolicy["ctx.sandboxPolicy
Sandbox policy home"] pkg_fs_sandbox["fs-sandbox"] pkg_user_approval["user-approval"] @@ -331,7 +333,6 @@ flowchart LR pkg_webhook_github["webhook-github"] pkg_lsp["lsp"] svc_lsp["ctx.lsp
Language-server navigation seam"] - pkg_tool_lsp["tool-lsp"] pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] @@ -681,11 +682,19 @@ flowchart LR svc_webhookRuntime --> pkg_webhook_github svc_workflowEngine --> pkg_tool_ralph svc_workflowEngine --> pkg_tool_workflow + svc_workingDirectory --> pkg_agent_instructions + svc_workingDirectory --> pkg_api_terminal_controller + svc_workingDirectory --> pkg_api_workspace_files + svc_workingDirectory --> pkg_file_reference_local + svc_workingDirectory --> pkg_sandbox_policy svc_workingDirectory --> pkg_sdk_jsonrpc_server svc_workingDirectory --> pkg_subagent svc_workingDirectory --> pkg_tool_bash svc_workingDirectory --> pkg_tool_fs + svc_workingDirectory --> pkg_tool_lsp svc_workingDirectory --> pkg_tool_pwsh + svc_workingDirectory --> pkg_tool_skill + svc_workingDirectory --> pkg_workspace_changes svc_workspaceRegistry --> pkg_api_session_controller svc_workspaceRegistry --> pkg_api_workspace_controller svc_worktrees --> pkg_experimental_tool_worktree @@ -713,7 +722,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | Explicit experimental creation from a pinned local commit. Existing write permissions govern checkout and shared Git metadata; the working-directory service owns the resulting Session directory. | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | One Session projection owns the effective execution directory, which only Host operations move. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`api-workspace-files`](../packages/api/workspace-files), [`api-terminal-controller`](../packages/api/terminal-controller), [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | One Session projection owns the effective execution directory, which only Host operations move. The filesystem validates changes and user context reports them; model tools resolve paths from the directory, the sandbox boundary, file views, and discovery follow it, and original metadata stays fixed. | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | Connection-owned providers serve shared resource tools in the calling agent scope. | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API. | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index fd6a35d746..8fc8df635c 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -64,6 +64,14 @@ flowchart LR pkg_tool_pwsh["tool-pwsh"] pkg_subagent["subagent"] pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"] + pkg_sandbox_policy["sandbox-policy"] + pkg_api_workspace_files["api-workspace-files"] + pkg_api_terminal_controller["api-terminal-controller"] + pkg_workspace_changes["workspace-changes"] + pkg_file_reference_local["file-reference-local"] + pkg_tool_skill["tool-skill"] + pkg_agent_instructions["agent-instructions"] + pkg_tool_lsp["tool-lsp"] pkg_mcp_resources["mcp-resources"] svc_mcpResources["ctx.mcpResources
Scoped MCP resource access"] pkg_mcp_client["mcp-client"] @@ -125,11 +133,8 @@ flowchart LR pkg_api_settings_controller["api-settings-controller"] svc_credentialsController["ctx.credentialsController
Host credential-surface Remote controller"] svc_settingsController["ctx.settingsController
Host settings-surface Remote controller"] - pkg_api_workspace_files["api-workspace-files"] svc_workspaceFiles["ctx.workspaceFiles
Host workspace file Remote service"] - pkg_workspace_changes["workspace-changes"] svc_workspaceChanges["ctx.workspaceChanges
Host per-turn changed-file summaries"] - pkg_api_terminal_controller["api-terminal-controller"] svc_terminalController["ctx.terminalController
Session interactive terminal Remote controller"] pkg_api_workspace_controller["api-workspace-controller"] svc_workspaceController["ctx.workspaceController
Host Workspace Remote controller"] @@ -189,7 +194,6 @@ flowchart LR pkg_tool_session_query["tool-session-query"] pkg_file_reference["file-reference"] svc_fileReferences["ctx.fileReferences
File reference discovery"] - pkg_file_reference_local["file-reference-local"] svc_sessionReferenceResolver["ctx.sessionReferenceResolver
Cross-session snapshot preparation"] pkg_session_title["session-title"] svc_sessionTitle["ctx.sessionTitle
Log-backed session titles"] @@ -203,7 +207,6 @@ flowchart LR svc_tools["ctx.tools
Scoped tool registry and executor selection"] pkg_tool_ask_user["tool-ask-user"] pkg_tool_cordis["tool-cordis"] - pkg_tool_skill["tool-skill"] pkg_tool_todo["tool-todo"] pkg_user_questions["user-questions"] svc_userQuestions["ctx.userQuestions
Human question/answer seam"] @@ -266,7 +269,6 @@ flowchart LR pkg_sandbox["sandbox"] svc_sandbox["ctx.sandbox
Process-sandbox seam"] pkg_sandbox_local["sandbox-local"] - pkg_sandbox_policy["sandbox-policy"] svc_sandboxPolicy["ctx.sandboxPolicy
Sandbox policy home"] pkg_fs_sandbox["fs-sandbox"] pkg_user_approval["user-approval"] @@ -333,7 +335,6 @@ flowchart LR pkg_webhook_github["webhook-github"] pkg_lsp["lsp"] svc_lsp["ctx.lsp
Language-server navigation seam"] - pkg_tool_lsp["tool-lsp"] pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] @@ -683,11 +684,19 @@ flowchart LR svc_webhookRuntime --> pkg_webhook_github svc_workflowEngine --> pkg_tool_ralph svc_workflowEngine --> pkg_tool_workflow + svc_workingDirectory --> pkg_agent_instructions + svc_workingDirectory --> pkg_api_terminal_controller + svc_workingDirectory --> pkg_api_workspace_files + svc_workingDirectory --> pkg_file_reference_local + svc_workingDirectory --> pkg_sandbox_policy svc_workingDirectory --> pkg_sdk_jsonrpc_server svc_workingDirectory --> pkg_subagent svc_workingDirectory --> pkg_tool_bash svc_workingDirectory --> pkg_tool_fs + svc_workingDirectory --> pkg_tool_lsp svc_workingDirectory --> pkg_tool_pwsh + svc_workingDirectory --> pkg_tool_skill + svc_workingDirectory --> pkg_workspace_changes svc_workspaceRegistry --> pkg_api_session_controller svc_workspaceRegistry --> pkg_api_workspace_controller svc_worktrees --> pkg_experimental_tool_worktree @@ -715,7 +724,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | 显式实验组合从固定的本地提交创建工作树。检出目录与共享 Git 元数据受现有写权限约束;工作目录服务拥有创建后的 Session 目录。 | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 两个 Session 投影拥有有效执行目录与工作区根;Host 操作让两者一起移动。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`api-workspace-files`](../packages/api/workspace-files), [`api-terminal-controller`](../packages/api/terminal-controller), [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | 两个 Session 投影拥有有效执行目录与工作区根;Host 操作让两者一起移动。文件系统验证变更,用户上下文报告目录信息;模型工具从目录解析路径,沙箱边界、文件视图与发现跟随根,原始元数据保持不变。 | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | 连接所有者提供的操作在调用 agent 的作用域内服务于共享资源工具。 | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 Session 拥有自己的工具与浏览器资源;共享服务不提供浏览器操作 API。 | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 68a0459176..7b98c65de2 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -357,7 +357,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-files` - `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert` -- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts) +- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts) ```ts config-catalog /** Deployment caps on one page, one listing, or one search. */ @@ -1255,7 +1255,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1310,6 +1310,14 @@ export interface Config { maxCachedLensBytes?: number /** Most line annotations a changes view shows in one file, across every annotation source. */ maxAnnotationsPerFile?: number + /** Milliseconds between two reads of the review page's lists while the page is open. */ + reviewListIntervalMs?: number + /** Milliseconds between two reads of the review page's navigation count while it is shown. */ + reviewCountIntervalMs?: number + /** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */ + reviewMaxBackoffMs?: number + /** Most change requests one review page list shows, capped by each provider's own limit. */ + reviewPageSize?: number } ``` @@ -1343,7 +1351,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1388,6 +1396,8 @@ export interface Config { maxCommits?: number /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ maxViewedFiles?: number + /** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */ + maxViewerItems?: number } ``` @@ -1681,6 +1691,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-feishu` + +- `inject`: `cliAccounts` · `skills` +- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts) + +```ts config-catalog +/** Where lark-cli is. */ +export interface Config { + /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + binDir?: string +} +``` + + @@ -2127,6 +2154,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-linear` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/linear/src/index.ts:29`](../packages/connector/linear/src/index.ts) + +```ts config-catalog +/** Linear MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Linear's hosted server. */ + url: string + /** `on-demand` (default) keeps Linear's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + @@ -2776,6 +2822,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-notion` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/notion/src/index.ts:29`](../packages/connector/notion/src/index.ts) + +```ts config-catalog +/** Notion MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Notion's hosted server. */ + url: string + /** `on-demand` (default) keeps Notion's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + @@ -3219,7 +3284,7 @@ export interface Config { - `inject`: `sessionProjections` - `refs`: [`SandboxMode`](subsystems/sandbox.md) -- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:95`](../packages/sandbox/sandbox-policy/src/index.ts) +- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:96`](../packages/sandbox/sandbox-policy/src/index.ts) ```ts config-catalog /** @@ -3233,8 +3298,9 @@ export interface Config { /** File-sandbox mode a session starts from (default: `read-only`). */ mode?: SandboxMode /** - * Absolute fallback root for agentless calls and sessions without a cwd (default: - * `process.cwd()`). Normal agent calls use their session cwd instead. + * Absolute fallback root for agentless calls and, without the working-directory + * service, sessions without a header directory (default: `process.cwd()`). + * Normal agent calls use their session's working directory instead. */ workspaceRoot?: string /** @@ -4159,6 +4225,44 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tencent-docs` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/tencent-docs/src/index.ts:30`](../packages/connector/tencent-docs/src/index.ts) + +```ts config-catalog +/** Tencent Docs MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Tencent Docs' hosted server. */ + url: string + /** `on-demand` (default) keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + + + + +## `@deepseek-ai/dsh-tencent-meeting` + +- `inject`: `cliAccounts` · `upstreamSkills` +- `source`: [`packages/connector/tencent-meeting/src/index.ts:28`](../packages/connector/tencent-meeting/src/index.ts) + +```ts config-catalog +/** Where tmeet and the upstream guide are. */ +export interface Config { + /** Absolute directory holding the `tmeet` executable; defaults to the installed `@tencentcloud/tmeet` executable for this platform. */ + binDir?: string + /** Absolute directory holding the upstream guide at its repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} +``` + + @@ -5053,7 +5157,7 @@ export interface Config { ## `@deepseek-ai/dsh-upstream-skills` - `inject`: `skills` -- `source`: [`packages/connector/upstream-skills/src/index.ts:32`](../packages/connector/upstream-skills/src/index.ts) +- `source`: [`packages/connector/upstream-skills/src/index.ts:35`](../packages/connector/upstream-skills/src/index.ts) ```ts config-catalog /** Where every registered plugin's upstream files are downloaded from. */ @@ -5106,7 +5210,7 @@ export type ApprovalPolicy = 'ask' | 'never' ## `@deepseek-ai/dsh-web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web/src/index.ts:62`](../packages/web/web/src/index.ts) +- `source`: [`packages/web/web/src/index.ts:77`](../packages/web/web/src/index.ts) ```ts config-catalog /** @@ -5118,7 +5222,10 @@ export type ApprovalPolicy = 'ask' | 'never' * fields rather than introduce a hidden priority chain. */ export interface WebRuntimeConfig { - /** Explicit search provider id. Omitted = auto-select when exactly one usable. */ + /** + * Explicit search provider id. Omitted = the usable DeepSeek provider assigned to the route of the model + * request, and otherwise auto-select when exactly one usable. + */ readonly searchProvider: Volatile /** Explicit fetch provider id. Omitted = auto-select when exactly one usable. */ readonly fetchProvider: Volatile @@ -5289,6 +5396,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-wecom` + +- `inject`: `cliAccounts` · `upstreamSkills` +- `source`: [`packages/connector/wecom/src/index.ts:28`](../packages/connector/wecom/src/index.ts) + +```ts config-catalog +/** Where wecom-cli and the upstream guides are. */ +export interface Config { + /** Absolute directory holding the `wecom-cli` executable; defaults to the installed platform package of `@wecom/cli`. */ + binDir?: string + /** Absolute directory holding the upstream guides at their repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} +``` + + @@ -5337,7 +5463,7 @@ export interface Config { ## `@deepseek-ai/dsh-workspace-changes` - `inject`: `subprocess` · `fs` -- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts) +- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts) ```ts config-catalog /** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index dcc2fdcd63..fa780583ed 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -359,7 +359,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-files` - `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert` -- `source`: [`packages/api/workspace-files/src/index.ts:74`](../packages/api/workspace-files/src/index.ts) +- `source`: [`packages/api/workspace-files/src/index.ts:100`](../packages/api/workspace-files/src/index.ts) ```ts config-catalog /** Deployment caps on one page, one listing, or one search. */ @@ -1257,7 +1257,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:530`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:587`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1312,6 +1312,14 @@ export interface Config { maxCachedLensBytes?: number /** Most line annotations a changes view shows in one file, across every annotation source. */ maxAnnotationsPerFile?: number + /** Milliseconds between two reads of the review page's lists while the page is open. */ + reviewListIntervalMs?: number + /** Milliseconds between two reads of the review page's navigation count while it is shown. */ + reviewCountIntervalMs?: number + /** Largest delay in milliseconds between two reads of the review page's lists or count after consecutive failures. */ + reviewMaxBackoffMs?: number + /** Most change requests one review page list shows, capped by each provider's own limit. */ + reviewPageSize?: number } ``` @@ -1345,7 +1353,7 @@ export interface Config { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:767`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1390,6 +1398,8 @@ export interface Config { maxCommits?: number /** Most files whose viewed marks one read lists; GitHub lists at most 3,000 files of a pull request. */ maxViewedFiles?: number + /** Most pull requests one viewer list read returns, at most 100, the size of one GitHub search page. */ + maxViewerItems?: number } ``` @@ -1683,6 +1693,23 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-feishu` + +- `inject`: `cliAccounts` · `skills` +- `source`: [`packages/connector/feishu/src/index.ts:30`](../packages/connector/feishu/src/index.ts) + +```ts config-catalog +/** Where lark-cli is. */ +export interface Config { + /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + binDir?: string +} +``` + + @@ -2129,6 +2156,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-linear` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/linear/src/index.ts:29`](../packages/connector/linear/src/index.ts) + +```ts config-catalog +/** Linear MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Linear's hosted server. */ + url: string + /** `on-demand` (default) keeps Linear's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + @@ -2778,6 +2824,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-notion` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/notion/src/index.ts:29`](../packages/connector/notion/src/index.ts) + +```ts config-catalog +/** Notion MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Notion's hosted server. */ + url: string + /** `on-demand` (default) keeps Notion's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + @@ -3221,7 +3286,7 @@ export interface Config { - `inject`: `sessionProjections` - `refs`: [`SandboxMode`](subsystems/sandbox.zh.md) -- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:95`](../packages/sandbox/sandbox-policy/src/index.ts) +- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:96`](../packages/sandbox/sandbox-policy/src/index.ts) ```ts config-catalog /** @@ -3235,8 +3300,9 @@ export interface Config { /** File-sandbox mode a session starts from (default: `read-only`). */ mode?: SandboxMode /** - * Absolute fallback root for agentless calls and sessions without a cwd (default: - * `process.cwd()`). Normal agent calls use their session cwd instead. + * Absolute fallback root for agentless calls and, without the working-directory + * service, sessions without a header directory (default: `process.cwd()`). + * Normal agent calls use their session's working directory instead. */ workspaceRoot?: string /** @@ -4161,6 +4227,44 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-tencent-docs` + +- `inject`: `mcpManager` · `systemPrompt` +- `source`: [`packages/connector/tencent-docs/src/index.ts:30`](../packages/connector/tencent-docs/src/index.ts) + +```ts config-catalog +/** Tencent Docs MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Tencent Docs' hosted server. */ + url: string + /** `on-demand` (default) keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} +``` + + + + + +## `@deepseek-ai/dsh-tencent-meeting` + +- `inject`: `cliAccounts` · `upstreamSkills` +- `source`: [`packages/connector/tencent-meeting/src/index.ts:28`](../packages/connector/tencent-meeting/src/index.ts) + +```ts config-catalog +/** Where tmeet and the upstream guide are. */ +export interface Config { + /** Absolute directory holding the `tmeet` executable; defaults to the installed `@tencentcloud/tmeet` executable for this platform. */ + binDir?: string + /** Absolute directory holding the upstream guide at its repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} +``` + + @@ -5055,7 +5159,7 @@ export interface Config { ## `@deepseek-ai/dsh-upstream-skills` - `inject`: `skills` -- `source`: [`packages/connector/upstream-skills/src/index.ts:32`](../packages/connector/upstream-skills/src/index.ts) +- `source`: [`packages/connector/upstream-skills/src/index.ts:35`](../packages/connector/upstream-skills/src/index.ts) ```ts config-catalog /** Where every registered plugin's upstream files are downloaded from. */ @@ -5108,7 +5212,7 @@ export type ApprovalPolicy = 'ask' | 'never' ## `@deepseek-ai/dsh-web` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/web/web/src/index.ts:62`](../packages/web/web/src/index.ts) +- `source`: [`packages/web/web/src/index.ts:77`](../packages/web/web/src/index.ts) ```ts config-catalog /** @@ -5120,7 +5224,10 @@ export type ApprovalPolicy = 'ask' | 'never' * fields rather than introduce a hidden priority chain. */ export interface WebRuntimeConfig { - /** Explicit search provider id. Omitted = auto-select when exactly one usable. */ + /** + * Explicit search provider id. Omitted = the usable DeepSeek provider assigned to the route of the model + * request, and otherwise auto-select when exactly one usable. + */ readonly searchProvider: Volatile /** Explicit fetch provider id. Omitted = auto-select when exactly one usable. */ readonly fetchProvider: Volatile @@ -5291,6 +5398,25 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-wecom` + +- `inject`: `cliAccounts` · `upstreamSkills` +- `source`: [`packages/connector/wecom/src/index.ts:28`](../packages/connector/wecom/src/index.ts) + +```ts config-catalog +/** Where wecom-cli and the upstream guides are. */ +export interface Config { + /** Absolute directory holding the `wecom-cli` executable; defaults to the installed platform package of `@wecom/cli`. */ + binDir?: string + /** Absolute directory holding the upstream guides at their repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} +``` + + @@ -5339,7 +5465,7 @@ export interface Config { ## `@deepseek-ai/dsh-workspace-changes` - `inject`: `subprocess` · `fs` -- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts) +- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts) ```ts config-catalog /** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 4ab58e2ab2..e96b587b0b 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `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:31`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:40`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../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:75`](../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:93`](../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` | @@ -73,8 +73,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../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`) | `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`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:79`](../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-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `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), `client-ui-forge`, `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:79`](../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), [`cua`](../packages/experimental/cua), [`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-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -109,7 +109,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:157`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:148`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:164`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | -| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:26`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - | +| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:25`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - | ## Non-harness or undeclared event strings seen in package source diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 510f50ad26..ae302bc17b 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -49,8 +49,8 @@ | `deepseek-account/signed-out` | `emit` | [`packages/account/deepseek-account/src/index.ts:28`](../packages/account/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/account/deepseek-account) (`emit`) | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | | `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:31`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` | -| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:40`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | +| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:32`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge`, `forge-session` | +| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:41`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` | | `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:83`](../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:75`](../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:93`](../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` | @@ -75,8 +75,8 @@ | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:72`](../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`) | `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`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:79`](../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-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `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), `client-ui-forge`, `file-upload`, `forge-session`, [`office-kit`](../packages/document/office-kit), `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:79`](../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), [`cua`](../packages/experimental/cua), [`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-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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), [`timeline`](../packages/experimental/timeline), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-office`](../packages/document/tool-office), `ui-session-status`, `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:87`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-persistence-sqlite`](../packages/session/session-persistence-sqlite), [`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:299`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -111,7 +111,7 @@ | `workspace/session-archived` | `parallel` | [`packages/workspace/workspace/src/index.ts:157`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | | `workspace/session-stop` | `parallel` | [`packages/workspace/workspace/src/index.ts:148`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | [`agent`](../packages/core/agent), [`jobs`](../packages/jobs/jobs), [`schedule`](../packages/schedule/schedule), [`subagent`](../packages/subagent/subagent) | | `workspace/session-unarchiving` | `parallel` | [`packages/workspace/workspace/src/index.ts:164`](../packages/workspace/workspace/src/index.ts) | [`workspace`](../packages/workspace/workspace) (`parallel`) | `worktree` | -| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:26`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - | +| `worktree/cleanup` | `emit` | [`packages/experimental/worktree/src/archive.ts:25`](../packages/experimental/worktree/src/archive.ts) | `worktree` (`emit`) | - | ## Non-harness or undeclared event strings seen in package source diff --git a/docs/module-graph.md b/docs/module-graph.md index aba40c3a06..da032e1d4a 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -245,7 +245,13 @@ flowchart TD subgraph group_connector["packages/connector"] pkg_cli_account["cli-account"] pkg_dingtalk["dingtalk"] + pkg_feishu["feishu"] + pkg_linear["linear"] + pkg_notion["notion"] + pkg_tencent_docs["tencent-docs"] + pkg_tencent_meeting["tencent-meeting"] pkg_upstream_skills["upstream-skills"] + pkg_wecom["wecom"] end subgraph group_context["packages/context"] pkg_agent_instructions["agent-instructions"] @@ -688,6 +694,12 @@ flowchart TD pkg_api_workspace_controller --> pkg_workspace pkg_dingtalk --> pkg_cli_account pkg_dingtalk --> pkg_skill + pkg_feishu --> pkg_cli_account + pkg_feishu --> pkg_skill + pkg_tencent_meeting --> pkg_cli_account + pkg_tencent_meeting --> pkg_upstream_skills + pkg_wecom --> pkg_cli_account + pkg_wecom --> pkg_upstream_skills pkg_experimental_api_speech_to_text --> pkg_experimental_speech_to_text pkg_experimental_api_speech_to_text --> pkg_typert_protocol pkg_experimental_client_ui_cot_translation --> pkg_experimental_translator @@ -969,6 +981,7 @@ flowchart TD pkg_workspace_changes --> pkg_session pkg_workspace_changes --> pkg_subprocess pkg_workspace_changes --> pkg_tools + pkg_workspace_changes --> pkg_working_directory pkg_creation_recommendations --> pkg_llm pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill @@ -1605,6 +1618,7 @@ flowchart TD pkg_sdk_jsonrpc_server --> pkg_subagent pkg_sdk_jsonrpc_server --> pkg_user_approval pkg_sdk_jsonrpc_server --> pkg_user_questions + pkg_sdk_jsonrpc_server --> pkg_util_time pkg_sdk_jsonrpc_server --> pkg_working_directory ``` @@ -1721,6 +1735,9 @@ flowchart TD | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | — | +| [`linear`](../packages/connector/linear) | `connector` | — | +| [`notion`](../packages/connector/notion) | `connector` | — | +| [`tencent-docs`](../packages/connector/tencent-docs) | `connector` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1844,6 +1861,9 @@ flowchart TD | [`deepseek-auth`](../packages/account/deepseek-auth) | `account` | [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`error`](../packages/util/error), [`launch-environment`](../packages/util/launch-environment) | | [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) | | [`dingtalk`](../packages/connector/dingtalk) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`tencent-meeting`](../packages/connector/tencent-meeting) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | +| [`wecom`](../packages/connector/wecom) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) | | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | @@ -1903,7 +1923,7 @@ flowchart TD | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`file-reference-local`](../packages/context/file-reference-local) | `context` | [`agent`](../packages/core/agent), [`file-reference`](../packages/context/file-reference), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-present`](../packages/deliverables/tool-present) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | | [`cua-macos`](../packages/experimental/cua-macos) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | @@ -2000,5 +2020,5 @@ flowchart TD | [`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-session-status`](../packages/client/ui-session-status), [`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), [`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), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`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) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`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), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 2afe8ed98a..b004bd752f 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -247,7 +247,13 @@ flowchart TD subgraph group_connector["packages/connector"] pkg_cli_account["cli-account"] pkg_dingtalk["dingtalk"] + pkg_feishu["feishu"] + pkg_linear["linear"] + pkg_notion["notion"] + pkg_tencent_docs["tencent-docs"] + pkg_tencent_meeting["tencent-meeting"] pkg_upstream_skills["upstream-skills"] + pkg_wecom["wecom"] end subgraph group_context["packages/context"] pkg_agent_instructions["agent-instructions"] @@ -690,6 +696,12 @@ flowchart TD pkg_api_workspace_controller --> pkg_workspace pkg_dingtalk --> pkg_cli_account pkg_dingtalk --> pkg_skill + pkg_feishu --> pkg_cli_account + pkg_feishu --> pkg_skill + pkg_tencent_meeting --> pkg_cli_account + pkg_tencent_meeting --> pkg_upstream_skills + pkg_wecom --> pkg_cli_account + pkg_wecom --> pkg_upstream_skills pkg_experimental_api_speech_to_text --> pkg_experimental_speech_to_text pkg_experimental_api_speech_to_text --> pkg_typert_protocol pkg_experimental_client_ui_cot_translation --> pkg_experimental_translator @@ -971,6 +983,7 @@ flowchart TD pkg_workspace_changes --> pkg_session pkg_workspace_changes --> pkg_subprocess pkg_workspace_changes --> pkg_tools + pkg_workspace_changes --> pkg_working_directory pkg_creation_recommendations --> pkg_llm pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill @@ -1607,6 +1620,7 @@ flowchart TD pkg_sdk_jsonrpc_server --> pkg_subagent pkg_sdk_jsonrpc_server --> pkg_user_approval pkg_sdk_jsonrpc_server --> pkg_user_questions + pkg_sdk_jsonrpc_server --> pkg_util_time pkg_sdk_jsonrpc_server --> pkg_working_directory ``` @@ -1723,6 +1737,9 @@ flowchart TD | [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | — | | [`client-web`](../packages/client/web) | `client` | — | | [`computer-use`](../packages/computer-use/computer-use) | `computer-use` | — | +| [`linear`](../packages/connector/linear) | `connector` | — | +| [`notion`](../packages/connector/notion) | `connector` | — | +| [`tencent-docs`](../packages/connector/tencent-docs) | `connector` | — | | [`office-kit`](../packages/document/office-kit) | `document` | — | | [`client-ui-action-cards`](../packages/experimental/client-ui-action-cards) | `experimental` | — | | [`client-ui-creation-recommendations`](../packages/experimental/client-ui-creation-recommendations) | `experimental` | — | @@ -1846,6 +1863,9 @@ flowchart TD | [`deepseek-auth`](../packages/account/deepseek-auth) | `account` | [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/account/deepseek-account), [`error`](../packages/util/error), [`launch-environment`](../packages/util/launch-environment) | | [`api-workspace-controller`](../packages/api/workspace-controller) | `api` | [`api-gateway`](../packages/api/gateway), [`client-connection`](../packages/client/connection), [`host-directory-picker`](../packages/host/directory-picker), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`typert-protocol`](../packages/typert/protocol), [`workspace`](../packages/workspace/workspace) | | [`dingtalk`](../packages/connector/dingtalk) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`feishu`](../packages/connector/feishu) | `connector` | [`cli-account`](../packages/connector/cli-account), [`skill`](../packages/skill/skill) | +| [`tencent-meeting`](../packages/connector/tencent-meeting) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | +| [`wecom`](../packages/connector/wecom) | `connector` | [`cli-account`](../packages/connector/cli-account), [`upstream-skills`](../packages/connector/upstream-skills) | | [`experimental-api-speech-to-text`](../packages/experimental/api-speech-to-text) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`typert-protocol`](../packages/typert/protocol) | | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | `experimental` | [`experimental-translator`](../packages/experimental/translator) | | [`experimental-speech-to-text-sensevoice`](../packages/experimental/speech-to-text-sensevoice) | `experimental` | [`experimental-speech-to-text`](../packages/experimental/speech-to-text), [`subprocess`](../packages/subprocess/subprocess) | @@ -1905,7 +1925,7 @@ flowchart TD | [`agent-instructions`](../packages/context/agent-instructions) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`home-paths`](../packages/util/home-paths), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`file-reference-local`](../packages/context/file-reference-local) | `context` | [`agent`](../packages/core/agent), [`file-reference`](../packages/context/file-reference), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`tool-present`](../packages/deliverables/tool-present) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | -| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | +| [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | | [`cua-macos`](../packages/experimental/cua-macos) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | | [`cua-windows`](../packages/experimental/cua-windows) | `experimental` | [`agent`](../packages/core/agent), [`computer-use`](../packages/computer-use/computer-use), [`subprocess`](../packages/subprocess/subprocess), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`user-questions`](../packages/interaction/user-questions) | @@ -2002,5 +2022,5 @@ flowchart TD | [`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-session-status`](../packages/client/ui-session-status), [`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), [`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), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`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) | +| [`sdk-jsonrpc-server`](../packages/sdk/server) | `sdk` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`commands`](../packages/interaction/commands), [`deepseek-auth`](../packages/account/deepseek-auth), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm), [`llm-deepseek-api-key`](../packages/llm/llm-deepseek-api-key), [`permission-presets`](../packages/interaction/permission-presets), [`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), [`util-time`](../packages/util/time), [`working-directory`](../packages/session/working-directory) | diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index 73ca9368d8..4bd9b203ea 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: 3de1bc82a91b1fda - zh: e4268205f18b81e8 + en: bbdeea7adbc0bf30 + zh: ed1eea613a6cb14b /session-persistence-event-catalog/event-envelope: en: 5cae0233560db4d6 zh: c8f5efc48be52095 @@ -1038,11 +1038,11 @@ en: a6a2e38fdd6d127a zh: 1fe82356d89f5769 /session-persistence-event-catalog/resolved-persistence-types/deepseeksearchllmrequest: - en: c2b2df63604aa276 - zh: ae73f57f53bb85a0 + en: e044fc1cee2eb7d4 + zh: efe705bce6fc0ef9 /session-persistence-event-catalog/resolved-persistence-types/developermessage: - en: a3f7241ba795de1e - zh: 084d2dd90601b2b3 + en: 116cc4dc07d18606 + zh: 3f91cbe2b5fff144 /session-persistence-event-catalog/resolved-persistence-types/epochheader: en: fa7fd1a765a494e2 zh: fd8e6fdd37d986cf @@ -1152,11 +1152,11 @@ en: 6dbe099c62f7c226 zh: 6fd788f63c038c91 /session-persistence-event-catalog/resolved-persistence-types/llmretrystartedeventdata: - en: 43a03018774afdb4 - zh: 5759aca7d706bf82 + en: cf2fa679500b170f + zh: c5ae8545aede2062 /session-persistence-event-catalog/resolved-persistence-types/message: - en: 306e5ce73c068078 - zh: ea083b295f6821ad + en: 43a4e4bd1200fc62 + zh: 0358110cfec20dd7 /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackdelete: en: c582953270d4ca44 zh: 966ccfe2e7660a2a @@ -1167,14 +1167,14 @@ en: f58575a1fc96df42 zh: 9f0c6ed9033e5c9d /session-persistence-event-catalog/resolved-persistence-types/messagefeedbackrating: - en: d2a0b0ad71c0d335 - zh: d11dd6deea395886 + en: 8056c68bde26363d + zh: d8cbe789276124b1 /session-persistence-event-catalog/resolved-persistence-types/messagesource: - en: 9521558a9dc6d38d - zh: 8f6f0e1ff972d32c + en: 908ec41c770af7d9 + zh: bf07ae6532c9e850 /session-persistence-event-catalog/resolved-persistence-types/message~2: - en: c0e7625fd450e041 - zh: 3dcfa3d131de5897 + en: 93d183436da8c385 + zh: c877886104c2a594 /session-persistence-event-catalog/resolved-persistence-types/modelmessagesource: en: 65a618e2ec94bbc4 zh: 622197f4b127068b @@ -1233,11 +1233,11 @@ en: 9a54c4478ad3b620 zh: 02c4c1fd7e252770 /session-persistence-event-catalog/resolved-persistence-types/sessiontitleeventdata: - en: 6cf1e7c94a274a24 - zh: 2bce42bf52d0e574 + en: cdcdc0620e6d7c49 + zh: 3a4e98cb9544c12e /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: 20ffa8747ad5abab - zh: 836ca9717eafedf3 + en: 8a721906148e35c3 + zh: 4964b375d0a1bd9f /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 7a7245bb23c38655 zh: 6d96a94c367fbe64 @@ -1347,14 +1347,14 @@ en: 73fde4d98617b19f zh: adae612c15a67764 /session-persistence-event-catalog/resolved-persistence-types/turnendreason: - en: 8b69c6e26f5843ad - zh: 7515d5a3f2419709 + en: 883ed71f55d838fd + zh: 6e5251555f9fa362 /session-persistence-event-catalog/resolved-persistence-types/usermessage: - en: da2ff374580fcaa8 - zh: b92e64d68122c337 + en: 2efbd385157c572a + zh: 8472acc0f626ce58 /session-persistence-event-catalog/resolved-persistence-types/usermessage~2: - en: 6410d8545a391c2b - zh: d9e90b3c5796f76a + en: 7df6a7019dc1adbf + zh: 1f193dc2d0dc672e /session-persistence-event-catalog/resolved-persistence-types/workflowagentoutcome: en: 711564ea7898e156 zh: 36b88b84a6dc3c7e @@ -1485,8 +1485,14 @@ en: 43cf5cd666b591a0 zh: 7c7a3011f8681f12 /session-persistence-event-catalog/resolved-persistence-types/childcreatedat-childid-label-mode~8: - en: a1f188c9058cf621 - zh: eb43c0f045fb9afb + en: 514f7ff5d2f88c07 + zh: b62cd87601f92642 +/session-persistence-event-catalog/resolved-persistence-types/clienttimezone-kind-user: + en: 62beba431162c85e + zh: 2a3aafe663ce31c6 +/session-persistence-event-catalog/resolved-persistence-types/clienttimezone-kind-user-principal-rpcid: + en: 90d6159479e5d717 + zh: c4dbebd0950e55e9 /session-persistence-event-catalog/resolved-persistence-types/code-name-reason: en: 7ae42d830651c83c zh: 1387de7f803d9f08 @@ -1551,11 +1557,11 @@ en: 4cb1c48095df98dc zh: 5a03e44761af559e /session-persistence-event-catalog/resolved-persistence-types/header-reason-startsseries: - en: 025df3bb1bbc5369 - zh: 52015f4decd2f1e5 + en: 747233c059621ae6 + zh: c43d942a7feb996f /session-persistence-event-catalog/resolved-persistence-types/headerseq-message-step-turn: - en: e06f7b64a1665de2 - zh: cc2280a56d63cb50 + en: 4a0977d6ef222a05 + zh: a85ce6839bc04604 /session-persistence-event-catalog/resolved-persistence-types/height-width: en: a5df50710083ac25 zh: aad3ccf6f6de70e4 @@ -1572,11 +1578,11 @@ en: 41f73c58a77dfa28 zh: af77f4aee3cb4a40 /session-persistence-event-catalog/resolved-persistence-types/inherited: - en: 828241cf325d2bec - zh: f53b66d8e6e8a41c + en: 26b15ad93125db72 + zh: 78b407367bbebe52 /session-persistence-event-catalog/resolved-persistence-types/inserted-outcome-removedcount-start: - en: cdd4832101b8d5c1 - zh: a98f9c6cb6701d78 + en: c43e5f1a961a97c7 + zh: 4ab16a990eca92ff /session-persistence-event-catalog/resolved-persistence-types/interrupted-message-step-stream: en: 35e45d462a41e963 zh: 89953d22ddada652 @@ -1911,11 +1917,8 @@ en: 08be4349548406a9 zh: 8e7cf9966198ef78 /session-persistence-event-catalog/resolved-persistence-types/kind-tool-registry: - en: 4e102391d685eff5 - zh: 9762243a13014f3d -/session-persistence-event-catalog/resolved-persistence-types/kind-user: - en: 156e57c019aa1b28 - zh: a1629b267f7cc713 + en: 33f81e65eab6b5f4 + zh: a909a08515ee73ec /session-persistence-event-catalog/resolved-persistence-types/kind-user-approval: en: a52d2dfbaf844127 zh: 4c5306ca40f20873 @@ -2001,11 +2004,11 @@ en: e0d6826170f96136 zh: c684a666de7cee7c /session-persistence-event-catalog/resolved-persistence-types/type-agent-preset-selected: - en: 3ffd4ea16273b2e2 - zh: 0f8cc2f25c129db2 + en: 6f4e460cc02ecb54 + zh: cbc4655190a0596a /session-persistence-event-catalog/resolved-persistence-types/type-agent-inbox-spliced: - en: 8595e5be01110031 - zh: e53835bbc7208402 + en: bfa17b1dd35c840a + zh: 3cd4658024ce7417 /session-persistence-event-catalog/resolved-persistence-types/type-approval-asked: en: 9c77f18b0dad22f0 zh: 8894cf2878fe90db @@ -2049,11 +2052,11 @@ en: ba73fb10b7e2ffc9 zh: 8d5c97e63e5f16da /session-persistence-event-catalog/resolved-persistence-types/type-deliverables-presented: - en: dee59c4cab27840e - zh: d2203a7a79799d1d + en: 9804c72cee421005 + zh: 27b031dee4e371c4 /session-persistence-event-catalog/resolved-persistence-types/type-developer-message: - en: 5c0287505cfa913b - zh: 5e783b2e19464855 + en: 75fd3954fcf8628d + zh: 69d808b702e90e15 /session-persistence-event-catalog/resolved-persistence-types/type-disabled: en: 04db8a26a3befdd4 zh: 8b24a37ac00bac8a @@ -2127,11 +2130,11 @@ en: acf7e21e4d21ebff zh: fb83a853634d204a /session-persistence-event-catalog/resolved-persistence-types/type-session-title: - en: d138c51e1202a7f0 - zh: 80bc77ae672ad43e + en: 978de727067fd9e1 + zh: 6a4c91b2aa5479ad /session-persistence-event-catalog/resolved-persistence-types/type-session-title-llm-request: - en: 88d1abda906b892d - zh: 010692a91ea0139d + en: aeb2eb7f645f92a0 + zh: ecf4aa7d6247628b /session-persistence-event-catalog/resolved-persistence-types/type-step-end: en: 7fc233c4a569dae2 zh: bc2b3fed4a397c00 @@ -2211,11 +2214,11 @@ en: 1b045de96172be4b zh: 8a15c6f35b576b37 /session-persistence-event-catalog/resolved-persistence-types/type-usage: - en: 0ce623d4c59f5a2f - zh: 2d830e6e1badb1ba + en: 7e301e838a718abd + zh: fbf004287370a259 /session-persistence-event-catalog/resolved-persistence-types/type-user-message: - en: 6e4884da342f291a - zh: 454973316ff24910 + en: 6a3fdd4c0501be4a + zh: b5ddb6da9843466d /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 ea4be01ac2..517848d300 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 | `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64) | +| `event:agent/inbox/spliced` | event | `5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb) | | `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 | `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` | [`{ type: "developer/message" }`](#persistence-type-sha256-7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd) | +| `event:developer/message` | event | `53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e` | [`{ type: "developer/message" }`](#persistence-type-sha256-53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e) | | `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 | `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2) | +| `event:session/title-llm-request` | event | `5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260) | | `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 | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -81,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 | `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` | [`{ type: "user/message" }`](#persistence-type-sha256-fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a) | +| `event:user/message` | event | `3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a` | [`{ type: "user/message" }`](#persistence-type-sha256-3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a) | | `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-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -3464,7 +3464,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web | `body` | required | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | required | `string` | - + @@ -3472,7 +3472,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:56`](../packages/web ### `DeveloperMessage` -SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` +SHA-256: `3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7` Sources: [`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message.ts) @@ -3481,7 +3481,7 @@ Sources: [`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"developer"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b) | Source compatibility: `source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4180,7 +4180,7 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr | `step` | required | `number` | | `turn` | required | `number` | - + @@ -4188,15 +4188,15 @@ Sources: [`packages/llm/llm-retry/src/types.ts:43`](../packages/llm/llm-retry/sr ### `Message` -SHA-256: `45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4` +SHA-256: `d73dbb5105041633eb357c9df0f1ae7fbfc911b00250b8b3c84d81fe319c8ae7` Sources: [`packages/llm/llm/src/message.ts:195`](../packages/llm/llm/src/message.ts) One of: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) -- [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) +- [`DeveloperMessage`](#persistence-type-sha256-3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7) +- [`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4273,7 +4273,7 @@ One of: - `"negative"` - `"positive"` - + @@ -4281,7 +4281,7 @@ One of: ### `MessageSource` -SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` +SHA-256: `7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b` Sources: [`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message.ts) @@ -4395,8 +4395,9 @@ Sources: [`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message | `tool-jobs` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "tool-jobs", form: "snapshot" }`](#persistence-type-sha256-c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49) | | `tool-jobs` | not declared | none | [`{ kind: "tool-jobs" }`](#persistence-type-sha256-24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8) | | `tool-registry` | not declared | none | [`{ kind: "tool-registry" }`](#persistence-type-sha256-8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543) | -| `user` | not declared | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302) | +| `user` | not declared | `rpcId`: `string` | [`{ clientTimeZone?, kind: "user", principal?, rpcId }`](#persistence-type-sha256-a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302) | | `user` | not declared | none | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | +| `user` | not declared | none | [`{ clientTimeZone?, kind: "user" }`](#persistence-type-sha256-b8ed92a5ca59733f046ea3506d64c35c64044b6a084fd51daee4c6c72727d39f) | | `user-approval` | `"catalog"` | none | [`{ kind: "user-approval", form: "catalog" }`](#persistence-type-sha256-825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8) | | `user-approval` | `"instructions"` | none | [`{ kind: "user-approval", form: "instructions" }`](#persistence-type-sha256-aa2bf9e82b9fdeb94a42af20031fffa30e4e23f01f4ac39757427d4c64c407f0) | | `user-approval` | `"notice"` | `summary`: `string` | [`{ kind: "user-approval", form: "notice" }`](#persistence-type-sha256-6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4) | @@ -4408,13 +4409,13 @@ Sources: [`packages/llm/llm/src/message.ts:135`](../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: `39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92` +SHA-256: `02193e4f882eee79523902b49c0f93d92eb5fc85aaa747c39bba9f42d319329a` -Array of [`Message`](#persistence-type-sha256-45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4). +Array of [`Message`](#persistence-type-sha256-d73dbb5105041633eb357c9df0f1ae7fbfc911b00250b8b3c84d81fe319c8ae7). @@ -4782,7 +4783,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ | `source` | required | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | required | `string` | - + @@ -4790,7 +4791,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ ### `SessionTitleLlmRequestEventData` -SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` +SHA-256: `8e0a3b4e470f634cfea5b9c6351dd34d8c819ddedd41a4c30eecde2017c9fd69` Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4798,7 +4799,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-39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92) | +| `messages` | required | [`Message[]`](#persistence-type-sha256-02193e4f882eee79523902b49c0f93d92eb5fc85aaa747c39bba9f42d319329a) | | `reasoningEffort` | optional | `string` | | `route` | required | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | required | `string` | @@ -5477,7 +5478,7 @@ Sources: [`packages/core/session/src/types.ts:242`](../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) | - + @@ -5485,7 +5486,7 @@ Sources: [`packages/core/session/src/types.ts:242`](../packages/core/session/src ### `UserMessage` -SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` +SHA-256: `120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499` Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -5494,19 +5495,19 @@ Sources: [`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message | `content` | required | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | required | `string` | | `role` | required | `"user"` | -| `source` | required | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | required | [`MessageSource`](#persistence-type-sha256-7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b) | 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: `300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70` +SHA-256: `6c0f8aded45d4b3194ba7a67bab10ec31e401dfa976e84b392911b5a221b0f85` -Array of [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212). +Array of [`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499). @@ -6141,6 +6142,34 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` | `mode` | required | `"external"` | | `version` | required | `2` | + + +### `{ clientTimeZone?, kind: "user" }` + +SHA-256: `b8ed92a5ca59733f046ea3506d64c35c64044b6a084fd51daee4c6c72727d39f` + +Sources: [`packages/sdk/server/src/server.ts:54`](../packages/sdk/server/src/server.ts) + +| Property | Presence | Type | +|---|---|---| +| `clientTimeZone` | optional | `string` | +| `kind` | required | `"user"` | + + + +### `{ clientTimeZone?, kind: "user", principal?, rpcId }` + +SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` + +Sources: [`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) + +| Property | Presence | Type | +|---|---|---| +| `clientTimeZone` | optional | `string` | +| `kind` | required | `"user"` | +| `principal` | optional | [`union (2 variants)`](#persistence-type-sha256-824a4aad44a54e245c67196817d67946734a2dc0eee0b0b6834a5b2a6ef352ce) | +| `rpcId` | required | `string` | + ### `{ code, name, reason? }` @@ -6471,18 +6500,18 @@ Sources: [`packages/core/session/src/types.ts:402`](../packages/core/session/src | `reason` | required | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | optional | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde` +SHA-256: `27f8b01d8292dda6a9b9d907fc0e8c811836301d0b9cd225afe9d60bbc367f44` Sources: [`packages/core/session/src/types.ts:321`](../packages/core/session/src/types.ts) | Property | Presence | Type | |---|---|---| | `headerSeq` | optional | `number` | -| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) | +| `message` | required | [`DeveloperMessage`](#persistence-type-sha256-3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7) | | `step` | required | `number` | | `turn` | required | `number` | @@ -6566,17 +6595,17 @@ Sources: [`packages/core/session/src/types.ts:439`](../packages/core/session/src |---|---|---| | `inherited` | optional | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5` +SHA-256: `d7c6a501b0381f8ee4430880905bc335a8089ebc57b2a65c3507bee9473ee3c4` Sources: [`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | Property | Presence | Type | |---|---|---| -| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70) | +| `inserted` | required | [`UserMessage[]`](#persistence-type-sha256-6c0f8aded45d4b3194ba7a67bab10ec31e401dfa976e84b392911b5a221b0f85) | | `outcome` | optional | `"canceled"` | | `removedCount` | optional | `number` | | `start` | required | `number` | @@ -7869,21 +7898,6 @@ Sources: [`packages/core/tools/src/index.ts:28`](../packages/core/tools/src/inde |---|---|---| | `kind` | required | `"tool-registry"` | - - -### `{ kind: "user" }` - -SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` - -Sources: [`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) - -| Property | Presence | Type | -|---|---|---| -| `clientTimeZone` | optional | `string` | -| `kind` | required | `"user"` | -| `principal` | optional | [`union (2 variants)`](#persistence-type-sha256-824a4aad44a54e245c67196817d67946734a2dc0eee0b0b6834a5b2a6ef352ce) | -| `rpcId` | required | `string` | - ### `{ kind: "user-approval" }` @@ -8264,17 +8278,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | required | `number` | | `type` | required | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` +SHA-256: `5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5) | +| `data` | required | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-d7c6a501b0381f8ee4430880905bc335a8089ebc57b2a65c3507bee9473ee3c4) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -8515,17 +8529,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | required | `number` | | `type` | required | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` +SHA-256: `53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e` | Property | Presence | Type | |---|---|---| -| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde) | +| `data` | required | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-27f8b01d8292dda6a9b9d907fc0e8c811836301d0b9cd225afe9d60bbc367f44) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `sourceEventSeqs` | optional | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8925,17 +8939,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | required | `number` | | `type` | required | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` +SHA-256: `5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260` | Property | Presence | Type | |---|---|---| -| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f) | +| `data` | required | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-8e0a3b4e470f634cfea5b9c6351dd34d8c819ddedd41a4c30eecde2017c9fd69) | | `ignorable` | optional | `true` | | `seq` | required | `number` | | `time` | required | `number` | @@ -9374,17 +9388,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: `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` +SHA-256: `3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a` | Property | Presence | Type | |---|---|---| -| `data` | required | [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) | +| `data` | required | [`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499) | | `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 aa7a5f1a29..a800d81d00 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 | `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64) | +| `event:agent/inbox/spliced` | event | `5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb` | [`{ type: "agent/inbox/spliced" }`](#persistence-type-sha256-5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb) | | `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 | `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` | [`{ type: "developer/message" }`](#persistence-type-sha256-7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd) | +| `event:developer/message` | event | `53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e` | [`{ type: "developer/message" }`](#persistence-type-sha256-53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e) | | `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 | `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2) | +| `event:session/title-llm-request` | event | `5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260` | [`{ type: "session/title-llm-request" }`](#persistence-type-sha256-5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260) | | `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 | `d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41` | [`{ type: "subagent/catalog" }`](#persistence-type-sha256-d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41) | @@ -83,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 | `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` | [`{ type: "user/message" }`](#persistence-type-sha256-fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a) | +| `event:user/message` | event | `3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a` | [`{ type: "user/message" }`](#persistence-type-sha256-3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a) | | `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-root/change` | event | `025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc` | [`{ type: "workspace-root/change" }`](#persistence-type-sha256-025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc) | @@ -3466,7 +3466,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` | `body` | 必需 | [`{ max_tokens, messages, model, thinking?, … }`](#persistence-type-sha256-9c001ecb5e1d3c3894410db2a1e383842e5f8454fb52182338686158abc1b3ee) | | `endpoint` | 必需 | `string` | - + @@ -3474,7 +3474,7 @@ SHA-256: `abd6ca62a5ab166553848324a23fef90eed7f59c8021bd63e7ea5bc6fd666b0c` ### `DeveloperMessage` -SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` +SHA-256: `3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7` 来源:[`packages/llm/llm/src/message.ts:156`](../packages/llm/llm/src/message.ts) @@ -3483,7 +3483,7 @@ SHA-256: `010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"developer"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.developer-message.source`; `kind`; `preserve`. @@ -4182,7 +4182,7 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` | `step` | 必需 | `number` | | `turn` | 必需 | `number` | - + @@ -4190,15 +4190,15 @@ SHA-256: `6f72ece8f317cd080c4f20a93f1bf709965f5b81ac4669528f5a023191cfcf20` ### `Message` -SHA-256: `45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4` +SHA-256: `d73dbb5105041633eb357c9df0f1ae7fbfc911b00250b8b3c84d81fe319c8ae7` 来源:[`packages/llm/llm/src/message.ts:195`](../packages/llm/llm/src/message.ts) 以下类型之一: - [`ToolResultMessage`](#persistence-type-sha256-4b259f7f8f0a44ad5e90b70a73553ced1df27012d126921d397ff403b6c86731) -- [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) -- [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) +- [`DeveloperMessage`](#persistence-type-sha256-3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7) +- [`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499) - [`SystemMessage`](#persistence-type-sha256-09f3f8dc417f278257202714132f98ba7b52957d7b558c4a04456603890eb363) - [`AssistantMessage`](#persistence-type-sha256-fa87537f4a9c1e25602990a8bf686b383e9e00352ec8946e16ae24ba7c1625be) @@ -4275,7 +4275,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` - `"negative"` - `"positive"` - + @@ -4283,7 +4283,7 @@ SHA-256: `390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2` ### `MessageSource` -SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` +SHA-256: `7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b` 来源:[`packages/llm/llm/src/message.ts:135`](../packages/llm/llm/src/message.ts) @@ -4397,8 +4397,9 @@ SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` | `tool-jobs` | `"snapshot"` | `sections`: [`ContextSnapshotSection[]`](#persistence-type-sha256-c748fb42c80a120038a8c587af80ec39924803c401364db11c8974d5bf6d0262) | [`{ kind: "tool-jobs", form: "snapshot" }`](#persistence-type-sha256-c5228b7a55498d84f529591744a0ab26e0b93ade18a70a26db1377a1ecfa6b49) | | `tool-jobs` | 未声明 | 无 | [`{ kind: "tool-jobs" }`](#persistence-type-sha256-24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8) | | `tool-registry` | 未声明 | 无 | [`{ kind: "tool-registry" }`](#persistence-type-sha256-8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543) | -| `user` | 未声明 | `rpcId`: `string` | [`{ kind: "user" }`](#persistence-type-sha256-a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302) | +| `user` | 未声明 | `rpcId`: `string` | [`{ clientTimeZone?, kind: "user", principal?, rpcId }`](#persistence-type-sha256-a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302) | | `user` | 未声明 | 无 | [`CommandSource`](#persistence-type-sha256-ada310bf0bdb8fed51f3b56ea63f6ea6b18bbd587f04fccb63a14ab0b2a24e05) | +| `user` | 未声明 | 无 | [`{ clientTimeZone?, kind: "user" }`](#persistence-type-sha256-b8ed92a5ca59733f046ea3506d64c35c64044b6a084fd51daee4c6c72727d39f) | | `user-approval` | `"catalog"` | 无 | [`{ kind: "user-approval", form: "catalog" }`](#persistence-type-sha256-825ca23416b1ea9d81442afead5cf9229a6fa05842f042135cc3aa9710a6a2d8) | | `user-approval` | `"instructions"` | 无 | [`{ kind: "user-approval", form: "instructions" }`](#persistence-type-sha256-aa2bf9e82b9fdeb94a42af20031fffa30e4e23f01f4ac39757427d4c64c407f0) | | `user-approval` | `"notice"` | `summary`: `string` | [`{ kind: "user-approval", form: "notice" }`](#persistence-type-sha256-6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4) | @@ -4410,13 +4411,13 @@ SHA-256: `394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc` | `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: `39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92` +SHA-256: `02193e4f882eee79523902b49c0f93d92eb5fc85aaa747c39bba9f42d319329a` -[`Message`](#persistence-type-sha256-45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4) 的数组。 +[`Message`](#persistence-type-sha256-d73dbb5105041633eb357c9df0f1ae7fbfc911b00250b8b3c84d81fe319c8ae7) 的数组。 @@ -4784,7 +4785,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` | `source` | 必需 | [`SessionTitleSource`](#persistence-type-sha256-30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f) | | `title` | 必需 | `string` | - + @@ -4792,7 +4793,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` ### `SessionTitleLlmRequestEventData` -SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` +SHA-256: `8e0a3b4e470f634cfea5b9c6351dd34d8c819ddedd41a4c30eecde2017c9fd69` 来源:[`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) @@ -4800,7 +4801,7 @@ SHA-256: `ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f` |---|---|---| | `maxTokens` | 必需 | `number` | | `messageSeqs` | 必需 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | -| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92) | +| `messages` | 必需 | [`Message[]`](#persistence-type-sha256-02193e4f882eee79523902b49c0f93d92eb5fc85aaa747c39bba9f42d319329a) | | `reasoningEffort` | 可选 | `string` | | `route` | 必需 | [`SessionTitleModelIdentity`](#persistence-type-sha256-07e1a58c58b593f507b8e7f25723bb0aa42baae6e00f5ecfddf28cb1e64d3235) | | `system` | 必需 | `string` | @@ -5479,7 +5480,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` | `interrupted` | 未声明 | 无 | [`{ kind: "interrupted" }`](#persistence-type-sha256-56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23) | | `max-tokens` | 未声明 | 无 | [`{ kind: "max-tokens" }`](#persistence-type-sha256-ab7ec5f9eb2c6dfacca5da4c37cf7ba85d04172053ee6b1ebf1709ffcd99c1a7) | - + @@ -5487,7 +5488,7 @@ SHA-256: `f1687f982fa3d41ef29e159feed154ecd13af4dd209acaee16038f223f2e9402` ### `UserMessage` -SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` +SHA-256: `120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499` 来源:[`packages/llm/llm/src/message.ts:161`](../packages/llm/llm/src/message.ts) @@ -5496,19 +5497,19 @@ SHA-256: `0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212` | `content` | 必需 | [`ContentBlock[]`](#persistence-type-sha256-b52f215a6cd691058a3413c12f161fa3b563a2f4895adb3df6f744ec4b0a6ef1) | | `id` | 必需 | `string` | | `role` | 必需 | `"user"` | -| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc) | +| `source` | 必需 | [`MessageSource`](#persistence-type-sha256-7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b) | 消息源兼容策略:`source` — `session-source-attribution` v1; `session.user-message.source`; `kind`; `preserve`. 仅表示归属的新增 kind:`action-cards`, `tmux-context`, `user-question-reply`, `working-directory`. - + ### `UserMessage[]` -SHA-256: `300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70` +SHA-256: `6c0f8aded45d4b3194ba7a67bab10ec31e401dfa976e84b392911b5a221b0f85` -[`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) 的数组。 +[`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499) 的数组。 @@ -6143,6 +6144,34 @@ SHA-256: `cbbe8377ee744964537dbafd83607219e58ba79a13f6db0d0645c7ad3d5e8a09` | `mode` | 必需 | `"external"` | | `version` | 必需 | `2` | + + +### `{ clientTimeZone?, kind: "user" }` + +SHA-256: `b8ed92a5ca59733f046ea3506d64c35c64044b6a084fd51daee4c6c72727d39f` + +来源:[`packages/sdk/server/src/server.ts:54`](../packages/sdk/server/src/server.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `clientTimeZone` | 可选 | `string` | +| `kind` | 必需 | `"user"` | + + + +### `{ clientTimeZone?, kind: "user", principal?, rpcId }` + +SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` + +来源:[`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) + +| 属性 | 存在性 | 类型 | +|---|---|---| +| `clientTimeZone` | 可选 | `string` | +| `kind` | 必需 | `"user"` | +| `principal` | 可选 | [`union (2 variants)`](#persistence-type-sha256-824a4aad44a54e245c67196817d67946734a2dc0eee0b0b6834a5b2a6ef352ce) | +| `rpcId` | 必需 | `string` | + ### `{ code, name, reason? }` @@ -6473,18 +6502,18 @@ SHA-256: `ad0c38a0adb82a94c925456df41586d9b5f9202fca18593eae2213d4445b4585` | `reason` | 必需 | [`RequestHeaderReason`](#persistence-type-sha256-530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6) | | `startsSeries` | 可选 | `true` | - + ### `{ headerSeq?, message, step, turn }` -SHA-256: `129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde` +SHA-256: `27f8b01d8292dda6a9b9d907fc0e8c811836301d0b9cd225afe9d60bbc367f44` 来源:[`packages/core/session/src/types.ts:321`](../packages/core/session/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| | `headerSeq` | 可选 | `number` | -| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def) | +| `message` | 必需 | [`DeveloperMessage`](#persistence-type-sha256-3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7) | | `step` | 必需 | `number` | | `turn` | 必需 | `number` | @@ -6568,17 +6597,17 @@ SHA-256: `17d1afb770d9941936130996da00dc86782cfef731d8d6526162c301256a4ac3` |---|---|---| | `inherited` | 可选 | `true` | - + ### `{ inserted, outcome?, removedCount?, start, … }` -SHA-256: `261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5` +SHA-256: `d7c6a501b0381f8ee4430880905bc335a8089ebc57b2a65c3507bee9473ee3c4` 来源:[`packages/core/agent/src/types.ts:110`](../packages/core/agent/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| -| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70) | +| `inserted` | 必需 | [`UserMessage[]`](#persistence-type-sha256-6c0f8aded45d4b3194ba7a67bab10ec31e401dfa976e84b392911b5a221b0f85) | | `outcome` | 可选 | `"canceled"` | | `removedCount` | 可选 | `number` | | `start` | 必需 | `number` | @@ -7871,21 +7900,6 @@ SHA-256: `8fcb0b44a575e998665c053643d1ab04c82f39253ebd190ac0c975b78e40b543` |---|---|---| | `kind` | 必需 | `"tool-registry"` | - - -### `{ kind: "user" }` - -SHA-256: `a4afec59b75aad5d13ef82d6931f35cc2d98918503916cf069355b77c5e42302` - -来源:[`packages/api/session-controller/src/types.ts:392`](../packages/api/session-controller/src/types.ts) - -| 属性 | 存在性 | 类型 | -|---|---|---| -| `clientTimeZone` | 可选 | `string` | -| `kind` | 必需 | `"user"` | -| `principal` | 可选 | [`union (2 variants)`](#persistence-type-sha256-824a4aad44a54e245c67196817d67946734a2dc0eee0b0b6834a5b2a6ef352ce) | -| `rpcId` | 必需 | `string` | - ### `{ kind: "user-approval" }` @@ -8266,17 +8280,17 @@ SHA-256: `a10c17474eaf2ddab7095a099e0fe3d046fc18e56c3e344fc8894c05ff9ef97b` | `time` | 必需 | `number` | | `type` | 必需 | `"agent-preset/selected"` | - + ### `{ type: "agent/inbox/spliced" }` -SHA-256: `f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64` +SHA-256: `5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5) | +| `data` | 必需 | [`{ inserted, outcome?, removedCount?, start, … }`](#persistence-type-sha256-d7c6a501b0381f8ee4430880905bc335a8089ebc57b2a65c3507bee9473ee3c4) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -8517,17 +8531,17 @@ SHA-256: `13d3d180f977bf78081d487ffa0ecb75857349bcab29a5a3fb48189fca2a6176` | `time` | 必需 | `number` | | `type` | 必需 | `"deliverables/presented"` | - + ### `{ type: "developer/message" }` -SHA-256: `7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd` +SHA-256: `53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde) | +| `data` | 必需 | [`{ headerSeq?, message, step, turn }`](#persistence-type-sha256-27f8b01d8292dda6a9b9d907fc0e8c811836301d0b9cd225afe9d60bbc367f44) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | @@ -8927,17 +8941,17 @@ SHA-256: `1b912703e2d64f91c99c675b8f805b01076c8325b905c1218ad81ef0b24909d5` | `time` | 必需 | `number` | | `type` | 必需 | `"session/title"` | - + ### `{ type: "session/title-llm-request" }` -SHA-256: `4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2` +SHA-256: `5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f) | +| `data` | 必需 | [`SessionTitleLlmRequestEventData`](#persistence-type-sha256-8e0a3b4e470f634cfea5b9c6351dd34d8c819ddedd41a4c30eecde2017c9fd69) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `time` | 必需 | `number` | @@ -9376,17 +9390,17 @@ SHA-256: `f1a96afe7503ac1817de769cd0ba13d9b80111c7034c50106b3344ecc14cc515` | `type` | 必需 | `"usage"` | | `usage` | 必需 | [`TokenUsage`](#persistence-type-sha256-fec5442b9ee4122e10514d81d5a43648003fe8bfb7ee2ba50c0cdbdd383ed394) | - + ### `{ type: "user/message" }` -SHA-256: `fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a` +SHA-256: `3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a` | 属性 | 存在性 | 类型 | |---|---|---| -| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212) | +| `data` | 必需 | [`UserMessage`](#persistence-type-sha256-120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499) | | `ignorable` | 可选 | `true` | | `seq` | 必需 | `number` | | `sourceEventSeqs` | 可选 | [`number[]`](#persistence-type-sha256-5d03ba38734809bcbd2a55221bd938b3b3fc34b49bb686c6113e9e4931e3aa78) | diff --git a/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.i18n.yaml b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.i18n.yaml new file mode 100644 index 0000000000..b2aefc04ba --- /dev/null +++ b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.i18n.yaml @@ -0,0 +1,28 @@ +# Bilingual-pair consistency record for 2026-11-09-sdk-prompt-time-zone.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-11-09-sdk-prompt-time-zone.md +/: + en: 3d5a424ae7d7e46b + zh: c22a8e4a62d8cc1a +/2026-11-09-sdk-prompt-time-zone: + en: 7b78b8897cdcad45 + zh: f150e11551183b79 +/2026-11-09-sdk-prompt-time-zone/summary: + en: efd312eda323fcd6 + zh: 58a84a6bb4f0927b +/2026-11-09-sdk-prompt-time-zone/table-of-contents: + en: 6cf314a069ceb451 + zh: 9adff678e9ecab3b +/2026-11-09-sdk-prompt-time-zone/declaration: + en: 6907136f28e48c90 + zh: 02f8298485f3d8e7 +/2026-11-09-sdk-prompt-time-zone/compatibility: + en: 2cf2990bac782470 + zh: c289f1f4e165868b +/2026-11-09-sdk-prompt-time-zone/verification: + en: 0cb1608608505f3e + zh: 4a3bdc35a048de66 +/2026-11-09-sdk-prompt-time-zone/dev-note: + en: b75c8458928b72b9 + zh: 003ba4e17b4b5269 diff --git a/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md new file mode 100644 index 0000000000..9dae42bc6e --- /dev/null +++ b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.md @@ -0,0 +1,60 @@ +--- +description: "Records a persistence type transition and its compatibility acknowledgement." +kind: persistence-change +--- + +# 2026-11-09-sdk-prompt-time-zone + +English | [中文](2026-11-09-sdk-prompt-time-zone.zh.md) + +## Summary + +Adds the sdk-user message source: SDK prompts record an optional canonical clientTimeZone on a user source without rpcId. + +## Table of Contents + +- [Declaration](#declaration) +- [Compatibility](#compatibility) +- [Verification](#verification) +- [Dev Note](#dev-note) + + +## Declaration + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-09-sdk-prompt-time-zone +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-05-timeline-priority-notice" + after: "5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-05-timeline-priority-notice" + after: "53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-05-timeline-priority-notice" + after: "5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260" + decision: same-version + - root: "event:user/message" + previous: "2026-11-05-timeline-priority-notice" + after: "3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a" + decision: same-version +``` + + +## Compatibility + +The kind stays 'user' and the field is optional, so every existing Session log is unchanged; an SDK prompt without a usable zone writes the same { kind: 'user' } source as before. The writer canonicalizes the zone before commit, and request preparation still refuses a noncanonical value. A current reader of an older log finds no clientTimeZone on SDK prompts and reports the zone as unavailable, as before. A reader that predates this change ignores a clientTimeZone without rpcId and also reports the zone as unavailable; the model-visible time context of recorded requests is replayed from its own logged events, not recomputed from the source. The field is not part of any model request: provider adapters read only the model-visible message content. SESSION_FORMAT_VERSION does not change. + + +## Verification + +pnpm exec vitest run packages/sdk/server/tests/time-zone.spec.ts packages/context/time-context/tests: SDK prompts persist the canonical explicit or sampled zone, omit it when the sampled zone is unusable, native commands record none, and an rpcId-free user source contributes its zone to the time context; all tests passed. + + +## Dev Note + +None. diff --git a/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.schema.json b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.schema.json new file mode 100644 index 0000000000..08fc0a7659 --- /dev/null +++ b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.schema.json @@ -0,0 +1,264 @@ +{ + "formatVersion": 2, + "roots": [ + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a"} + ], + "types": [], + "nodes": { + "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "02193e4f882eee79": {"kind":"array","element":"d73dbb5105041633"}, + "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":[]}, + "120eda1d93010166": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"7ce6b3aae88d0154","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":[]}, + "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"}, + "27f8b01d8292dda6": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"3b64001bcf263052","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, + "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"}, + "3a34ff4c0c404f4b": {"kind":"object","properties":[{"name":"data","type":"120eda1d93010166","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":[]}, + "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":[]}, + "3b64001bcf263052": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"7ce6b3aae88d0154","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":[]}, + "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":[]}, + "53538b9e2b974a81": {"kind":"object","properties":[{"name":"data","type":"27f8b01d8292dda6","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":[]}, + "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, + "5509e694e7b11c54": {"kind":"object","properties":[{"name":"data","type":"d7c6a501b0381f8e","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":[]}, + "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":[]}, + "5d8b5283839b9337": {"kind":"object","properties":[{"name":"data","type":"8e0a3b4e470f634c","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":[]}, + "6085488d223aeffd": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, + "6292bcbedaa97fea": {"kind":"object","properties":[{"name":"kind","type":"f68c335306535a00","optional":false}],"indices":[]}, + "62ecb62dc0fe1b5e": {"kind":"literal","value":"next-turn"}, + "63ba8895cc09e469": {"kind":"literal","value":"retry"}, + "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"}, + "6b23ed9ce1b397e6": {"kind":"literal","value":"compact-checkpoint"}, + "6ba7edb6447b6a3e": {"kind":"literal","value":"share-viewer"}, + "6c0f8aded45d4b31": {"kind":"array","element":"120eda1d93010166"}, + "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"}, + "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"}, + "7ce6b3aae88d0154": {"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","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, + "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":[]}, + "8e0a3b4e470f634c": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"02193e4f882eee79","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":[]}, + "8e611bf46821e500": {"kind":"object","properties":[{"name":"tool","type":"fcf427290c6213c2","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false},{"name":"type","type":"85f9b505b7bdff1f","optional":false}],"indices":[]}, + "8f1062573ea91841": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"63ba8895cc09e469","optional":false},{"name":"principal","type":"824a4aad44a54e24","optional":true},{"name":"rpcId","type":"4cd48f3e5108bd6e","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"}, + "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":[]}, + "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"}, + "b8ed92a5ca59733f": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, + "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"}, + "c77ac037cb8af460": {"kind":"literal","value":"timeline-priority"}, + "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":[]}, + "d215701afb7aafbf": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"c77ac037cb8af460","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, + "d4e4d575abeb4b72": {"kind":"literal","value":"canceled"}, + "d73dbb5105041633": {"kind":"union","types":["09f3f8dc417f2782","120eda1d93010166","3b64001bcf263052","4b259f7f8f0a44ad","fa87537f4a9c1e25"]}, + "d7c6a501b0381f8e": {"kind":"object","properties":[{"name":"inserted","type":"6c0f8aded45d4b31","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":[]}, + "d85590a5675c6e2f": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"1f1385dbc3e875c0","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":[]}, + "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":[]}, + "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"}, + "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-11-09-sdk-prompt-time-zone.zh.md b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.zh.md new file mode 100644 index 0000000000..34ad01a98c --- /dev/null +++ b/docs/persistence-changes/2026-11-09-sdk-prompt-time-zone.zh.md @@ -0,0 +1,60 @@ +--- +description: "记录持久化类型更改及其兼容性确认。" +kind: persistence-change +--- + +# 2026-11-09-sdk-prompt-time-zone + +[English](2026-11-09-sdk-prompt-time-zone.md) | 中文 + +## 概述 + +新增 sdk-user 消息来源:SDK prompt 在不带 rpcId 的 user 来源上记录可选的规范化 clientTimeZone。 + +## 目录 + +- [声明](#declaration) +- [兼容性](#compatibility) +- [验证](#verification) +- [开发备注](#dev-note) + + +## 声明 + +```yaml persistence-change +schemaVersion: 1 +id: 2026-11-09-sdk-prompt-time-zone +baseline: false +changes: + - root: "event:agent/inbox/spliced" + previous: "2026-11-05-timeline-priority-notice" + after: "5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb" + decision: same-version + - root: "event:developer/message" + previous: "2026-11-05-timeline-priority-notice" + after: "53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e" + decision: same-version + - root: "event:session/title-llm-request" + previous: "2026-11-05-timeline-priority-notice" + after: "5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260" + decision: same-version + - root: "event:user/message" + previous: "2026-11-05-timeline-priority-notice" + after: "3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a" + decision: same-version +``` + + +## 兼容性 + +kind 仍为 'user',字段可选,因此所有既有 Session 日志都不变;没有可用时区的 SDK prompt 仍写入与之前相同的 { kind: 'user' } 来源。写入方在提交前规范化时区,请求准备阶段仍拒绝非规范值。当前读取方读取旧日志时,SDK prompt 上没有 clientTimeZone,与之前一样报告时区不可用。早于本更改的读取方忽略不带 rpcId 的 clientTimeZone,同样报告时区不可用;已记录请求的模型可见时间上下文从其自身记录的事件回放,不从来源重新计算。该字段不进入任何模型请求:provider 适配器只读取模型可见的消息内容。SESSION_FORMAT_VERSION 不变。 + + +## 验证 + +pnpm exec vitest run packages/sdk/server/tests/time-zone.spec.ts packages/context/time-context/tests:SDK prompt 持久化规范化后的显式或采样时区,采样时区不可用时不写该字段,原生命令不记录时区,不带 rpcId 的 user 来源向时间上下文提供其时区;全部测试通过。 + + +## 开发备注 + +无。 diff --git a/docs/persistence-changes/historical-formats/README.i18n.yaml b/docs/persistence-changes/historical-formats/README.i18n.yaml index ae9ee0c4b5..d7c0c26f52 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: d0b94efc6bce9073 - zh: 0bc584a91a013c98 + en: 8d508263179b3354 + zh: 2c75bdc2f433764a /session-persistence-formats/scope-and-evidence: en: 44ba17a168ec63ac zh: c80a44bdbf17a174 diff --git a/docs/persistence-changes/historical-formats/README.md b/docs/persistence-changes/historical-formats/README.md index d54fdb1d18..e4f1010f1f 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) | 67 / 640 | +| 4 | Current checkout | [Current catalog](../../persistence-catalog.md) | [JSON](../../persistence-schema.json) | 67 / 641 | diff --git a/docs/persistence-changes/historical-formats/README.zh.md b/docs/persistence-changes/historical-formats/README.zh.md index 1becff2660..0113bdf9fd 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) | 67 / 640 | +| 4 | 当前工作树 | [当前目录](../../persistence-catalog.zh.md) | [JSON](../../persistence-schema.json) | 67 / 641 | diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index cc446efccb..b6f7d7a49e 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":"f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64"}, + {"key":"event:agent/inbox/spliced","kind":"event","event":"agent/inbox/spliced","surface":false,"digest":"5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb"}, {"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":"7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd"}, + {"key":"event:developer/message","kind":"event","event":"developer/message","surface":true,"digest":"53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e"}, {"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":"4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2"}, + {"key":"event:session/title-llm-request","kind":"event","event":"session/title-llm-request","surface":false,"digest":"5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260"}, {"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":"d49164d37eab0f0f70fa787c65d887abbea869c010ccb103d717fab3519c3a41"}, @@ -63,16 +63,16 @@ {"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":"fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a"}, + {"key":"event:user/message","kind":"event","event":"user/message","surface":true,"digest":"3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a"}, {"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-root/change","kind":"event","event":"workspace-root/change","surface":false,"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc"}, {"key":"event:workspace/changes","kind":"event","event":"workspace/changes","surface":false,"digest":"e308ccf867a5398e316e0af8cb6ce238a8d33a63b9b384c8250a686786285f72"} ], "types": [ - {"digest":"010783c095f1d9bddbdd2000f3f0a2d31e2ba4a687f2dabf169c5703b98c9def","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]}, {"digest":"0116b1f89c05221d56b0ba35c83d302bf4857bc7277d247e9bbaf74b27d2c66e","names":[],"sources":[]}, {"digest":"0203243b72fc867afc81aff5f4cf2167e564ed342534eb612fc92f295cf07789","names":[],"sources":[]}, + {"digest":"02193e4f882eee79523902b49c0f93d92eb5fc85aaa747c39bba9f42d319329a","names":[],"sources":[]}, {"digest":"022623b9ef98ec47ec3c3bae0c51027c70d2601141c5e92e26a0d83d1b4cef06","names":[],"sources":[]}, {"digest":"023a355b2be0d688fb6e4df8388dadb942761d46cfe96d0f499aae9631a159d4","names":[],"sources":["packages/core/session/src/types.ts:215"]}, {"digest":"025f11632cd02aaecc23a46c3b5bf43b9009d88293ed9b35ccbc1139d73334dc","names":[],"sources":[]}, @@ -92,7 +92,6 @@ {"digest":"0a92c5bdfa06c2e2615b777728f3aa95f408d43b9012e7b754568311251db623","names":[],"sources":["packages/experimental/liveshare/src/host/viewer-principal.ts:29"]}, {"digest":"0aa62ab51b36c0e64b134bd03ba8725d758744180a1a447da49beaad194f219f","names":[],"sources":[]}, {"digest":"0acd94fe8794574c9ae72c7855ee16d29c546096d4af760d16d1225385764555","names":["packages/llm/llm/src/types.ts#ReplayEnvelope"],"sources":["packages/llm/llm/src/types.ts:474"]}, - {"digest":"0aed9f5c80e82b6e80e92eace5b9e23cd5e58c567d37b4321cd147d51342e212","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"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":[]}, @@ -113,8 +112,8 @@ {"digest":"11638dc58a31496fb6706ced3e23e3a2db1f3b2a8845968c810827a72b5fc811","names":[],"sources":[]}, {"digest":"119abe2b9c0b2f46ecb31d82b9acba4d4b30e049f655e2475e8b4ae12d5a9e25","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:19"]}, {"digest":"11f70b595aa76897fc4e25a352bfa718c659f44b799e5aa14e84e5a38fe72912","names":[],"sources":["packages/interaction/user-approval/src/index.ts:41"]}, + {"digest":"120eda1d93010166aa81e87bc16c09cb4deae354737521e9e54fd42d535db499","names":["packages/llm/llm/src/message.ts#UserMessage"],"sources":["packages/llm/llm/src/message.ts:161"]}, {"digest":"124aa62078ca3311353b39cc3bf6c75da281338be6bbf672f8b361d828cddca3","names":[],"sources":[]}, - {"digest":"129f610271310df606674a5ce5c28b444bbf42c231b0f48ad26a0104ffeb6fde","names":[],"sources":["packages/core/session/src/types.ts:321"]}, {"digest":"12a0cfa619ac4a5fc6c3e8e359c8dae15769edc61497a575935c78d5842f8e42","names":[],"sources":[]}, {"digest":"12d5808fac1996b9b3c2afa806e03022252ba2d7b88f835862ae1896591f60c7","names":["packages/llm/llm/src/types.ts#ImageBlock"],"sources":["packages/llm/llm/src/types.ts:86"]}, {"digest":"1379f0b72275994d20f1ddca2d60a96ab16ec80397ca9f1af21bdc67ba5c269c","names":[],"sources":[]}, @@ -173,11 +172,11 @@ {"digest":"24ce31aa528272e59f21cd26da9eca08968bcc97529756a749bfdab71746d9c8","names":[],"sources":[]}, {"digest":"254dce209e735f9cb6f6b7aec0354712b1611759ec02af4d35a96f2081e666f6","names":[],"sources":[]}, {"digest":"260523b412c19ad8c2bb00093b07f64245ff8ba6b2f76c5b545303772ac9704c","names":[],"sources":[]}, - {"digest":"261128de68865c1f92f2bfa2ccd21f362d6e624cb00fc0cf5558d9d7b82302c5","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"26718e15e7e395bce9642dba5bbe09b3b1a4ce2213d20d566cd9207d7fc5fb78","names":[],"sources":[]}, {"digest":"26c879bdd130e8b8683a6ce588414fad2244783d6573ca399fa0de184a2b0bb1","names":[],"sources":[]}, {"digest":"2765e9119edf5816ac1ab4c95c5ee32c90403f3742962eff11544f7752d59d2e","names":[],"sources":[]}, {"digest":"277b61f9c6f8170425fa6ffe06cfa14376757a896a4749cb82a687d7364c4fc9","names":[],"sources":[]}, + {"digest":"27f8b01d8292dda6a9b9d907fc0e8c811836301d0b9cd225afe9d60bbc367f44","names":[],"sources":["packages/core/session/src/types.ts:321"]}, {"digest":"287211846beea1eccb5f9acee00d20388a38fcb2e95858fa2332d6f58529379a","names":[],"sources":["packages/llm/llm/src/types.ts:165"]}, {"digest":"28936c614bd4e7e2774806edcbb3cbfd3ee643ac1cbf0bbdff43d915505a8fe3","names":[],"sources":[]}, {"digest":"290f32bfd81ff85a8095886a8066fae06e885942b63a8bcd6a8d66d328445808","names":[],"sources":[]}, @@ -196,7 +195,6 @@ {"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"]}, - {"digest":"300665af8bcc85dc20a65fd6681ee48d883178731c6f74457ed41539c607bc70","names":[],"sources":[]}, {"digest":"30d5a537b296685770b1241c4b4bbde19d5a31ff81aa23df73fab5e90b8fc65f","names":["packages/session/session-title/src/types.ts#SessionTitleSource"],"sources":["packages/session/session-title/src/types.ts:28"]}, {"digest":"312aee2f0c42aabbae6cc60d92d596d8453c0aeb061c5868d1755a69ef49e69a","names":[],"sources":[]}, {"digest":"31907de9563751822af6d9be02bafaf26faa098bbd1cb412524134d577cc1648","names":["packages/compaction/compaction/src/checkpoint.ts#CompactionCheckpointSource"],"sources":["packages/compaction/compaction/src/checkpoint.ts:21"]}, @@ -217,12 +215,12 @@ {"digest":"383cf73ae4748e5beb281ae74857ba1ffb92ae01075b9fbf51af78b666007a8f","names":[],"sources":[]}, {"digest":"3860b4757d512a2869be833acb0faf834335b1b056bf3f83df5474dce95f8fa6","names":[],"sources":["packages/llm/llm/src/assistant-stream.ts:34"]}, {"digest":"390eed1028aba02774f14408647acec10ec5516e97d4f15ecde2b9989d5a69f2","names":["packages/feedback/message-feedback/src/types.ts#MessageFeedbackRating"],"sources":["packages/feedback/message-feedback/src/types.ts:17"]}, - {"digest":"394ffa61d7dc84ebfd56ad772b59e47be136b95b9549ebf0b77a3bbebf4ce6cc","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:135"]}, {"digest":"39cf2d3ff8bac81c62d49ac2ba38a095b18e80f3ad700819fa1f650a4e60197f","names":["packages/jobs/jobs/src/types.ts#JobToolCall"],"sources":["packages/jobs/jobs/src/types.ts:16"]}, - {"digest":"39fe981d6583647fe76f121c43bd6eac1f1a0d6707297f0901b3078899f9ac92","names":[],"sources":[]}, + {"digest":"3a34ff4c0c404f4b674b06d4d567953b4dee24c35dd72b03ee5b89553326bb3a","names":[],"sources":[]}, {"digest":"3b04790e08b35241ffa0d38f6d7e4f8788aa921341f6c0d7574a329397c59408","names":[],"sources":[]}, {"digest":"3b1be838223869fe0a08210db85bf773796ed3f2373ac16555dff227cade0c48","names":[],"sources":[]}, {"digest":"3b4f2c9ef2c1217eac596c7b070173cb7896e2fae09e729bc7c56c801e56bb29","names":[],"sources":[]}, + {"digest":"3b64001bcf263052763f2669013e5e20f0a963760d02cf765b142ad1349188f7","names":["packages/llm/llm/src/message.ts#DeveloperMessage"],"sources":["packages/llm/llm/src/message.ts:156"]}, {"digest":"3bc287e765d58dc3a22672a0495a6cfd561220dd38fbaecef80aa95b96caed79","names":[],"sources":[]}, {"digest":"3bd652ebfa8726b3ce3937a4f1bd2759e02f86b3a08a20f9e41a8513656fbc5f","names":["packages/core/session/src/types.ts#OptionalSessionSeq"],"sources":["packages/core/session/src/types.ts:66"]}, {"digest":"3bdb8dc6989655b0d4ec361edafb8e2629bc263e1ea591819414fdafc1a413b3","names":[],"sources":[]}, @@ -246,7 +244,6 @@ {"digest":"44818000e56acb97afdb5045ce235eb55e3fb1ccabc9fc7d0750bb38f36a7f8e","names":[],"sources":[]}, {"digest":"44c8c77aa9aa100b0d74d2deee85474b29faa6eee0ac0f662f7abe9931ddd7f2","names":[],"sources":[]}, {"digest":"4513e088d43e6c68425be30451b9f961cc264fe7318ca62681c41d4d78615986","names":[],"sources":[]}, - {"digest":"45e3a4c397121e1a2a455c990b4d45852111b64909ced474d41b9f977ac592a4","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:195"]}, {"digest":"45f005e6bbb7645248be792b715a74bc7fdf5a67f5381655d3a75dcc7aa2112e","names":[],"sources":[]}, {"digest":"45f2a07ea94573123b6ae14db787a40062dec3834f36d8be92c523d40ba28448","names":[],"sources":["packages/interaction/user-approval/src/types.ts:44"]}, {"digest":"477614bca595a9e7adb5a1870be446b9a8684f3ba8950259d6289f2d3b74f028","names":[],"sources":["packages/compaction/compaction-image-offload/src/projection.ts:25"]}, @@ -271,7 +268,6 @@ {"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:67"]}, {"digest":"4edec1b770e8ec4ce1220bf42edc5ac46713a1b48d4caa778dcfc98bad1f28a3","names":[],"sources":[]}, - {"digest":"4ee17e4219bd5fab6148ec0a8b3ec0fb939edb8f211374cf779bc8135ef9bed2","names":[],"sources":[]}, {"digest":"4f507598cf476214aa7646ce7841a7064a9dcb05d0a1eaaefaf79c2b738f160f","names":[],"sources":[]}, {"digest":"4f91f187baeabef5c7950c4780d31bbe39f3345dff591a6cf26ac7e135ac1cf4","names":[],"sources":["packages/context/session-reference/src/types.ts:18"]}, {"digest":"4fb59762612c3e3ac3a3bd4f84c9c148d3c3893bd422ba2b201cc039fabd49bc","names":[],"sources":[]}, @@ -283,8 +279,10 @@ {"digest":"52c6113cb0e53f345324bf84f01928bea5d5df57ee80bc0dd65407b8bc5a3734","names":[],"sources":[]}, {"digest":"5302e763151277614b97e77f00e3b326694c6c1247b916a20503c344dc970777","names":[],"sources":["packages/core/session/src/types.ts:387"]}, {"digest":"530da6c0267813bb4511af72883cc518834e624e3b3220a7062955fd57a788a6","names":["packages/core/session/src/types.ts#RequestHeaderReason"],"sources":["packages/core/session/src/types.ts:283"]}, + {"digest":"53538b9e2b974a81f1248a4505482f8ab5c91bdf59b24cb3bd8e908bf8dd278e","names":[],"sources":[]}, {"digest":"53cf1704ae0709c7678bcf070c83c619fc48ca1b5c173b74cfa8702f22a8e492","names":[],"sources":[]}, {"digest":"54f9276a1617d7c12594722c89cfe864bcbe4517e9a6f9c98bab14f199a135e0","names":[],"sources":["packages/core/session/src/types.ts:367"]}, + {"digest":"5509e694e7b11c54a7b7b1730ad09fd46986a1aeaa45a713a69b9247f5861efb","names":[],"sources":[]}, {"digest":"557e148d30b79ee48645850832b30c717d7c3b64641deb5d6133b8b4e91ee0b8","names":[],"sources":[]}, {"digest":"5654685d7557ec747e74887237065e626a5bdfa426ca43f7fbb0b6fee9b0916c","names":[],"sources":[]}, {"digest":"56b7c047694875a843ba020dfea3c8380d54ae4ff88ab349e72004dc21e07c23","names":[],"sources":["packages/core/session/src/types.ts:231"]}, @@ -310,6 +308,7 @@ {"digest":"5d17f27a1ef9f7026c0232714adf7573961536d75f3303ca97973975f5af170e","names":[],"sources":[]}, {"digest":"5d542ac7bdf13310c46e1a884dec9fb18ad8c6e153cff207e639cd7bf9d7e694","names":[],"sources":[]}, {"digest":"5d7a64ed6aac5551ebf998dc25e1e7b48a144769913f89702840180e61dc3995","names":[],"sources":[]}, + {"digest":"5d8b5283839b93371885639068f7df86ab6d3134faf186456bdd4f4bdcb42260","names":[],"sources":[]}, {"digest":"5dd766ccd1702a1142ad8b4bd44f2242f8e8a6752669ad3de0a5d224329b1438","names":[],"sources":["packages/compaction/compaction/src/types.ts:82"]}, {"digest":"5e6db6e24948d4a853c71cb9fabd252ad051ce93d4672c1266cf837c1c17b84e","names":[],"sources":[]}, {"digest":"5ebce1317eacd2c148456627a09668e927ee15c204f0643f5ea76b46b54a2647","names":[],"sources":[]}, @@ -344,6 +343,7 @@ {"digest":"6bbe793f6a93dc8d50a4d4d3fbb6f8ed15650bcb7e151d28669628f7b7c3fc25","names":["packages/goal/goal/src/types.ts#GoalSnapshot"],"sources":["packages/goal/goal/src/types.ts:60"]}, {"digest":"6bc8e51124d0874bc89e1d0ceff381a9c3cd0fc240667d69f841ce4f60f65fe5","names":[],"sources":["packages/core/session/src/types.ts:342"]}, {"digest":"6c03546143cdf6ae88f1745ac98c5139efa1588d1415249bbc5f3104d32ab800","names":[],"sources":["packages/core/session/src/types.ts:200"]}, + {"digest":"6c0f8aded45d4b3194ba7a67bab10ec31e401dfa976e84b392911b5a221b0f85","names":[],"sources":[]}, {"digest":"6c1cccb433ddc153facb380c7dda956237ba5c31f8a532a69142dc277890cc9b","names":[],"sources":[]}, {"digest":"6c5a37d42ebdb12db4410699259335f1e149e3a0260425684c00b153afc8990d","names":[],"sources":["packages/core/session/src/types.ts:201"]}, {"digest":"6ccb6bc423fb3952458abf9c1b1c3284208b7e660344b612cc55da773d61afe4","names":[],"sources":[]}, @@ -378,12 +378,12 @@ {"digest":"7b1ce60193fa8b69292e5843858d9cee7dc565dcb40d33c136e5d7e8b8d4296a","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":"7ce6b3aae88d015451212bcc1fef9d4bb25ed03bc842b7f4609e3e9f40fb695b","names":["packages/llm/llm/src/message.ts#MessageSource"],"sources":["packages/llm/llm/src/message.ts:135"]}, {"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":"7eaef7a763ba5b949b8464bc8add8980a3a5ab566014b69787aeba71e5dfe07b","names":[],"sources":[]}, - {"digest":"7ee5a828196d9e4b1672f94f977e68f37125da4297c23029dd682823c09e12fd","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"]}, @@ -426,6 +426,7 @@ {"digest":"8c1c4f72755a78ea163523a46565316e36e9b644382eb48e6635c71a6f412dd2","names":[],"sources":[]}, {"digest":"8c627d7a45fa406cea879a3922105e27ed4c3c7966e264afaf11ea7a330f2dd1","names":[],"sources":[]}, {"digest":"8cdd3fdd295cee53035de16a1b23411716f75e9f994fe9510cac5d7fef605c76","names":[],"sources":[]}, + {"digest":"8e0a3b4e470f634cfea5b9c6351dd34d8c819ddedd41a4c30eecde2017c9fd69","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"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":[]}, @@ -550,6 +551,7 @@ {"digest":"b815d7b91cdd9fc6ccc7dcba05cfc5ce1d55fab5fc0c0801803cd3630cedb602","names":[],"sources":[]}, {"digest":"b81e9de81a481b24e1e1f9adf038bfc59e57b4f35ce62f8f1e45284186f4f812","names":[],"sources":["packages/session/session-title/src/types.ts:30"]}, {"digest":"b8327af7ee5767952d1300cb4f03b7fc04197ae5ba275e13981c689ff7506172","names":["packages/goal/goal/src/types.ts#GoalPhase"],"sources":["packages/goal/goal/src/types.ts:45"]}, + {"digest":"b8ed92a5ca59733f046ea3506d64c35c64044b6a084fd51daee4c6c72727d39f","names":[],"sources":["packages/sdk/server/src/server.ts:54"]}, {"digest":"b8fc636a2121df9d8423c242e03c9d23b7ab7c6fdce00e45746932c60b730f97","names":["packages/deliverables/tool-present/src/types.ts#PresentedFile"],"sources":["packages/deliverables/tool-present/src/types.ts:5"]}, {"digest":"b9305f0ea75ccd6a6061c27fde19f2ab85534f9f3c1a717b573b077ebae0f611","names":[],"sources":[]}, {"digest":"b978cff734e62143eb56c9125423ec275405eda969802d42aaf73ecb987d3b26","names":[],"sources":[]}, @@ -606,6 +608,8 @@ {"digest":"d63b8b8ffad9c02fd80c43a17df4f240c1fe8118ecca9de34f9d5871838ab5b9","names":[],"sources":[]}, {"digest":"d66e11dddf5dfa3c71547e2cbd7b0608824cd8d6243fc16f532017ff28e8fba5","names":[],"sources":[]}, {"digest":"d6e654b88b584fcdf290a56802b1730bc7b9847ae86baa4265ab7769eb48990c","names":[],"sources":[]}, + {"digest":"d73dbb5105041633eb357c9df0f1ae7fbfc911b00250b8b3c84d81fe319c8ae7","names":["packages/llm/llm/src/message.ts#Message"],"sources":["packages/llm/llm/src/message.ts:195"]}, + {"digest":"d7c6a501b0381f8ee4430880905bc335a8089ebc57b2a65c3507bee9473ee3c4","names":[],"sources":["packages/core/agent/src/types.ts:110"]}, {"digest":"d85590a5675c6e2fd8164e5792a6cceac714605b8ac228adae5ee668facb1490","names":[],"sources":[]}, {"digest":"d8a476d2c6fd30df6ec0e799f91716d1518c780d23b4121dce545abfcfb7c5a5","names":[],"sources":[]}, {"digest":"d9196086e41e4dd5c2ce87f5c25529c8112a1731d258cf0728747d41a9ee3241","names":[],"sources":[]}, @@ -662,7 +666,6 @@ {"digest":"ec8b5ff7c77ca6893ac7ba5a0c5b2aefeb52f12c64450b7359660c2a7e8a53d7","names":[],"sources":["packages/core/session/src/types.ts:238"]}, {"digest":"edbbfff1128099fda7b792c56330d2cb04debc9790988e66d1c3f4026e813e0e","names":[],"sources":[]}, {"digest":"edd37b1e4974af648633014435572089b1e8fb71910468a0767a7e28fdd22abf","names":[],"sources":[]}, - {"digest":"ee4277d9b4c96ab0a024b3c65d294712b6721808c564162bce7f7feed40c139f","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"ee577a0cc18664c9daee50e9455153321155604f8f1817362f8f4a4b6fb9e1ad","names":[],"sources":[]}, {"digest":"eea687d437880bd5f55fb447a561112800ca34334c0724d9cecb98493059d9e4","names":["packages/schedule/schedule/src/types.ts#ScheduleCreateChange"],"sources":["packages/schedule/schedule/src/types.ts:199"]}, {"digest":"eefbea819caeeea91ccb02dfafc16c68dd7f961cf9c1b2be25a2084509cf5c5a","names":[],"sources":[]}, @@ -682,7 +685,6 @@ {"digest":"f4a66f654996c093aae700ea4c434ff2ee3569fea9c0e5813ccf6afdccabd163","names":[],"sources":[]}, {"digest":"f5520c1d261ca86ea03735799c311a0a9ede8babb588cf0a65422576d2ee0ad1","names":[],"sources":[]}, {"digest":"f56c5b59ca0161310c338d31dd16cf14287ccd602ff4181058df178c1c286d7f","names":["packages/context/session-reference/src/types.ts#SessionReferenceSource"],"sources":["packages/context/session-reference/src/types.ts:13"]}, - {"digest":"f5d843edb0eeef61c9f5328599d5f92b61112b7710b0310b043196b15b390d64","names":[],"sources":[]}, {"digest":"f6329fb30c7ea8013e8975ca5e78284fb7685cc6bd620e8aa4e9a99bc81d45eb","names":[],"sources":[]}, {"digest":"f634871d1e18b1eb199497ac8ab72d3964f48d03fbf611dc7521a1970cf429d9","names":[],"sources":[]}, {"digest":"f6605d6c57933aeaaf10911b5fbd6c61e655baa181af7192d3240f49d255b90d","names":[],"sources":[]}, @@ -699,7 +701,6 @@ {"digest":"fab2bb09bc5e3b9db0685e8f5500b029af1a2b33e70bc703c1d5d0f596fbc1fd","names":["packages/sandbox/sandbox/src/index.ts#SandboxMode"],"sources":["packages/sandbox/sandbox/src/index.ts:38"]}, {"digest":"fab35c4520883c0d69e42d079c9f543fc5ac7a2d15b537b5572fcd99059c7018","names":[],"sources":[]}, {"digest":"fb5e0517050d2c6d40e5b8145db1f7c5ca7044d5d50fada6ff80e0b22c6ca973","names":[],"sources":[]}, - {"digest":"fb6a6e338625067ac582f55dde412a583040cd738bb8fc6820cb0b941c59f05a","names":[],"sources":[]}, {"digest":"fb8b6a2e53cb9cf44c551176de0fb77d1ddc60037b99a891ff8a860b6d5c29a0","names":[],"sources":[]}, {"digest":"fbd2c74b346a1595b376139c587fadd23e4a21acc9c0abce342975b6cfc60986","names":[],"sources":[]}, {"digest":"fc351843b8ecbd05d739c4ca4fcd4bc7cfad6c0beacbbd48389959bb1bf06cf3","names":[],"sources":[]}, @@ -712,9 +713,9 @@ {"digest":"fee1caf8ab6a65c1bc981f5a1730164490f22a2a89ffa3d0b76f1f432c44c8b5","names":[],"sources":[]} ], "nodes": { - "010783c095f1d9bd": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"394ffa61d7dc84eb","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":[]}, "0116b1f89c05221d": {"kind":"literal","value":"web_search_20250305"}, "0203243b72fc867a": {"kind":"object","properties":[{"name":"kind","type":"24b10f7cdae64928","optional":false}],"indices":[]}, + "02193e4f882eee79": {"kind":"array","element":"d73dbb5105041633"}, "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":[]}, "025f11632cd02aae": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"5f22f22ce033e6ce","optional":false}],"indices":[]}, @@ -734,7 +735,6 @@ "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":[]}, "0aa62ab51b36c0e6": {"kind":"object","properties":[],"indices":[{"key":"4cd48f3e5108bd6e","value":"bbc5696e3f13c758"}]}, "0acd94fe8794574c": {"kind":"object","properties":[{"name":"blocks","type":"b1664fa89f8eab49","optional":true},{"name":"response","type":"bbc5696e3f13c758","optional":false}],"indices":[]}, - "0aed9f5c80e82b6e": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"394ffa61d7dc84eb","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":[]}, "0af3ecfb8c60d416": {"kind":"literal","value":"turn/start"}, "0b6d718c693fdf7f": {"kind":"object","properties":[{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "0b9b8facbe2c1977": {"kind":"literal","value":"disabled"}, @@ -755,8 +755,8 @@ "11638dc58a31496f": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "119abe2b9c0b2f46": {"kind":"object","properties":[{"name":"dialect","type":"a6b41f5bede8094d","optional":false},{"name":"handlerId","type":"4cd48f3e5108bd6e","optional":false},{"name":"matcher","type":"4cd48f3e5108bd6e","optional":true},{"name":"point","type":"4cd48f3e5108bd6e","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "11f70b595aa76897": {"kind":"object","properties":[{"name":"policy","type":"05d2ae1e0c7f8770","optional":false},{"name":"source","type":"76632533f67879dc","optional":true}],"indices":[]}, + "120eda1d93010166": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"68f44f59e91c4139","optional":false},{"name":"source","type":"7ce6b3aae88d0154","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":[]}, "124aa62078ca3311": {"kind":"object","properties":[{"name":"data","type":"da60ed58a8fa23d7","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"d4c799e3d51cae10","optional":false}],"indices":[]}, - "129f610271310df6": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"010783c095f1d9bd","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "12a0cfa619ac4a5f": {"kind":"literal","value":"read-only"}, "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"}, @@ -815,11 +815,11 @@ "24ce31aa528272e5": {"kind":"object","properties":[{"name":"kind","type":"99e7e7d7fed55ae6","optional":false}],"indices":[]}, "254dce209e735f9c": {"kind":"literal","value":"blocked"}, "260523b412c19ad8": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"2f3f201c8846e19c","optional":false}],"indices":[]}, - "261128de68865c1f": {"kind":"object","properties":[{"name":"inserted","type":"300665af8bcc85dc","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":[]}, "26718e15e7e395bc": {"kind":"object","properties":[{"name":"data","type":"11f70b595aa76897","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"36d6a9a871d949ea","optional":false}],"indices":[]}, "26c879bdd130e8b8": {"kind":"literal","value":"dispatch"}, "2765e9119edf5816": {"kind":"literal","value":"model"}, "277b61f9c6f81704": {"kind":"literal","value":"file"}, + "27f8b01d8292dda6": {"kind":"object","properties":[{"name":"headerSeq","type":"0657d3ca5ac4e7bf","optional":true},{"name":"message","type":"3b64001bcf263052","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "287211846beea1ec": {"kind":"object","properties":[{"name":"kind","type":"6c1cccb433ddc153","optional":false}],"indices":[]}, "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":[]}, @@ -838,7 +838,6 @@ "2f1e6a7ebace43d7": {"kind":"union","types":["3f74ba74acd10644","58f94390b982f8a5","de30b1fa12c75f81","ebb768d85ec87fb6"]}, "2f3f201c8846e19c": {"kind":"literal","value":"tool-goal"}, "2fe5026daf14bd4f": {"kind":"object","properties":[{"name":"arguments","type":"bbc5696e3f13c758","optional":false},{"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":[]}, - "300665af8bcc85dc": {"kind":"array","element":"0aed9f5c80e82b6e"}, "30d5a537b2966857": {"kind":"union","types":["1b5649238876e288","ada310bf0bdb8fed","b81e9de81a481b24"]}, "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":[]}, @@ -859,12 +858,12 @@ "383cf73ae4748e5b": {"kind":"literal","value":"recall"}, "3860b4757d512a28": {"kind":"object","properties":[{"name":"args","type":"93c33d9687613293","optional":false},{"name":"dt","type":"5d03ba38734809bc","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"index","type":"0657d3ca5ac4e7bf","optional":false},{"name":"name","type":"4cd48f3e5108bd6e","optional":true},{"name":"time0","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"616f93a5047de668","optional":false}],"indices":[]}, "390eed1028aba027": {"kind":"union","types":["b1f62380f6746fed","df5d9709b7db2a72"]}, - "394ffa61d7dc84eb": {"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","8f1062573ea91841","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","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "39cf2d3ff8bac81c": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":false},{"name":"rootCallId","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, - "39fe981d6583647f": {"kind":"array","element":"45e3a4c397121e1a"}, + "3a34ff4c0c404f4b": {"kind":"object","properties":[{"name":"data","type":"120eda1d93010166","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":[]}, "3b04790e08b35241": {"kind":"object","properties":[{"name":"form","type":"aec150797b655c5f","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "3b1be838223869fe": {"kind":"object","properties":[{"name":"data","type":"e4c18e294232c3ba","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"c589e938cc0e4989","optional":false}],"indices":[]}, "3b4f2c9ef2c1217e": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"bb94f3217aa56c88","optional":false}],"indices":[]}, + "3b64001bcf263052": {"kind":"object","properties":[{"name":"content","type":"b52f215a6cd69105","optional":false},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"role","type":"589d0d91239681f8","optional":false},{"name":"source","type":"7ce6b3aae88d0154","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":[]}, "3bc287e765d58dc3": {"kind":"literal","value":"normal"}, "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":[]}, @@ -888,7 +887,6 @@ "44818000e56acb97": {"kind":"literal","value":"feedback/message-delete"}, "44c8c77aa9aa100b": {"kind":"literal","value":"subagent/catalog"}, "4513e088d43e6c68": {"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":"2c64d4bc7264fd3f","optional":false}],"indices":[]}, - "45e3a4c397121e1a": {"kind":"union","types":["010783c095f1d9bd","09f3f8dc417f2782","0aed9f5c80e82b6e","4b259f7f8f0a44ad","fa87537f4a9c1e25"]}, "45f005e6bbb76452": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"05205074b24d8340","optional":false},{"name":"through","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "45f2a07ea9457312": {"kind":"object","properties":[{"name":"callId","type":"4cd48f3e5108bd6e","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"reason","type":"4cd48f3e5108bd6e","optional":true},{"name":"toolName","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "477614bca595a9e7": {"kind":"object","properties":[{"name":"targets","type":"9e2c06d8653585b3","optional":false}],"indices":[]}, @@ -913,7 +911,6 @@ "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"}, - "4ee17e4219bd5fab": {"kind":"object","properties":[{"name":"data","type":"ee4277d9b4c96ab0","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":[]}, "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":[]}, "4fb59762612c3e3a": {"kind":"object","properties":[{"name":"data","type":"b1ebd5cda47d90d9","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"18fcdd273a2f2f9d","optional":false}],"indices":[]}, @@ -925,8 +922,10 @@ "52c6113cb0e53f34": {"kind":"object","properties":[{"name":"form","type":"6f9e00383836275e","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false},{"name":"sections","type":"c748fb42c80a1200","optional":false}],"indices":[]}, "5302e76315127761": {"kind":"object","properties":[{"name":"error","type":"a81059ca06999da1","optional":true},{"name":"message","type":"4b259f7f8f0a44ad","optional":false},{"name":"meta","type":"c592ce75aab73fca","optional":true},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "530da6c0267813bb": {"kind":"union","types":["34d1ab5c5df37818","4f507598cf476214","e7ce49f12953583f","f789af5ab844827e"]}, + "53538b9e2b974a81": {"kind":"object","properties":[{"name":"data","type":"27f8b01d8292dda6","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":[]}, "53cf1704ae0709c7": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"99e7e7d7fed55ae6","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":[]}, + "5509e694e7b11c54": {"kind":"object","properties":[{"name":"data","type":"d7c6a501b0381f8e","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":[]}, "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":[]}, "56b7c047694875a8": {"kind":"object","properties":[{"name":"kind","type":"69d238a6e9b08d67","optional":false}],"indices":[]}, @@ -952,6 +951,7 @@ "5d17f27a1ef9f702": {"kind":"literal","value":"tool-workflow/agent-end"}, "5d542ac7bdf13310": {"kind":"object","properties":[{"name":"childCreatedAt","type":"0657d3ca5ac4e7bf","optional":false},{"name":"childId","type":"4cd48f3e5108bd6e","optional":false},{"name":"label","type":"4cd48f3e5108bd6e","optional":true},{"name":"mode","type":"d28765f87d6b6ab4","optional":false},{"name":"version","type":"93d38436347f67c9","optional":false}],"indices":[]}, "5d7a64ed6aac5551": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false}],"indices":[]}, + "5d8b5283839b9337": {"kind":"object","properties":[{"name":"data","type":"8e0a3b4e470f634c","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":[]}, "5dd766ccd1702a11": {"kind":"object","properties":[{"name":"shadowedRange","type":"9e41386b3a0c9572","optional":false},{"name":"shadowedSeqs","type":"5d03ba38734809bc","optional":false},{"name":"shadowedTokenCount","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "5e6db6e24948d4a8": {"kind":"object","properties":[{"name":"data","type":"17d1afb770d99419","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"1c2686c0682e7bc5","optional":false}],"indices":[]}, "5ebce1317eacd2c1": {"kind":"literal","value":"subagent/descriptor"}, @@ -986,6 +986,7 @@ "6bbe793f6a93dc8d": {"kind":"object","properties":[{"name":"blockedReason","type":"84ac8c1a66ffc697","optional":true},{"name":"id","type":"4cd48f3e5108bd6e","optional":false},{"name":"maxGoalRounds","type":"0657d3ca5ac4e7bf","optional":false},{"name":"objective","type":"4cd48f3e5108bd6e","optional":false},{"name":"phase","type":"b8327af7ee576795","optional":false},{"name":"revision","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "6bc8e51124d0874b": {"kind":"object","properties":[{"name":"message","type":"09f3f8dc417f2782","optional":false},{"name":"step","type":"0657d3ca5ac4e7bf","optional":false},{"name":"turn","type":"0657d3ca5ac4e7bf","optional":false}],"indices":[]}, "6c03546143cdf6ae": {"kind":"object","properties":[{"name":"kind","type":"e6411b09c1d982f7","optional":false}],"indices":[]}, + "6c0f8aded45d4b31": {"kind":"array","element":"120eda1d93010166"}, "6c1cccb433ddc153": {"kind":"literal","value":"tool-calls"}, "6c5a37d42ebdb12d": {"kind":"object","properties":[{"name":"kind","type":"dbdafceb9a900183","optional":false},{"name":"reason","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "6ccb6bc423fb3952": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"f68c335306535a00","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, @@ -1020,12 +1021,12 @@ "7b1ce60193fa8b69": {"kind":"literal","value":"working-directory"}, "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":[]}, + "7ce6b3aae88d0154": {"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","8f1062573ea91841","8f324cea3916c051","8fcb0b44a575e998","96bfb916a727cd44","99135d8a39379779","99f0e98184709ad1","9edc162949abf93b","9f65c43e340bba31","a15a19ef63cf5d1b","a16e567c8cd2c55c","a2066bd52f61218b","a3c6f1ea38e9a61d","a4afec59b75aad5d","aa2bf9e82b9fdeb9","aae343bc3d663c83","ada310bf0bdb8fed","ade057f4fdc387ae","b062078e899958f9","b2a5c8c008a31e3d","b3681c026a0b98e9","b4ec0af39fd52ed9","b613f83572fe2fbf","b6f94c17dd9bbd7c","b70f3e81fe11b7a5","b79641a9d25e7566","b8ed92a5ca59733f","ba2a1a8f194b1bb2","ba4c40b4381e0dcd","baccc97ec34be6c4","c5228b7a55498d84","c55827fba7018198","cb1c8959e1726f82","cda2345a9be9d139","d215701afb7aafbf","d85590a5675c6e2f","d9c462b9f62fdd3e","db06ef35b27a3842","dba54c09c6e7aafc","dd00cdccd0ba487b","dd5ee8762bd8a14b","dd6cc2bb2a8f2824","dde0cdf9d426768b","deaae5cd30987d4f","e7f4cbb3a57f4cbd","edbbfff1128099fd","ee577a0cc18664c9","f230c0b583e23b25","f29d63336e8266d8","f4a66f654996c093","f56c5b59ca016131","f6329fb30c7ea801","f6605d6c57933aea","f6afe41e3926f422","f7283223aacdc39b","f97f47b0eb87905e","fcf81d3c58c13593","fe1a7acdeed4d0f5"]}, "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":[]}, "7eaef7a763ba5b94": {"kind":"object","properties":[{"name":"form","type":"16d0507cb94b4cfc","optional":false},{"name":"kind","type":"23af3759678a30de","optional":false}],"indices":[]}, - "7ee5a828196d9e4b": {"kind":"object","properties":[{"name":"data","type":"129f610271310df6","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":[]}, "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":[]}, @@ -1068,6 +1069,7 @@ "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":[]}, "8cdd3fdd295cee53": {"kind":"literal","value":"command/done"}, + "8e0a3b4e470f634c": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"02193e4f882eee79","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":[]}, "8e31bb958e9b015e": {"kind":"object","properties":[{"name":"failure","type":"5f2117d1856a5ab4","optional":false},{"name":"kind","type":"1e0b0b66b6f0c53f","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":[]}, "8e8155594e078123": {"kind":"literal","value":"workspace/changes"}, @@ -1192,6 +1194,7 @@ "b815d7b91cdd9fc6": {"kind":"literal","value":"goal"}, "b81e9de81a481b24": {"kind":"object","properties":[{"name":"kind","type":"e31572180d6b28b7","optional":false},{"name":"model","type":"07e1a58c58b593f5","optional":true},{"name":"provider","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "b8327af7ee576795": {"kind":"union","types":["254dce209e735f9c","c43b119ce579b3e9","c8e6f48878cc2a2f","d9196086e41e4dd5"]}, + "b8ed92a5ca59733f": {"kind":"object","properties":[{"name":"clientTimeZone","type":"4cd48f3e5108bd6e","optional":true},{"name":"kind","type":"68f44f59e91c4139","optional":false}],"indices":[]}, "b8fc636a2121df9d": {"kind":"object","properties":[{"name":"description","type":"4cd48f3e5108bd6e","optional":true},{"name":"path","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "b9305f0ea75ccd6a": {"kind":"literal","value":"hook/invoked"}, "b978cff734e62143": {"kind":"object","properties":[{"name":"data","type":"79ddc907312f97cf","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"af0750d32d97d47b","optional":false}],"indices":[]}, @@ -1248,6 +1251,8 @@ "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"}, + "d73dbb5105041633": {"kind":"union","types":["09f3f8dc417f2782","120eda1d93010166","3b64001bcf263052","4b259f7f8f0a44ad","fa87537f4a9c1e25"]}, + "d7c6a501b0381f8e": {"kind":"object","properties":[{"name":"inserted","type":"6c0f8aded45d4b31","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":[]}, "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"}, @@ -1304,7 +1309,6 @@ "ec8b5ff7c77ca689": {"kind":"object","properties":[{"name":"kind","type":"b2245a906e13aa94","optional":false}],"indices":[]}, "edbbfff1128099fd": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"a9059a81430b3207","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "edd37b1e4974af64": {"kind":"object","properties":[{"name":"data","type":"611d82d2dc50df70","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"347de3380f2da308","optional":false}],"indices":[]}, - "ee4277d9b4c96ab0": {"kind":"object","properties":[{"name":"maxTokens","type":"0657d3ca5ac4e7bf","optional":false},{"name":"messageSeqs","type":"5d03ba38734809bc","optional":false},{"name":"messages","type":"39fe981d6583647f","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":[]}, "ee577a0cc18664c9": {"kind":"object","properties":[{"name":"form","type":"e8de0f457fed5b9f","optional":false},{"name":"kind","type":"8067b0d232c350f1","optional":false},{"name":"summary","type":"4cd48f3e5108bd6e","optional":false}],"indices":[]}, "eea687d437880bd5": {"kind":"object","properties":[{"name":"operation","type":"7624ca28c61ca0ea","optional":false},{"name":"schedule","type":"4b1e632e05776982","optional":false},{"name":"version","type":"f88f1b7b6bb733f6","optional":false}],"indices":[]}, "eefbea819caeeea9": {"kind":"literal","value":"block-end"}, @@ -1324,7 +1328,6 @@ "f4a66f654996c093": {"kind":"object","properties":[{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "f5520c1d261ca86e": {"kind":"object","properties":[{"name":"data","type":"e3056e0dda3a379e","optional":false},{"name":"ignorable","type":"dacf3d5f3e4ff619","optional":true},{"name":"seq","type":"0657d3ca5ac4e7bf","optional":false},{"name":"time","type":"0657d3ca5ac4e7bf","optional":false},{"name":"type","type":"24a8188c4d61b70a","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":[]}, - "f5d843edb0eeef61": {"kind":"object","properties":[{"name":"data","type":"261128de68865c1f","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":[]}, "f6329fb30c7ea801": {"kind":"object","properties":[{"name":"form","type":"383cf73ae4748e5b","optional":false},{"name":"kind","type":"0fe52387f6505270","optional":false}],"indices":[]}, "f634871d1e18b1eb": {"kind":"literal","value":"plan/mode"}, "f6605d6c57933aea": {"kind":"object","properties":[{"name":"form","type":"fee1caf8ab6a65c1","optional":false},{"name":"kind","type":"9ac52f0f84fec2eb","optional":false}],"indices":[]}, @@ -1341,7 +1344,6 @@ "fab2bb09bc5e3b9d": {"kind":"union","types":["12a0cfa619ac4a5f","18fce9540bb20897","a3edd1efd1fef21b"]}, "fab35c4520883c0d": {"kind":"literal","value":"rejected"}, "fb5e0517050d2c6d": {"kind":"literal","value":"tool/ptc-dispatch"}, - "fb6a6e338625067a": {"kind":"object","properties":[{"name":"data","type":"0aed9f5c80e82b6e","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":[]}, "fb8b6a2e53cb9cf4": {"kind":"literal","value":"image"}, "fbd2c74b346a1595": {"kind":"literal","value":"agent-instructions"}, "fc351843b8ecbd05": {"kind":"literal","value":"external"}, diff --git a/docs/subsystems/deliverables.md b/docs/subsystems/deliverables.md index b1e97daa44..078c2f9ba9 100644 --- a/docs/subsystems/deliverables.md +++ b/docs/subsystems/deliverables.md @@ -51,7 +51,7 @@ interface WorkspaceChangedFile { interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ + /** The Session working directory `path` values are relative to, as it stood when the turn started. */ cwd: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] diff --git a/docs/subsystems/deliverables.zh.md b/docs/subsystems/deliverables.zh.md index 396b7d8137..7c60d8da71 100644 --- a/docs/subsystems/deliverables.zh.md +++ b/docs/subsystems/deliverables.zh.md @@ -51,7 +51,7 @@ interface WorkspaceChangedFile { interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ + /** The Session working directory `path` values are relative to, as it stood when the turn started. */ cwd: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index effd721974..0f1d528cdf 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -19,13 +19,19 @@ zh: 5349e9f25d08fd97 /forges/overview-and-viewed-marks: en: fd5928603c9375b1 - zh: 1a3bca55344ff385 + zh: e5e32a588a18abae +/forges/viewer-lists-and-descriptions: + en: 05dba49e668fbd82 + zh: 7502689f5dd46118 /forges/session-bindings: en: 74255d6005e1c9e8 zh: 252d0d552f1e26a1 /forges/panel: - en: 0fc2e5a367d0a3ad - zh: a1028e4ecf61b70c + en: 83ad892728d13987 + zh: d19b012f5898ef07 +/forges/panel/review-page: + en: f576f6e104ec9546 + zh: b97efdd34b3a9d1b /forges/extension-api: en: f35345e482e84f4f zh: 2ecb7d9498decb31 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index edf3a8c2d9..f7cea75239 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -54,6 +54,20 @@ interface ForgeProvider { readonly label: string /** What this provider's hosts call a change request. */ readonly changeRequestNoun: ChangeRequestNoun + /** + * Where and which lists of the signed-in user's change requests this provider reads. A provider declares `viewer` and + * implements `listForViewer` and `countForViewer` together; omitting any declares that it reads no viewer lists. + */ + readonly viewer?: ForgeViewerCapability + /** + * Read one viewer list, most recently updated first. A query outside {@link ForgeProvider.viewer} resolves to an + * `unsupported` failure. + */ + listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise + /** Count the change requests in every list of {@link ForgeViewerCapability.filters} on one of its hosts. */ + countForViewer?(host: string, signal: AbortSignal): Promise | ForgeFailure> + /** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */ + readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** @@ -349,9 +363,11 @@ interface ForgeFailure { * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of - * a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure. + * a later status can succeed; `rate-limited`: the host refused the read under its rate limit, so reading again + * succeeds only after the limit resets; `unsupported`: the provider does not offer the read; `unavailable`: any other + * failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'rate-limited' | 'unsupported' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -750,6 +766,143 @@ interface ForgeViewedRequest { } ``` +## Viewer lists and descriptions + +A provider that declares `viewer` reads three lists of open change requests that involve the signed-in user on each of its hosts: `review-requested`, `authored`, and `involved`, which never share a change request. `ctx.forge.viewerSources()` names each provider's hosts, lists, and `maxItems`; `ctx.forge.listForViewer` reads one list most recently updated first, as `ChangeRequestSummary` items without the checks, reviewers, and merge state of a snapshot; and `ctx.forge.countForViewer` reads the size of every list on one host. Neither read joins status polling: a caller polls a list itself and watches each change request it shows in full. A provider, host, or list that offers no viewer list resolves to `unsupported`, and a host that refuses under its rate limit resolves to `rate-limited`. + +`ctx.forge.readDescription` reads the Markdown description and labels of a change request; raw HTML in its `body` must not render as HTML. `images` maps each image address a browser cannot load without the user's host session to an address the host issued for loading that image without one; those addresses stop loading at `imagesExpireAt`, after which a reader reads the description again. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns the searches and the image pairing. + +```ts type-equiv +/** + * A list of open change requests that involve the signed-in user: `review-requested` asks the user or one of the user's + * teams for a review; `authored` names the user as author; `involved` names the user in any other way, as an assignee, + * a commenter, a reviewer, or a mention, and holds none of the other two lists' change requests. + */ +type ForgeViewerFilter = 'review-requested' | 'authored' | 'involved' +``` + +```ts type-equiv +/** Hosts a provider lists change requests on for the signed-in user, and the lists it offers there. */ +interface ForgeViewerCapability { + /** Lowercase host names, each one this provider serves. */ + readonly hosts: readonly string[] + /** The lists the provider reads on each of `hosts`. */ + readonly filters: ReadonlySet + /** Most change requests one read returns, a positive integer. */ + readonly maxItems: number +} +``` + +```ts type-equiv +/** A registered provider's viewer lists, as {@link ForgeViewerCapability} with the forge family that offers them. */ +interface ForgeViewerSource extends ForgeViewerCapability { + /** Forge family of the provider. */ + readonly forge: string +} +``` + +```ts type-equiv +/** One read of a list of open change requests that involve the signed-in user on one host. */ +interface ForgeViewerQuery { + /** Lowercase host name from the provider's {@link ForgeViewerCapability.hosts}. */ + readonly host: string + /** The list to read, from the provider's {@link ForgeViewerCapability.filters}. */ + readonly filter: ForgeViewerFilter + /** One repository to read in, or null for every repository the user can read on `host`. */ + readonly repository: Pick | null + /** Most change requests returned, a positive integer no greater than {@link ForgeViewerCapability.maxItems}. */ + readonly limit: number +} +``` + +```ts type-equiv +/** The signed-in user's latest submitted review of a change request. */ +interface ChangeRequestViewerReview { + /** Outcome of the review. */ + readonly verdict: ReviewVerdict + /** Commit the review was on, or null when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** Status of one change request as a viewer list reports it, without the checks, reviewers, and merge state of a snapshot. */ +interface ChangeRequestSummary { + /** The change request. */ + readonly ref: ChangeRequestRef + /** Web page of the change request. */ + readonly url: string + /** Title as the author wrote it. */ + readonly title: string + /** Whether the author marked the change request as a draft. */ + readonly draft: boolean + /** Author, or null when the host hides the account. */ + readonly author: ForgeCommentAuthor | null + /** Commit object name at the head of the change request. */ + readonly headSha: string + /** Combined check outcome on the head commit. */ + readonly checksRollup: ChecksRollup + /** Aggregate review outcome. */ + readonly reviewDecision: ReviewDecision + /** The signed-in user's latest submitted review, or null before the first. */ + readonly viewerReview: ChangeRequestViewerReview | null + /** + * The review request that asks the signed-in user, or null when none does: `team` names the team, as + * `organization/slug`, when the request asks a team the user belongs to rather than the user. + */ + readonly viewerRequest: { readonly team: string | null } | null + /** Issues the host closes once the change request merges, in host order, at most the provider's limit. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean + /** ISO 8601 time of the host's last update to the change request. */ + readonly updatedAt: string +} +``` + +```ts type-equiv +/** One page of a viewer list, most recently updated first. */ +interface ForgeViewerList { + /** Login of the signed-in user the provider read as. */ + readonly viewer: string + /** Change requests most recently updated first, at most the query's limit. */ + readonly items: readonly ChangeRequestSummary[] + /** Number of change requests the host reports in the whole list; more than `items` holds when the list was cut. */ + readonly total: number +} +``` + +```ts type-equiv +/** The description of a change request as its author wrote it. */ +interface ChangeRequestDescription { + /** Markdown source; it may contain raw HTML, which readers must not render as HTML. Empty without a description. */ + readonly body: string + /** Labels in host order, at most the provider's limit. */ + readonly labels: readonly ChangeRequestLabel[] + /** Whether the change request has more labels than `labels` holds. */ + readonly labelsTruncated: boolean + /** + * Image addresses that a browser cannot load without the user's host session, each mapped to an address the host + * issued for loading that image without one. Addresses not listed load as written. + */ + readonly images: Readonly> + /** ISO 8601 time after which the addresses in `images` stop loading, or null when there are none or the host names no time. */ + readonly imagesExpireAt: string | null + /** ISO 8601 time the change request was created. */ + readonly createdAt: string +} +``` + +```ts type-equiv +/** One label of a change request. */ +interface ChangeRequestLabel { + /** Name as the host spells it. */ + readonly name: string + /** Six-digit hexadecimal color without `#`, or null when the host reports none. */ + readonly color: string | null +} +``` + ## Session bindings `ctx.forgeSession` derives each Session's bindings from its own log by the command rules that providers register: forge-github's `gh` rule and forge-gitlab's `glab` rule bind the URLs that `gh pr create` and `glab mr create` results print and the change request that `gh pr view`, `glab mr view`, and their sibling reference commands act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules. @@ -1367,6 +1520,12 @@ interface ForgeLocalChanges { } ``` +### Review page + +The [code review page](../../packages/experimental/client-ui-forge/README.md#use-this-package) reads change requests by URL instead of through a Session binding. Its `forgePanel` methods (`reviewLists`, `reviewCount`, `reviewChangeRequest`, `reviewDescription`, and the `review*` reads and actions that mirror the Session-bound ones) resolve the URL with `ForgeService.changeRequestFromUrl`, fail with `forgePanel/unrecognized-url` when no provider serves it, and name no Session resource, so only callers that may use the Host's code host credentials reach them. One list hub reads the [viewer lists](#viewer-lists-and-descriptions) only while a list or count stream lasts: streams of one repository scope share one reader that reads every list of every host each `reviewListIntervalMs`, hosts in parallel and each host's lists in order, stops the round's further reads on a host that refuses the viewer or is rate-limited, and backs off after failed rounds up to `reviewMaxBackoffMs`; the count reads every `reviewCountIntervalMs`, and lists of every repository refresh it too. `reviewLists` streams `ForgeReviewFrame` values with each host's lists, the items of the latest successful read, and the failure of the latest read; `reviewCount` streams `ForgeReviewCountFrame` values; and `reviewChangeRequest` streams `ForgeReviewChangeRequest` values for the shown change request, which is polled through `ForgeService.watch` while its stream lasts. + +The chat tab starts in the blank Session `connectWorkspace` resolves and records the change request with `reviewStage`; the Host keeps that choice in memory and binds the change request once the Session's next message enters its inbox, so an untouched blank stays unbound. + ## Extension API @@ -1724,6 +1883,41 @@ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSi */ async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise +/** + * List the viewer lists every registered provider offers; `forge/providers-changed` announces a change. + * @returns one source per provider that declares viewer lists and reads them, in registration order. + */ +viewerSources(): ForgeViewerSource[] + +/** + * Read one list of open change requests that involve the signed-in user. + * @param forge - forge family of a registered provider. + * @param query - host, list, repository, and limit of the read. + * @param signal - cancellation of the read. + * @returns the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list. + * @throws when no provider serves `forge`, or with `signal.reason` when it aborts. + */ +async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise + +/** + * Count the change requests in each viewer list a provider offers on one host. + * @param forge - forge family of a registered provider. + * @param host - lowercase host name the provider lists on. + * @param signal - cancellation of the read. + * @returns the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`. + * @throws when no provider serves `forge`, or with `signal.reason` when it aborts. + */ +async countForViewer(forge: string, host: string, signal: AbortSignal): Promise | ForgeFailure> + +/** + * Read the description and labels of a change request. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced * with `forge/review-changed`. @@ -1815,13 +2009,239 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote({ mode: 'stream' }) async *changeRequestStates(signal: AbortSignal): AsyncIterable +/** + * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on: + * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one + * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to + * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops. + * @param repository - one repository to list in, or null for every repository the user can read. + * @param signal - ends the stream. + * @returns frames, each complete. + */ +@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable + +/** + * Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read: + * the latest count first, then each change. It is read every `reviewCountIntervalMs` while some stream lasts, and a + * list stream of every repository updates it as well. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns frames, each complete. + */ +@Remote({ mode: 'stream' }) async *reviewCount(signal: AbortSignal): AsyncIterable + +/** + * Read every streamed review page list and the count again at once. + * @param signal - request cancellation. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise + +/** + * Poll one change request the review page shows at once; its stream reports the result. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewPoll(url: string, signal: AbortSignal): Promise + +/** + * Stream one change request the review page shows in full: its latest polling result first, then each later result + * and each review change `forge/review-changed` announces for it. The change request is polled through `ctx.forge` + * while the stream lasts. Review page reads and actions name a change request by URL and need no Session binding, so + * only callers that may use the Host's code host credentials reach them. + * @param url - web URL of the change request. + * @param signal - ends the stream. + * @returns frames, each complete. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote({ mode: 'stream' }) async *reviewChangeRequest(url: string, signal: AbortSignal): AsyncIterable + +/** + * Read the description and labels of a change request for the review page. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the description. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/description-failed` with the + * host's reason when the host does not provide it. + */ +@Remote async reviewDescription(url: string, signal: AbortSignal): Promise + +/** + * Read every check of a change request the review page shows. + * @param url - web URL of the change request. + * @param headSha - head commit whose checks the page shows. + * @param signal - request cancellation. + * @returns the snapshot with every check. + * @throws as {@link ForgePanelController.changeRequestChecks} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewChecks(url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Read the review threads of a change request the review page shows, at the head of its latest status. + * @param url - web URL of the change request. + * @param headSha - head commit the page shows. + * @param fresh - whether to read from the host even when threads at this head and update time are kept. + * @param signal - request cancellation. + * @returns the threads at `headSha`. + * @throws as {@link ForgePanelController.changeRequestReview} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewThreads(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise + +/** + * Write to the review threads or the pending review of a change request the review page shows. + * @param url - web URL of the change request. + * @param write - the write and the head commit the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write, as {@link ForgePanelController.changeRequestReviewWrite} does. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid write. + */ +@Remote async reviewThreadWrite(url: string, write: ForgeReviewWrite, signal: AbortSignal): Promise + +/** + * Publish a line comment or a completed review on a change request the review page shows. + * @param url - web URL of the change request. + * @param request - reviewed head, ranges, plain text, and explicit review decision. + * @param signal - request cancellation. + * @returns confirmed publication or a typed failure, as {@link ForgePanelController.submitReview} does. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid review. + */ +@Remote async reviewSubmit(url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise + +/** + * Read the changes of a change request the review page shows, or of consecutive commits of it. + * @param url - web URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files and the commit they end at, without a local checkout count. + * @throws as {@link ForgePanelController.changeRequestDiff} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewDiff(url: string, commits: ForgeCommitRange | null, signal: AbortSignal): Promise + +/** + * List the commits of a change request the review page shows. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the commits, or null when the provider does not read commits. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-failed` when the host does + * not list them. + */ +@Remote async reviewCommits(url: string, signal: AbortSignal): Promise + +/** + * Read one file of a change request's repository at a commit for the review page. + * @param url - web URL of the change request. + * @param commit - commit object name. + * @param path - path relative to the repository root. + * @param signal - request cancellation. + * @returns the text. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-too-large` or + * `forgePanel/diff-failed` when the host does not provide the file. + */ +@Remote async reviewText(url: string, commit: string, path: string, signal: AbortSignal): Promise + +/** + * Read the signed-in user's viewed marks on the files of a change request the review page shows. + * @param url - web URL of the change request. + * @param headSha - head commit of the shown diff. + * @param signal - request cancellation. + * @returns the marks, or null when the provider keeps no viewed marks. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or + * `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does. + */ +@Remote async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request the review page shows. + * @param url - web URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; the action errors of + * {@link ForgePanelController.setFileViewed}. + */ +@Remote async reviewSetViewed(url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + +/** + * Mark a draft change request the review page shows ready for review. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or + * `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewMarkReady(url: string, signal: AbortSignal): Promise + +/** + * Merge a change request the review page shows while its head is still `headSha`. + * @param url - web URL of the change request. + * @param method - how the commits enter the base branch. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewMerge(url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise + +/** + * Rerun the failed checks of a change request the review page shows. + * @param url - web URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewRerunChecks(url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request the review page shows from more reviewers. + * @param url - web URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or + * `forgePanel/action-unknown` with the host's reason; an error without reviewers. + */ +@Remote async reviewRequestReviews(url: string, reviewers: readonly Pick[], signal: AbortSignal): Promise + +/** + * List accounts a review of a change request the review page shows can be requested from. + * @param url - web URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/reviewers-failed` when the host + * does not list them. + */ +@Remote async reviewReviewerCandidates(url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request the review page shows. + * @param url - web URL of the change request. + * @param method - merge or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewUpdateBranch(url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + +/** + * Remember the change request a review conversation's draft quotes, or forget it with null. When the Session's next + * message enters its inbox, the change request is bound to the Session with a `track` record before the turn starts; + * a Session that already started is bound at its next message. The choice lives in memory until then. + * @param sessionId - the Session whose draft quotes the change request; staging neither loads nor resumes it. + * @param url - web URL of the change request, or null. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewStage(sessionId: SessionId, url: string | null, signal: AbortSignal): Promise + /** * Read or await the worktree service's archive cleanup of the Session's checkout. - * @param session - Session whose cleanup is visible to the caller. + * @param sessionId - Session whose cleanup is visible to the caller; reading neither loads nor resumes it. * @param revision - null reads now; a matching revision waits for completion. * @returns the cleanup state, or null without a worktree service, an attempt, or a current revision. */ -@Remote async worktreeCleanup(session: Session, revision: number | null): Promise +@Remote async worktreeCleanup(sessionId: SessionId, revision: number | null): Promise /** * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each @@ -1866,11 +2286,11 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Reinspect a followed Session's checkout, probe sign-in again, and poll its * change requests at once; an unfollowed Session is unchanged. - * @param session - Session whose panel refreshes. + * @param sessionId - Session whose panel refreshes; refreshing neither loads nor resumes it. * @param signal - request cancellation. * @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later. */ -@Remote async refresh(session: Session, signal: AbortSignal): Promise +@Remote async refresh(sessionId: SessionId, signal: AbortSignal): Promise /** * Read the changes one scope covers in the checkout of the Session's @@ -2245,7 +2665,7 @@ registerLens(lens: ForgeLens): () => Promise @Remote async continueInProject(session: Session, signal: AbortSignal): Promise ``` -Types: [Session](session.md) · [WorktreeCleanup](worktrees.md) +Types: [Session](session.md) · [SessionId](core.md) · [WorktreeCleanup](worktrees.md) Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/experimental/client-ui-forge/src/index.ts) diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 1f962fae0e..712903907d 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -54,6 +54,20 @@ interface ForgeProvider { readonly label: string /** What this provider's hosts call a change request. */ readonly changeRequestNoun: ChangeRequestNoun + /** + * Where and which lists of the signed-in user's change requests this provider reads. A provider declares `viewer` and + * implements `listForViewer` and `countForViewer` together; omitting any declares that it reads no viewer lists. + */ + readonly viewer?: ForgeViewerCapability + /** + * Read one viewer list, most recently updated first. A query outside {@link ForgeProvider.viewer} resolves to an + * `unsupported` failure. + */ + listForViewer?(query: ForgeViewerQuery, signal: AbortSignal): Promise + /** Count the change requests in every list of {@link ForgeViewerCapability.filters} on one of its hosts. */ + countForViewer?(host: string, signal: AbortSignal): Promise | ForgeFailure> + /** Read the description and labels of a change request. Omission declares that this provider reads no descriptions. */ + readDescription?(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** @@ -349,9 +363,11 @@ interface ForgeFailure { * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of - * a later status can succeed; `unsupported`: the provider does not offer the read; `unavailable`: any other failure. + * a later status can succeed; `rate-limited`: the host refused the read under its rate limit, so reading again + * succeeds only after the limit resets; `unsupported`: the provider does not offer the read; `unavailable`: any other + * failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unsupported' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'rate-limited' | 'unsupported' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -752,6 +768,145 @@ interface ForgeViewedRequest { } ``` + + +## 登录用户的列表与描述 + +声明了 `viewer` 的提供方在它的每个主机上读取与登录用户有关的三类打开的变更请求:`review-requested`、`authored` 与 `involved`,三者互不重叠。`ctx.forge.viewerSources()` 列出每个提供方的主机、列表与 `maxItems`;`ctx.forge.listForViewer` 按最近更新在前读取一个列表,每项是 `ChangeRequestSummary`,不含快照的检查、评审者与合并状态;`ctx.forge.countForViewer` 读取一个主机上每个列表的总数。两者都不进入状态轮询:调用方自行轮询列表,并对完整展示的变更请求单独 watch。提供方、主机或列表不提供查看者列表时返回 `unsupported`,主机按限流拒绝时返回 `rate-limited`。 + +`ctx.forge.readDescription` 读取变更请求的 Markdown 描述与标签;`body` 中的原始 HTML 不得按 HTML 渲染。`images` 把浏览器在没有用户托管平台会话时无法加载的图片地址,映射为托管平台签发、无需会话即可加载该图片的地址;这些地址在 `imagesExpireAt` 之后失效,之后读者应重新读取描述。搜索与图片配对由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。 + +```ts type-equiv +/** + * A list of open change requests that involve the signed-in user: `review-requested` asks the user or one of the user's + * teams for a review; `authored` names the user as author; `involved` names the user in any other way, as an assignee, + * a commenter, a reviewer, or a mention, and holds none of the other two lists' change requests. + */ +type ForgeViewerFilter = 'review-requested' | 'authored' | 'involved' +``` + +```ts type-equiv +/** Hosts a provider lists change requests on for the signed-in user, and the lists it offers there. */ +interface ForgeViewerCapability { + /** Lowercase host names, each one this provider serves. */ + readonly hosts: readonly string[] + /** The lists the provider reads on each of `hosts`. */ + readonly filters: ReadonlySet + /** Most change requests one read returns, a positive integer. */ + readonly maxItems: number +} +``` + +```ts type-equiv +/** A registered provider's viewer lists, as {@link ForgeViewerCapability} with the forge family that offers them. */ +interface ForgeViewerSource extends ForgeViewerCapability { + /** Forge family of the provider. */ + readonly forge: string +} +``` + +```ts type-equiv +/** One read of a list of open change requests that involve the signed-in user on one host. */ +interface ForgeViewerQuery { + /** Lowercase host name from the provider's {@link ForgeViewerCapability.hosts}. */ + readonly host: string + /** The list to read, from the provider's {@link ForgeViewerCapability.filters}. */ + readonly filter: ForgeViewerFilter + /** One repository to read in, or null for every repository the user can read on `host`. */ + readonly repository: Pick | null + /** Most change requests returned, a positive integer no greater than {@link ForgeViewerCapability.maxItems}. */ + readonly limit: number +} +``` + +```ts type-equiv +/** The signed-in user's latest submitted review of a change request. */ +interface ChangeRequestViewerReview { + /** Outcome of the review. */ + readonly verdict: ReviewVerdict + /** Commit the review was on, or null when the host reports none. */ + readonly reviewedSha: string | null +} +``` + +```ts type-equiv +/** Status of one change request as a viewer list reports it, without the checks, reviewers, and merge state of a snapshot. */ +interface ChangeRequestSummary { + /** The change request. */ + readonly ref: ChangeRequestRef + /** Web page of the change request. */ + readonly url: string + /** Title as the author wrote it. */ + readonly title: string + /** Whether the author marked the change request as a draft. */ + readonly draft: boolean + /** Author, or null when the host hides the account. */ + readonly author: ForgeCommentAuthor | null + /** Commit object name at the head of the change request. */ + readonly headSha: string + /** Combined check outcome on the head commit. */ + readonly checksRollup: ChecksRollup + /** Aggregate review outcome. */ + readonly reviewDecision: ReviewDecision + /** The signed-in user's latest submitted review, or null before the first. */ + readonly viewerReview: ChangeRequestViewerReview | null + /** + * The review request that asks the signed-in user, or null when none does: `team` names the team, as + * `organization/slug`, when the request asks a team the user belongs to rather than the user. + */ + readonly viewerRequest: { readonly team: string | null } | null + /** Issues the host closes once the change request merges, in host order, at most the provider's limit. */ + readonly closingIssues: readonly ChangeRequestIssue[] + /** Whether the host reported more closing issues than `closingIssues` holds. */ + readonly closingIssuesTruncated: boolean + /** ISO 8601 time of the host's last update to the change request. */ + readonly updatedAt: string +} +``` + +```ts type-equiv +/** One page of a viewer list, most recently updated first. */ +interface ForgeViewerList { + /** Login of the signed-in user the provider read as. */ + readonly viewer: string + /** Change requests most recently updated first, at most the query's limit. */ + readonly items: readonly ChangeRequestSummary[] + /** Number of change requests the host reports in the whole list; more than `items` holds when the list was cut. */ + readonly total: number +} +``` + +```ts type-equiv +/** The description of a change request as its author wrote it. */ +interface ChangeRequestDescription { + /** Markdown source; it may contain raw HTML, which readers must not render as HTML. Empty without a description. */ + readonly body: string + /** Labels in host order, at most the provider's limit. */ + readonly labels: readonly ChangeRequestLabel[] + /** Whether the change request has more labels than `labels` holds. */ + readonly labelsTruncated: boolean + /** + * Image addresses that a browser cannot load without the user's host session, each mapped to an address the host + * issued for loading that image without one. Addresses not listed load as written. + */ + readonly images: Readonly> + /** ISO 8601 time after which the addresses in `images` stop loading, or null when there are none or the host names no time. */ + readonly imagesExpireAt: string | null + /** ISO 8601 time the change request was created. */ + readonly createdAt: string +} +``` + +```ts type-equiv +/** One label of a change request. */ +interface ChangeRequestLabel { + /** Name as the host spells it. */ + readonly name: string + /** Six-digit hexadecimal color without `#`, or null when the host reports none. */ + readonly color: string | null +} +``` + ## Session 绑定 `ctx.forgeSession` 按提供方注册的命令规则,从每个 Session 自己的日志派生其绑定:forge-github 的 `gh` 规则与 forge-gitlab 的 `glab` 规则绑定 `gh pr create` 与 `glab mr create` 结果输出的 URL,以及 `gh pr view`、`glab mr view` 及其同类引用命令所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。 @@ -1369,6 +1524,12 @@ interface ForgeLocalChanges { } ``` +### 代码评审页 + +[代码评审页](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)按 URL 读取变更请求,而不经过会话绑定。它的 `forgePanel` 方法(`reviewLists`、`reviewCount`、`reviewChangeRequest`、`reviewDescription`,以及与会话绑定版本对应的各个 `review*` 读取与操作)用 `ForgeService.changeRequestFromUrl` 解析 URL,没有提供方能处理时以 `forgePanel/unrecognized-url` 失败;它们不指向任何会话资源,因此只有可以使用 Host 代码托管凭据的调用方能访问。一个列表中心只在列表流或计数流存在时读取[登录用户的列表](#viewer-lists-and-descriptions):同一仓库范围的流共用一个读取器,它每隔 `reviewListIntervalMs` 读取每个主机的每个列表,各主机并行、同一主机的列表依次读取;某主机拒绝当前用户或触发限流时,本轮不再读取它的其余列表;连续失败的轮次按 `reviewMaxBackoffMs` 为上限退避。计数每隔 `reviewCountIntervalMs` 读取一次,全部仓库范围的列表读取也会更新它。`reviewLists` 流式返回 `ForgeReviewFrame`,含每个主机的列表、最近一次成功读取的条目以及最近一次读取的失败;`reviewCount` 流式返回 `ForgeReviewCountFrame`;`reviewChangeRequest` 为显示中的变更请求流式返回 `ForgeReviewChangeRequest`,该变更请求在其流存在期间经 `ForgeService.watch` 轮询。 + +对话标签在 `connectWorkspace` 解析出的空白会话中开始,并用 `reviewStage` 记录该变更请求;Host 只在内存中保存这个选择,等该会话的下一条消息进入收件箱时再绑定,因此未使用的空白会话保持未绑定。 + ## 扩展 API @@ -1726,6 +1887,41 @@ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSi */ async mergeBase(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise +/** + * List the viewer lists every registered provider offers; `forge/providers-changed` announces a change. + * @returns one source per provider that declares viewer lists and reads them, in registration order. + */ +viewerSources(): ForgeViewerSource[] + +/** + * Read one list of open change requests that involve the signed-in user. + * @param forge - forge family of a registered provider. + * @param query - host, list, repository, and limit of the read. + * @param signal - cancellation of the read. + * @returns the list, or why the host did not provide it; `unsupported` when the provider does not offer the host or list. + * @throws when no provider serves `forge`, or with `signal.reason` when it aborts. + */ +async listForViewer(forge: string, query: ForgeViewerQuery, signal: AbortSignal): Promise + +/** + * Count the change requests in each viewer list a provider offers on one host. + * @param forge - forge family of a registered provider. + * @param host - lowercase host name the provider lists on. + * @param signal - cancellation of the read. + * @returns the count of each list, or why the host did not provide them; `unsupported` when the provider does not list on `host`. + * @throws when no provider serves `forge`, or with `signal.reason` when it aborts. + */ +async countForViewer(forge: string, host: string, signal: AbortSignal): Promise | ForgeFailure> + +/** + * Read the description and labels of a change request. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the description, or why the host did not provide it; `unsupported` when the provider reads no descriptions. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async readDescription(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status; a publication the host took is announced * with `forge/review-changed`. @@ -1817,13 +2013,239 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote({ mode: 'stream' }) async *changeRequestStates(signal: AbortSignal): AsyncIterable +/** + * Stream the review page's lists of the signed-in user's open change requests on every host a provider lists them on: + * the lists read so far first, then a frame after each read settles. Readers of one repository scope share one + * reader, which reads every `reviewListIntervalMs` while some stream lasts and backs off after failed rounds up to + * `reviewMaxBackoffMs`; nothing is read while no stream lasts. The stream ends when `signal` aborts or the Remote stops. + * @param repository - one repository to list in, or null for every repository the user can read. + * @param signal - ends the stream. + * @returns frames, each complete. + */ +@Remote({ mode: 'stream' }) async *reviewLists( repository: { readonly owner: string; readonly name: string } | null, signal: AbortSignal, ): AsyncIterable + +/** + * Stream the number of open change requests that ask the signed-in user for a review, summed over the hosts read: + * the latest count first, then each change. It is read every `reviewCountIntervalMs` while some stream lasts, and a + * list stream of every repository updates it as well. The stream ends when `signal` aborts or the Remote stops. + * @param signal - ends the stream. + * @returns frames, each complete. + */ +@Remote({ mode: 'stream' }) async *reviewCount(signal: AbortSignal): AsyncIterable + +/** + * Read every streamed review page list and the count again at once. + * @param signal - request cancellation. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewRefresh(signal: AbortSignal): Promise + +/** + * Poll one change request the review page shows at once; its stream reports the result. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewPoll(url: string, signal: AbortSignal): Promise + +/** + * Stream one change request the review page shows in full: its latest polling result first, then each later result + * and each review change `forge/review-changed` announces for it. The change request is polled through `ctx.forge` + * while the stream lasts. Review page reads and actions name a change request by URL and need no Session binding, so + * only callers that may use the Host's code host credentials reach them. + * @param url - web URL of the change request. + * @param signal - ends the stream. + * @returns frames, each complete. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote({ mode: 'stream' }) async *reviewChangeRequest(url: string, signal: AbortSignal): AsyncIterable + +/** + * Read the description and labels of a change request for the review page. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the description. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/description-failed` with the + * host's reason when the host does not provide it. + */ +@Remote async reviewDescription(url: string, signal: AbortSignal): Promise + +/** + * Read every check of a change request the review page shows. + * @param url - web URL of the change request. + * @param headSha - head commit whose checks the page shows. + * @param signal - request cancellation. + * @returns the snapshot with every check. + * @throws as {@link ForgePanelController.changeRequestChecks} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewChecks(url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Read the review threads of a change request the review page shows, at the head of its latest status. + * @param url - web URL of the change request. + * @param headSha - head commit the page shows. + * @param fresh - whether to read from the host even when threads at this head and update time are kept. + * @param signal - request cancellation. + * @returns the threads at `headSha`. + * @throws as {@link ForgePanelController.changeRequestReview} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewThreads(url: string, headSha: string, fresh: boolean, signal: AbortSignal): Promise + +/** + * Write to the review threads or the pending review of a change request the review page shows. + * @param url - web URL of the change request. + * @param write - the write and the head commit the user saw. + * @param signal - request cancellation. + * @returns whether the host took the write, as {@link ForgePanelController.changeRequestReviewWrite} does. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid write. + */ +@Remote async reviewThreadWrite(url: string, write: ForgeReviewWrite, signal: AbortSignal): Promise + +/** + * Publish a line comment or a completed review on a change request the review page shows. + * @param url - web URL of the change request. + * @param request - reviewed head, ranges, plain text, and explicit review decision. + * @param signal - request cancellation. + * @returns confirmed publication or a typed failure, as {@link ForgePanelController.submitReview} does. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; an error for an invalid review. + */ +@Remote async reviewSubmit(url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise + +/** + * Read the changes of a change request the review page shows, or of consecutive commits of it. + * @param url - web URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files and the commit they end at, without a local checkout count. + * @throws as {@link ForgePanelController.changeRequestDiff} does, with `forgePanel/unrecognized-url` in place of + * `forgePanel/not-bound`. + */ +@Remote async reviewDiff(url: string, commits: ForgeCommitRange | null, signal: AbortSignal): Promise + +/** + * List the commits of a change request the review page shows. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @returns the commits, or null when the provider does not read commits. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-failed` when the host does + * not list them. + */ +@Remote async reviewCommits(url: string, signal: AbortSignal): Promise + +/** + * Read one file of a change request's repository at a commit for the review page. + * @param url - web URL of the change request. + * @param commit - commit object name. + * @param path - path relative to the repository root. + * @param signal - request cancellation. + * @returns the text. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/diff-too-large` or + * `forgePanel/diff-failed` when the host does not provide the file. + */ +@Remote async reviewText(url: string, commit: string, path: string, signal: AbortSignal): Promise + +/** + * Read the signed-in user's viewed marks on the files of a change request the review page shows. + * @param url - web URL of the change request. + * @param headSha - head commit of the shown diff. + * @param signal - request cancellation. + * @returns the marks, or null when the provider keeps no viewed marks. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head` or + * `forgePanel/viewed-failed` as {@link ForgePanelController.changeRequestViewed} does. + */ +@Remote async reviewViewed(url: string, headSha: string, signal: AbortSignal): Promise + +/** + * Set or clear the signed-in user's viewed mark on one file of a change request the review page shows. + * @param url - web URL of the change request. + * @param request - the file, its mark, and the head commit of the shown diff. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; the action errors of + * {@link ForgePanelController.setFileViewed}. + */ +@Remote async reviewSetViewed(url: string, request: ForgeViewedRequest, signal: AbortSignal): Promise + +/** + * Mark a draft change request the review page shows ready for review. + * @param url - web URL of the change request. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or + * `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewMarkReady(url: string, signal: AbortSignal): Promise + +/** + * Merge a change request the review page shows while its head is still `headSha`. + * @param url - web URL of the change request. + * @param method - how the commits enter the base branch. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewMerge(url: string, method: MergeMethod, headSha: string, signal: AbortSignal): Promise + +/** + * Rerun the failed checks of a change request the review page shows. + * @param url - web URL of the change request. + * @param request - the head commit whose checks the user saw. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewRerunChecks(url: string, request: ForgeRerunRequest, signal: AbortSignal): Promise + +/** + * Request reviews of a change request the review page shows from more reviewers. + * @param url - web URL of the change request. + * @param reviewers - the reviewers to ask, by kind and login. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/action-failed` or + * `forgePanel/action-unknown` with the host's reason; an error without reviewers. + */ +@Remote async reviewRequestReviews(url: string, reviewers: readonly Pick[], signal: AbortSignal): Promise + +/** + * List accounts a review of a change request the review page shows can be requested from. + * @param url - web URL of the change request. + * @param query - text the login or name contains; empty for the host's suggestions. + * @param signal - request cancellation. + * @returns the accounts, the host's suggestions first. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/reviewers-failed` when the host + * does not list them. + */ +@Remote async reviewReviewerCandidates(url: string, query: string, signal: AbortSignal): Promise + +/** + * Bring the base branch's new commits into the head branch of a change request the review page shows. + * @param url - web URL of the change request. + * @param method - merge or rebase. + * @param headSha - head commit the user confirmed. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL; `forgePanel/stale-head`, + * `forgePanel/action-failed`, or `forgePanel/action-unknown` with the host's reason. + */ +@Remote async reviewUpdateBranch(url: string, method: BranchUpdateMethod, headSha: string, signal: AbortSignal): Promise + +/** + * Remember the change request a review conversation's draft quotes, or forget it with null. When the Session's next + * message enters its inbox, the change request is bound to the Session with a `track` record before the turn starts; + * a Session that already started is bound at its next message. The choice lives in memory until then. + * @param sessionId - the Session whose draft quotes the change request; staging neither loads nor resumes it. + * @param url - web URL of the change request, or null. + * @param signal - request cancellation. + * @throws `forgePanel/unrecognized-url` when no provider serves the URL. + */ +@Remote // oxlint-disable-next-line typescript/require-await -- async keeps a refused or cancelled request a rejection, as Remote callers expect async reviewStage(sessionId: SessionId, url: string | null, signal: AbortSignal): Promise + /** * Read or await the worktree service's archive cleanup of the Session's checkout. - * @param session - Session whose cleanup is visible to the caller. + * @param sessionId - Session whose cleanup is visible to the caller; reading neither loads nor resumes it. * @param revision - null reads now; a matching revision waits for completion. * @returns the cleanup state, or null without a worktree service, an attempt, or a current revision. */ -@Remote async worktreeCleanup(session: Session, revision: number | null): Promise +@Remote async worktreeCleanup(sessionId: SessionId, revision: number | null): Promise /** * List the branches that can start a worktree of the Session's current checkout: the checked-out branch, each @@ -1868,11 +2290,11 @@ Serves the forge panel. Following a Session inspects the checkout of its current /** * Reinspect a followed Session's checkout, probe sign-in again, and poll its * change requests at once; an unfollowed Session is unchanged. - * @param session - Session whose panel refreshes. + * @param sessionId - Session whose panel refreshes; refreshing neither loads nor resumes it. * @param signal - request cancellation. * @returns settles once the inspection and the sign-in probe have ended; poll results reach the panel stream later. */ -@Remote async refresh(session: Session, signal: AbortSignal): Promise +@Remote async refresh(sessionId: SessionId, signal: AbortSignal): Promise /** * Read the changes one scope covers in the checkout of the Session's @@ -2247,7 +2669,7 @@ registerLens(lens: ForgeLens): () => Promise @Remote async continueInProject(session: Session, signal: AbortSignal): Promise ``` -Types: [Session](session.zh.md) · [WorktreeCleanup](worktrees.zh.md) +Types: [Session](session.zh.md) · [SessionId](core.zh.md) · [WorktreeCleanup](worktrees.zh.md) Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/experimental/client-ui-forge/src/index.ts) diff --git a/docs/subsystems/sandbox.md b/docs/subsystems/sandbox.md index 71f4eedea6..eec53fd71e 100644 --- a/docs/subsystems/sandbox.md +++ b/docs/subsystems/sandbox.md @@ -207,13 +207,15 @@ The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mo /** * Resolve the complete policy for one capability call. An approved explicit * mode outranks the session's last `sandbox/mode` event, which outranks the - * deployment default. A session cwd is its workspace-write boundary; the - * configured root is the fallback for agentless calls and sessions without a - * cwd. Configured extra roots and this Session's active registrations are - * snapshotted together; existing operations and processes keep their policy. + * deployment default. A session's working directory is its workspace-write + * boundary, so a Host move of the Session moves the boundary; the configured + * root is the fallback for agentless calls and, without the working-directory + * service, sessions without a header directory. Configured extra roots and + * this Session's active registrations are snapshotted together; existing + * operations and processes keep their policy. * @param request - optional session and approved mode override. * @returns the fully resolved per-call mode and absolute workspace root. - * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's recorded cwd is + * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's directory is * relative or contains a NUL byte. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy diff --git a/docs/subsystems/sandbox.zh.md b/docs/subsystems/sandbox.zh.md index 2b79f4c17c..6176b98861 100644 --- a/docs/subsystems/sandbox.zh.md +++ b/docs/subsystems/sandbox.zh.md @@ -207,13 +207,15 @@ The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mo /** * Resolve the complete policy for one capability call. An approved explicit * mode outranks the session's last `sandbox/mode` event, which outranks the - * deployment default. A session cwd is its workspace-write boundary; the - * configured root is the fallback for agentless calls and sessions without a - * cwd. Configured extra roots and this Session's active registrations are - * snapshotted together; existing operations and processes keep their policy. + * deployment default. A session's working directory is its workspace-write + * boundary, so a Host move of the Session moves the boundary; the configured + * root is the fallback for agentless calls and, without the working-directory + * service, sessions without a header directory. Configured extra roots and + * this Session's active registrations are snapshotted together; existing + * operations and processes keep their policy. * @param request - optional session and approved mode override. * @returns the fully resolved per-call mode and absolute workspace root. - * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's recorded cwd is + * @throws `SandboxInvalidRootError` (`SANDBOX_INVALID_ROOT`) when the session's directory is * relative or contains a NUL byte. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy diff --git a/docs/subsystems/session-query.md b/docs/subsystems/session-query.md index 5dca82b24c..1de45c1072 100644 --- a/docs/subsystems/session-query.md +++ b/docs/subsystems/session-query.md @@ -396,16 +396,6 @@ getListMetadata(session: Session): SessionListMetadata */ observeSession( sessionId: SessionId, options: SessionObservationOptions = {}, ): Promise -/** - * Inspect domain-owned state without attaching or resuming a cold Session. - * The getter runs synchronously after preparation and must not mutate or retain the Session. - * @param sessionId - logical Session identity. - * @param read - domain getter returning detached data. - * @param signal - preparation cancellation. - * @returns the getter's value at the current live or prepared cut. - */ -inspectSession(sessionId: SessionId, read: (session: Session) => T, signal?: AbortSignal): Promise - /** * Search the live-preferred logical corpus and group by session. * @param request - query text, metadata filters, page size, and cursor. diff --git a/docs/subsystems/session-query.zh.md b/docs/subsystems/session-query.zh.md index 40605385c1..e8740f0062 100644 --- a/docs/subsystems/session-query.zh.md +++ b/docs/subsystems/session-query.zh.md @@ -396,16 +396,6 @@ getListMetadata(session: Session): SessionListMetadata */ observeSession( sessionId: SessionId, options: SessionObservationOptions = {}, ): Promise -/** - * Inspect domain-owned state without attaching or resuming a cold Session. - * The getter runs synchronously after preparation and must not mutate or retain the Session. - * @param sessionId - logical Session identity. - * @param read - domain getter returning detached data. - * @param signal - preparation cancellation. - * @returns the getter's value at the current live or prepared cut. - */ -inspectSession(sessionId: SessionId, read: (session: Session) => T, signal?: AbortSignal): Promise - /** * Search the live-preferred logical corpus and group by session. * @param request - query text, metadata filters, page size, and cursor. diff --git a/docs/subsystems/skills.md b/docs/subsystems/skills.md index fba5f93d78..9c644b2f2b 100644 --- a/docs/subsystems/skills.md +++ b/docs/subsystems/skills.md @@ -337,8 +337,9 @@ Holds what CLI app plugins register: for each plugin, the entry skill and the do /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. The registration belongs to the calling plugin: unloading that plugin aborts the download - * and removes the entry skill. + * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the + * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs + * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. * @returns the handle the plugin's view observes and its check retries. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a diff --git a/docs/subsystems/skills.zh.md b/docs/subsystems/skills.zh.md index 19590ad35b..72defb9e6e 100644 --- a/docs/subsystems/skills.zh.md +++ b/docs/subsystems/skills.zh.md @@ -337,8 +337,9 @@ Holds what CLI app plugins register: for each plugin, the entry skill and the do /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. The registration belongs to the calling plugin: unloading that plugin aborts the download - * and removes the entry skill. + * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the + * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs + * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. * @returns the handle the plugin's view observes and its check retries. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a diff --git a/docs/subsystems/web.i18n.yaml b/docs/subsystems/web.i18n.yaml index 409796b80c..dc7f1422a6 100644 --- a/docs/subsystems/web.i18n.yaml +++ b/docs/subsystems/web.i18n.yaml @@ -9,14 +9,14 @@ en: 380da3cd0aabd52b zh: 1317c26089c3ab07 /web-access/search-request-and-result: - en: c6eee490ae914ae0 - zh: d576eaeb48480c81 + en: aae36206db7d881a + zh: 3db415334859f12a /web-access/fetch-request-and-result: en: b96bcdf42ced9eab zh: aa927e2450238557 /web-access/provider-availability: - en: ba99c3876cb05fd9 - zh: cd366d7c3279bd87 + en: 359df7da69bf2945 + zh: 007f24572cffe391 /web-access/fetch-network-policy: en: 6851874be5841d90 zh: dc085bf3b82d77df diff --git a/docs/subsystems/web.md b/docs/subsystems/web.md index 0513c0dc35..8a93b2e64e 100644 --- a/docs/subsystems/web.md +++ b/docs/subsystems/web.md @@ -12,7 +12,7 @@ Search and fetch share no request schema and no business logic, but they are del ## Search request and result -Each seam request carries exactly one `query`. The `dsh-tool-web` consumer accepts a required `queries` array and fans it out into separate seam requests; a one-item array performs one search. `maxResults` is a consumer-owned bound (`dsh-tool-web`'s `searchMaxResults` config, default `10`) passed through the seam and enforced on the way back — if a provider over-returns, the seam truncates `sources[]` and sets `truncated`. +Each seam request carries exactly one `query`. The `dsh-tool-web` consumer accepts a required `queries` array and fans it out into separate seam requests; a one-item array performs one search. `maxResults` is a consumer-owned bound (`dsh-tool-web`'s `searchMaxResults` config, default `10`) passed through the seam and enforced on the way back — if a provider over-returns, the seam truncates `sources[]` and sets `truncated`. `llmProvider` names the provider route of the model request a search serves; `dsh-tool-web` sets it to the route of the calling Session's latest model request. ```ts type-equiv /** @@ -31,6 +31,12 @@ interface WebSearchRequest { * bound regardless. */ readonly maxResults?: number + /** + * Provider route id of the model request this search serves. While no search + * provider is configured, the seam selects with it, as `searchReady()` selects + * with its argument. Omitted = the search serves no model request. + */ + readonly llmProvider?: string } ``` @@ -127,7 +133,7 @@ A provider's `available(): boolean` is a cheap LOCAL check (credential presence, A search or fetch provider may also implement `ready(llmProvider): Promise`, a configuration-only check that must not make network calls: it answers whether an operation made for a model request on that chat route has a credential to send. `searchReady(llmProvider?)` and `fetchReady(llmProvider?)` ask only the provider that `search()` or `fetch()` would select, treat a provider without `ready()` as ready, and answer true when selection fails, because the operation reports that failure as a `WebError`. Readiness is not a selection input; `dsh-tool-web` makes it the activation condition of `web_search` and `web_fetch`, so a model step whose route answers false neither declares nor dispatches the tool. The DeepSeek Search and Fetch API providers use the route to choose between the account token and the API key, as the [web-deepseek-api authentication](../../packages/web/web-deepseek-api/README.md#authentication) section describes. -Selection never depends on registration, config, or HMR order: a capability has an explicit provider id (config `searchProvider`/`fetchProvider`, or the matching env var feeding the same field), or auto-selects when exactly one usable provider is registered; multiple usable providers with no configured id is `WEB_PROVIDER_AMBIGUOUS`, not first-wins. Each operation reads the configured id when it runs, so a saved settings change applies to the next search or fetch without remounting `ctx.web`. +Selection never depends on registration, config, or HMR order: a capability has an explicit provider id (config `searchProvider`/`fetchProvider`, or the matching env var feeding the same field), or auto-selects when exactly one usable provider is registered; multiple usable providers with no configured id is `WEB_PROVIDER_AMBIGUOUS`, not first-wins. One fixed preference precedes that rule for search: with no configured id, a search runs `deepseek-official` (DeepSeek Messages search, which has no per-search charge) for a model request on the `deepseek-official` or `deepseek-account` route, and `deepseek-search-api` on every other route and outside a model request, whenever that provider is registered and usable. `searchReady(llmProvider)` selects the same provider as a search whose request carries that `llmProvider`. Each operation reads the configured id when it runs, so a saved settings change applies to the next search or fetch without remounting `ctx.web`. ## Fetch network policy @@ -162,6 +168,7 @@ Selection semantics (resolved at execution time, never order-dependent): - A configured id that is registered and `available()` → that provider. - A configured id not registered → `WEB_PROVIDER_CONFIGURED_MISSING`. - A configured id registered but unavailable → `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`. +- No search id configured, and the provider assigned to the route of the model request the search serves is usable → that provider: `deepseek-official` (Messages search) on the `deepseek-official` and `deepseek-account` routes, `deepseek-search-api` on every other route and outside a model request. - No id configured, exactly one registered usable provider → that provider. - No id configured, multiple usable providers → `WEB_PROVIDER_AMBIGUOUS`. - No id configured, no usable provider → `WEB_PROVIDER_UNAVAILABLE`. @@ -199,7 +206,7 @@ registerFetchProvider(provider: WebFetchProvider): () => void * time with the selection rules above; throws {@link WebError} when the * capability cannot run. The seam enforces `request.maxResults` on the result: * if the provider over-returns, `sources[]` is truncated and `truncated` set. - * @param request - the query and optional result limit. + * @param request - the query, the optional result limit, and the route of the model request the search serves. * @param signal - optional cancellation signal forwarded to the provider. * @returns the provider's results, capped to `request.maxResults`. */ diff --git a/docs/subsystems/web.zh.md b/docs/subsystems/web.zh.md index cca07c0f16..8281fee299 100644 --- a/docs/subsystems/web.zh.md +++ b/docs/subsystems/web.zh.md @@ -12,7 +12,7 @@ Web 访问 seam 是一个[能力 seam](../../.agents/notes/implemented/architect ## 搜索请求与结果 -每个 seam 请求只携带一个 `query`。消费方 `dsh-tool-web` 接受必填的 `queries` 数组,并把它扇出为多个独立 seam 请求;单元素数组执行一次搜索。`maxResults` 是消费方自有的上限(`dsh-tool-web` 的 `searchMaxResults` 配置,默认 `10`),通过 seam 传递并在返回时强制执行——如果提供方返回超量,seam 截断 `sources[]` 并设置 `truncated`。 +每个 seam 请求只携带一个 `query`。消费方 `dsh-tool-web` 接受必填的 `queries` 数组,并把它扇出为多个独立 seam 请求;单元素数组执行一次搜索。`maxResults` 是消费方自有的上限(`dsh-tool-web` 的 `searchMaxResults` 配置,默认 `10`),通过 seam 传递并在返回时强制执行——如果提供方返回超量,seam 截断 `sources[]` 并设置 `truncated`。`llmProvider` 指明搜索所服务的模型请求的提供方路由;`dsh-tool-web` 把它设为发起调用的 Session 最近一次模型请求的路由。 ```ts type-equiv /** @@ -31,6 +31,12 @@ interface WebSearchRequest { * bound regardless. */ readonly maxResults?: number + /** + * Provider route id of the model request this search serves. While no search + * provider is configured, the seam selects with it, as `searchReady()` selects + * with its argument. Omitted = the search serves no model request. + */ + readonly llmProvider?: string } ``` @@ -127,7 +133,7 @@ type WebFetchBody = 搜索或抓取提供方还可以实现 `ready(llmProvider): Promise`,这是只检查配置、禁止发起网络调用的判断:它回答为该对话路由上的模型请求发起的操作是否有可发送的凭据。`searchReady(llmProvider?)` 与 `fetchReady(llmProvider?)` 只询问 `search()` 或 `fetch()` 会选中的提供方,把没有 `ready()` 的提供方视为就绪,并在选择失败时回答 true,因为对应操作会把该失败报告为 `WebError`。就绪判断不是选择输入;`dsh-tool-web` 把它作为 `web_search` 与 `web_fetch` 的激活条件,因此路由回答 false 的模型步骤既不声明也不派发该工具。DeepSeek Search 与 Fetch API 提供方依据该路由在账号令牌与 API 密钥之间选择,见 [web-deepseek-api 鉴权](../../packages/web/web-deepseek-api/README.zh.md#authentication)一节。 -选择从不依赖注册顺序、配置顺序或 HMR(热模块替换)顺序:一项能力要么有显式的提供方 id(配置 `searchProvider`/`fetchProvider`,或填充同一字段的对应环境变量),要么在恰好只有一个可用提供方注册时自动选择;如果存在多个可用提供方却未配置 id,则抛出 `WEB_PROVIDER_AMBIGUOUS`,而不会选用最先注册的提供方。每次操作在执行时读取配置的 id,因此保存的设置变更无需重新挂载 `ctx.web` 即对下一次搜索或抓取生效。 +选择从不依赖注册顺序、配置顺序或 HMR(热模块替换)顺序:一项能力要么有显式的提供方 id(配置 `searchProvider`/`fetchProvider`,或填充同一字段的对应环境变量),要么在恰好只有一个可用提供方注册时自动选择;如果存在多个可用提供方却未配置 id,则抛出 `WEB_PROVIDER_AMBIGUOUS`,而不会选用最先注册的提供方。搜索在这条规则之前有一条固定的优先规则:没有配置 id 时,为 `deepseek-official` 或 `deepseek-account` 路由上的模型请求发起的搜索运行 `deepseek-official`(不按次收费的 DeepSeek Messages 搜索),其他路由上以及不服务于模型请求的搜索运行 `deepseek-search-api`,前提是该提供方已注册且可用。`searchReady(llmProvider)` 选中的提供方与请求携带该 `llmProvider` 的搜索相同。每次操作在执行时读取配置的 id,因此保存的设置变更无需重新挂载 `ctx.web` 即对下一次搜索或抓取生效。 ## 抓取网络策略 @@ -162,6 +168,7 @@ Selection semantics (resolved at execution time, never order-dependent): - A configured id that is registered and `available()` → that provider. - A configured id not registered → `WEB_PROVIDER_CONFIGURED_MISSING`. - A configured id registered but unavailable → `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`. +- No search id configured, and the provider assigned to the route of the model request the search serves is usable → that provider: `deepseek-official` (Messages search) on the `deepseek-official` and `deepseek-account` routes, `deepseek-search-api` on every other route and outside a model request. - No id configured, exactly one registered usable provider → that provider. - No id configured, multiple usable providers → `WEB_PROVIDER_AMBIGUOUS`. - No id configured, no usable provider → `WEB_PROVIDER_UNAVAILABLE`. @@ -199,7 +206,7 @@ registerFetchProvider(provider: WebFetchProvider): () => void * time with the selection rules above; throws {@link WebError} when the * capability cannot run. The seam enforces `request.maxResults` on the result: * if the provider over-returns, `sources[]` is truncated and `truncated` set. - * @param request - the query and optional result limit. + * @param request - the query, the optional result limit, and the route of the model request the search serves. * @param signal - optional cancellation signal forwarded to the provider. * @returns the provider's results, capped to `request.maxResults`. */ diff --git a/docs/subsystems/working-directory.i18n.yaml b/docs/subsystems/working-directory.i18n.yaml index 8e77a990b4..ea31f99075 100644 --- a/docs/subsystems/working-directory.i18n.yaml +++ b/docs/subsystems/working-directory.i18n.yaml @@ -6,8 +6,8 @@ en: 45832e24372ea387 zh: 7e0f31726fa1dc4e /working-directory/directory-selection: - en: 10d9f5bed386adfe - zh: c112d1b4356166b7 + en: 4cf56f80c75a2b0c + zh: 97d6813aa8636e3c /working-directory/model-context: en: 872112549d003dca zh: 48bfd30fdf25c234 diff --git a/docs/subsystems/working-directory.md b/docs/subsystems/working-directory.md index e879ff9b3f..92bd506d2e 100644 --- a/docs/subsystems/working-directory.md +++ b/docs/subsystems/working-directory.md @@ -10,7 +10,7 @@ A Session's active directory is owned by [`dsh-working-directory`](../../package `get` is the one read of a Session's directory: relative paths resolve from it, and it is the workspace root for everything that follows the Session's checkout. Every change the service records is a `workspace-root/change`. A log written while the model could move the directory holds `working-directory/change` events, which have no writer now. The service ignores them: such a Session resumes in its original project, or in the directory of its last `workspace-root/change`, and the next request's context reports the directory. -Changes are local to one Session. Relative filesystem operations, newly started processes, instruction discovery, skills, and file completion use the active directory. Existing terminals and persistent shells retain their own directories. Sandbox writable roots and project membership remain anchored to the original project. +Changes are local to one Session. Relative filesystem operations, newly started processes, instruction discovery, skills, and file completion use the active directory. The sandbox `workspace-write` boundary, the Files tree and directory listings, and the change summaries follow it too. Existing terminals and persistent shells retain their own directories. Project membership remains anchored to the original project. ## Model context diff --git a/docs/subsystems/working-directory.zh.md b/docs/subsystems/working-directory.zh.md index df9b0ac5da..6c6ea10551 100644 --- a/docs/subsystems/working-directory.zh.md +++ b/docs/subsystems/working-directory.zh.md @@ -10,7 +10,7 @@ Session 的当前目录由 [`dsh-working-directory`](../../packages/session/work `get` 是读取 Session 目录的唯一接口:相对路径从它解析,跟随 Session 检出的一切也以它为工作区根。服务记录的每次变更都是 `workspace-root/change`。写于模型还能移动目录时期的日志含有 `working-directory/change` 事件,现在没有写入方。服务忽略它们:这样的 Session 在原始项目中恢复,或在最近一条 `workspace-root/change` 的目录中恢复,下一次请求的上下文会报告该目录。 -变更仅影响一个 Session。相对路径文件系统操作、新启动的进程、指令发现、技能和文件补全使用当前目录。已有终端和持久 shell 保留自己的目录。沙箱可写根目录与项目归属继续绑定原始项目。 +变更仅影响一个 Session。相对路径文件系统操作、新启动的进程、指令发现、技能和文件补全使用当前目录。沙箱 `workspace-write` 边界、文件树与目录列举以及变更摘要也跟随它。已有终端和持久 shell 保留自己的目录。项目归属继续绑定原始项目。 ## 模型上下文 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index eda76426f7..a793cbc5df 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -453,6 +453,15 @@ Source: [`packages/api/workspace-controller/src/index.ts`](../../packages/api/wo Host Remote file reads and workspace directory observations over the composed filesystem. ```ts cordis-catalog +/** + * Resolve the scope other Host services use to open the same `session//` addresses: + * a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory. + * @param sessionId - Session identity received on the wire. + * @param signal - cancellation for the persistence read of a stored Session. + * @returns the scope, or undefined when no live or stored Session has that identity. + */ +scopeOf(sessionId: SessionId, signal?: AbortSignal): Promise + /** * Read one page of lines from a UTF-8 file readable by the filesystem backend. * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. @@ -519,6 +528,8 @@ Host Remote file reads and workspace directory observations over the composed fi @Remote({ mode: 'stream' }) changes(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): AsyncIterable ``` +Types: [SessionId](core.md) + Source: [`packages/api/workspace-files/src/index.ts`](../../packages/api/workspace-files/src/index.ts) diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index e800d15107..585b0dc605 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -453,6 +453,15 @@ Source: [`packages/api/workspace-controller/src/index.ts`](../../packages/api/wo Host Remote file reads and workspace directory observations over the composed filesystem. ```ts cordis-catalog +/** + * Resolve the scope other Host services use to open the same `session//` addresses: + * a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory. + * @param sessionId - Session identity received on the wire. + * @param signal - cancellation for the persistence read of a stored Session. + * @returns the scope, or undefined when no live or stored Session has that identity. + */ +scopeOf(sessionId: SessionId, signal?: AbortSignal): Promise + /** * Read one page of lines from a UTF-8 file readable by the filesystem backend. * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. @@ -519,6 +528,8 @@ Host Remote file reads and workspace directory observations over the composed fi @Remote({ mode: 'stream' }) changes(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): AsyncIterable ``` +Types: [SessionId](core.zh.md) + Source: [`packages/api/workspace-files/src/index.ts`](../../packages/api/workspace-files/src/index.ts) diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 261a408ad8..b71f5aefea 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -210,14 +210,14 @@ async exit(agent: Agent, signal?: AbortSignal): Promise +async cleanupOf(sessionId: SessionId, revision: number | null): Promise ``` -Types: [Agent](core.md) · [Session](session.md) +Types: [Agent](core.md) · [SessionId](core.md) Source: [`packages/experimental/worktree/src/index.ts`](../../packages/experimental/worktree/src/index.ts) diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index 668d19be62..5d0c6f778c 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -210,14 +210,14 @@ async exit(agent: Agent, signal?: AbortSignal): Promise +async cleanupOf(sessionId: SessionId, revision: number | null): Promise ``` -Types: [Agent](core.zh.md) · [Session](session.zh.md) +Types: [Agent](core.zh.md) · [SessionId](core.zh.md) Source: [`packages/experimental/worktree/src/index.ts`](../../packages/experimental/worktree/src/index.ts) diff --git a/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.i18n.yaml new file mode 100644 index 0000000000..8ba22f8003 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/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-rc.4/forge-rate-limited-failure/guide.md +/: + en: a269b2e48637b03f + zh: c9448349795ddcba +/forgefailure-code-gains-rate-limited: + en: 4f089ad68e437051 + zh: d410b8ae2e2ade27 +/forgefailure-code-gains-rate-limited/change: + en: 97194ff490de2bbe + zh: 49f6c69fd0dff633 +/forgefailure-code-gains-rate-limited/migration: + en: b7d9cfab3582d1ca + zh: dbf6458a78bf8931 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md new file mode 100644 index 0000000000..6c2e12a336 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "ForgeFailure.code gains rate-limited, which forge-github returns when GitHub refuses a read under its rate limit, so an exhaustive switch over the code no longer compiles." +--- + +# `ForgeFailure.code` gains `rate-limited` + +English | [中文](guide.zh.md) + +## Change + +`ForgeFailure['code']` from `@deepseek-ai/dsh-experimental-forge` adds `'rate-limited'`: the host refused the read under its rate limit, and reading again succeeds only after the limit resets. [forge-github](../../../../packages/experimental/forge-github/README.md#use-this-package) now returns it for a GraphQL `RATE_LIMITED` error, HTTP 429, or a message that names a primary or secondary rate limit, which it reported as `unavailable` before. Status polls, check reads, review reads, diffs, file reads, viewer lists, and descriptions can all carry it. + +A third-party plugin is affected when it switches exhaustively over `ForgeFailure['code']`, ending in `assertNever` or typing a `Record`, which then fails to compile, or when it treats every code other than the documented ones as impossible. A provider that never returns `rate-limited` keeps working unchanged. + +## Migration + +1. Search for `ForgeFailure['code']`, `failure.code`, and `assertNever(` over forge failures in your plugin, and add a `'rate-limited'` case to each exhaustive switch or record. Read it like `unavailable` when you have no rate-limit handling, or wait before reading again when you do. +2. A provider that detects its host's rate limit may return `{ code: 'rate-limited', message }` from any read that resolves to `ForgeFailure`. +3. Run your typecheck; it passes once every exhaustive switch names the new code. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md new file mode 100644 index 0000000000..9cf6cea5ec --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/forge-rate-limited-failure/guide.zh.md @@ -0,0 +1,20 @@ +--- +kind: upgrade-guide +description: "ForgeFailure.code 新增 rate-limited,forge-github 在 GitHub 按限流拒绝读取时返回它,对该代码做穷尽 switch 的代码因此无法通过编译。" +--- + +# `ForgeFailure.code` 新增 `rate-limited` + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-experimental-forge` 的 `ForgeFailure['code']` 新增 `'rate-limited'`:托管平台按限流拒绝了读取,限额重置之后再读才会成功。[forge-github](../../../../packages/experimental/forge-github/README.zh.md#use-this-package) 遇到 GraphQL `RATE_LIMITED` 错误、HTTP 429,或提到主限流、次级限流的消息时返回它,此前这些情况都报告为 `unavailable`。状态轮询、检查读取、评审读取、diff、文件读取、登录用户的列表与描述读取都可能返回它。 + +受影响的是对 `ForgeFailure['code']` 做穷尽 switch 的第三方插件:以 `assertNever` 结尾、或声明了 `Record` 的代码会编译失败;把文档列出的代码之外的值都当作不可能出现的代码也会受影响。从不返回 `rate-limited` 的提供方无需修改。 + +## 迁移 + +1. 在插件中搜索 `ForgeFailure['code']`、`failure.code`,以及针对 forge 失败的 `assertNever(`,给每个穷尽的 switch 或 record 加上 `'rate-limited'`。没有限流处理时按 `unavailable` 对待;有限流处理时,等一段时间再读取。 +2. 能识别主机限流的提供方,可以在任何返回 `ForgeFailure` 的读取中返回 `{ code: 'rate-limited', message }`。 +3. 运行类型检查;所有穷尽的 switch 都列出新代码后即可通过。 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.i18n.yaml new file mode 100644 index 0000000000..993678b9ff --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/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-rc.4/web-search-deepseek-model-default/guide.md +/: + en: 0770389edf4d335e + zh: fdbfa622103fb642 +/search-on-deepseek-models-defaults-to-legacy-messages-search: + en: 1b8b03f925f55d40 + zh: ad09560d0736d4a6 +/search-on-deepseek-models-defaults-to-legacy-messages-search/change: + en: 02ae47ad15769fe8 + zh: 1f7b1fe3f97656da +/search-on-deepseek-models-defaults-to-legacy-messages-search/migration: + en: 5fbf8405a6a2c9dc + zh: ae8bb97ee2970f07 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md new file mode 100644 index 0000000000..1e5db7c0a5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "The shipped composition no longer fixes a search provider, so web search in a conversation on a DeepSeek model runs legacy Messages search instead of the DeepSeek Search API." +--- + +# Search on DeepSeek models defaults to legacy Messages search + +English | [中文](guide.zh.md) + +## Change + +Previously, the shared base composition set `web.searchProvider` to `deepseek-search-api`, so every search was one DeepSeek Search API request. Now the base sets no `searchProvider`, and `dsh-web` selects per model provider route. A search made for a model request on the `deepseek-official` or `deepseek-account` route runs the `deepseek-official` search provider: an auxiliary Messages request to `web-search-deepseek`'s endpoint, which has no per-search charge and is billed as model tokens, and which appends a `web/deepseek-search-llm-request` event to the Session log. A search on any other route, or outside a model request, still runs `deepseek-search-api`. + +The Messages search endpoint does not follow the model provider's base URL: it is `web-search-deepseek.baseURL`, else `$DEEPSEEK_SEARCH_BASE_URL`, else `https://api.deepseek.com/anthropic/v1`, and outside an account conversation it receives the key under `web-search-deepseek.apiKeyEnv` (`DEEPSEEK_API_KEY` by default). A deployment whose DeepSeek model provider points at a gateway therefore sends that key to the official endpoint and its searches fail until step 2 or 3 is applied. + +The Web search provider menu on the Web search and fetch settings page gains **Automatic**, which is the selection when none is stored. A composition or profile that sets `web.searchProvider` itself, and `DSH_WEB_SEARCH_PROVIDER`, see no change. Fetch still defaults to `http`. + +## Migration + +1. To accept the new default, change nothing. Confirm: the Web search provider menu shows Automatic, and a search in a conversation on a DeepSeek model appends a `web/deepseek-search-llm-request` event. +2. To keep the DeepSeek Search API for every model, select DeepSeek Search API in that menu and save, or set `searchProvider: deepseek-search-api` beside `fetchProvider: http` in the `config` of the `@deepseek-ai/dsh-web` row. Confirm: the menu shows DeepSeek Search API, and a search appends no `web/deepseek-search-llm-request` event. +3. To use Messages search through a gateway, select DeepSeek server-side search in that menu and save the gateway's Anthropic-compatible base, which ends before `/messages`, as its Base URL, or set `web-search-deepseek.baseURL`; then select Automatic again if other models should keep the Search API. Confirm: a search on a DeepSeek model returns results, and its `web/deepseek-search-llm-request` event names the gateway endpoint. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md new file mode 100644 index 0000000000..0fcccc1b13 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/web-search-deepseek-model-default/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "交付的组合不再固定搜索提供方,因此使用 DeepSeek 模型的会话中,网页搜索改用旧版 Messages 搜索而不是 DeepSeek Search API。" +--- + +# DeepSeek 模型上的搜索默认使用旧版 Messages 搜索 + +[English](guide.md) | 中文 + +## 变更 + +过去,共享的基础组合把 `web.searchProvider` 设为 `deepseek-search-api`,因此每次搜索都是一次 DeepSeek Search API 请求。现在基础组合不设置 `searchProvider`,由 `dsh-web` 按模型提供方路由选择。为 `deepseek-official` 或 `deepseek-account` 路由上的模型请求发起的搜索使用 `deepseek-official` 搜索提供方:它向 `web-search-deepseek` 的端点发送一次辅助 Messages 请求,不按次收费,按模型 token 计费,并向会话日志追加一个 `web/deepseek-search-llm-request` 事件。其他路由上的搜索,以及不服务于模型请求的搜索,仍使用 `deepseek-search-api`。 + +Messages 搜索的端点不跟随模型提供方的基础地址:它是 `web-search-deepseek.baseURL`,其次是 `$DEEPSEEK_SEARCH_BASE_URL`,再次是 `https://api.deepseek.com/anthropic/v1`;在账号会话之外,它收到的是 `web-search-deepseek.apiKeyEnv`(默认 `DEEPSEEK_API_KEY`)下的密钥。因此,DeepSeek 模型提供方指向网关的部署会把该密钥发往官方端点,搜索会失败,直到执行第 2 步或第 3 步。 + +「网页搜索与获取」设置页的「网页搜索提供方」菜单新增**自动选择**,没有已存选择时即选中它。自行设置了 `web.searchProvider` 的组合或 profile,以及 `DSH_WEB_SEARCH_PROVIDER`,不受影响。Fetch 仍默认为 `http`。 + +## 迁移 + +1. 接受新的默认值时无需修改。确认:「网页搜索提供方」菜单显示「自动选择」,且使用 DeepSeek 模型的会话中的搜索会追加一个 `web/deepseek-search-llm-request` 事件。 +2. 要让所有模型继续使用 DeepSeek Search API,在该菜单中选择 DeepSeek Search API 并保存,或在 `@deepseek-ai/dsh-web` 条目的 `config` 中把 `searchProvider: deepseek-search-api` 与 `fetchProvider: http` 一起设置。确认:菜单显示 DeepSeek Search API,且搜索不再追加 `web/deepseek-search-llm-request` 事件。 +3. 要通过网关使用 Messages 搜索,在该菜单中选择 DeepSeek 服务端搜索,把网关的 Anthropic 兼容基础地址(到 `/messages` 之前为止)作为其 Base URL 保存,或设置 `web-search-deepseek.baseURL`;如果其他模型应继续使用 Search API,再重新选择「自动选择」。确认:DeepSeek 模型上的搜索返回结果,且其 `web/deepseek-search-llm-request` 事件指向网关端点。 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.i18n.yaml new file mode 100644 index 0000000000..0fb2284938 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/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-rc.4/workspace-write-boundary-follows-root/guide.md +/: + en: 8e9487f2e34d2fb5 + zh: 490859f7f2bda707 +/the-workspace-write-boundary-follows-the-session-s-working-directory: + en: 540195a16ff3b882 + zh: bc29122de6e89f97 +/the-workspace-write-boundary-follows-the-session-s-working-directory/change: + en: 6285cb3bb9343ae3 + zh: 216498974cd862f9 +/the-workspace-write-boundary-follows-the-session-s-working-directory/migration: + en: eadc3ff3b86b6722 + zh: 8713fea1250b3578 diff --git a/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.md b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.md new file mode 100644 index 0000000000..7f4c9dcb67 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "The workspace-write boundary follows the Session's working directory instead of its original project, so a Session in a worktree can no longer write the repository's Git directory." +--- +# The `workspace-write` boundary follows the Session's working directory + +English | [中文](guide.zh.md) + +## Change + +`ctx.sandboxPolicy.resolve({ session })` returns the Session's working directory as `workspaceRoot`: the checkout the Session works in. Before, it returned the original project recorded in the Session header for the whole Session. A Session that enters a worktree through `enter_worktree` or the forge New worktree option can now write only inside that worktree; the original project is no longer writable. The boundary moves with every Host move of the Session's directory, including SDK `setWorkingDirectory` (`set_working_directory` in Python) and a child started through `ctx.subagents.start({ cwd })`; a `working-directory/change` recorded before this release does not move it. + +The repository's Git directory lies outside a linked worktree. Under `workspace-write`, `git add`, `git commit`, and other commands that write it are therefore denied inside a worktree unless a grant covers that directory. Before, a worktree inside the original project shared the project's boundary, which contained `.git`. The policy reads no Git files and derives no grant. + +The Files tree, directory listings and watches, deliverables and change summaries, open-in-app actions, and Session rows read the same directory. `WorkspaceChangesSummary.cwd` is the directory the turn started in, no longer the original project. + +Who observes it: operators and models that commit from a worktree Session under `workspace-write`, operators who relied on a worktree Session still writing its original project, and Host plugins that read `WorkspaceChangesSummary.cwd` as the original project. + +## Migration + +1. To let worktree Sessions commit under `workspace-write`, add the repository's Git directory, such as `/repo/.git`, to `additionalWritableRoots` of `@deepseek-ai/dsh-sandbox-policy` in `cordis.yml`, or register it for one Session from a Host plugin with `ctx.sandboxPolicy.registerWritableRoot(session, directory)`. The grant also covers `.git/hooks` and `.git/config`; use it for trusted work only. Windows processes ignore additional writable roots, so the grant does not reach `git` there. Without an effective grant, the model requests escalation for each such command where approvals are enabled. +2. Where a task must write the original project after entering a worktree, leave with `exit_worktree()` or the forge panel's continue-in-project action, or keep the Session in the original project; the boundary follows that change. Where an SDK client moved the directory only to change where relative paths resolve, pass absolute paths or the shell's `workdir` instead. +3. In Host plugins that consume `ctx.workspaceChanges.summary`, read the original project from the Session header's `cwd`; `WorkspaceChangesSummary.cwd` is the directory listed `path` values are relative to. +4. Where `cordis.yml` sets the sandbox policy's `workspaceRoot` to bound Sessions without a header directory, set `defaultDirectory` of `@deepseek-ai/dsh-working-directory` to the same directory; that directory now bounds them. +5. Confirm: after `enter_worktree`, a write to the original project outside the worktree is denied, and, on macOS or Linux, `git commit` in the worktree succeeds once the grant of step 1 is in place. diff --git a/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.zh.md new file mode 100644 index 0000000000..abb5cc9612 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.4/workspace-write-boundary-follows-root/guide.zh.md @@ -0,0 +1,25 @@ +--- +kind: upgrade-guide +description: "workspace-write 边界跟随 Session 的工作目录而不是原始项目,因此 worktree 中的 Session 不再能写入仓库的 Git 目录。" +--- +# `workspace-write` 边界跟随 Session 的工作目录 + +[English](guide.md) | 中文 + +## 变更 + +`ctx.sandboxPolicy.resolve({ session })` 返回的 `workspaceRoot` 是 Session 的工作目录,即它所在的检出目录。此前整个 Session 期间返回的都是 Session header 记录的原始项目。通过 `enter_worktree` 或 forge 的"新建工作树"选项进入 worktree 的 Session 现在只能在该 worktree 内写入;原始项目不再可写。Host 每次移动 Session 的目录,边界都随之移动,包括 SDK 的 `setWorkingDirectory`(Python 中为 `set_working_directory`)以及通过 `ctx.subagents.start({ cwd })` 启动的子代理;本版本之前记录的 `working-directory/change` 不移动边界。 + +仓库的 Git 目录位于链接 worktree 之外。因此在 `workspace-write` 下,`git add`、`git commit` 等写入它的命令在 worktree 内会被拒绝,除非有授权覆盖该目录。此前,位于原始项目内的 worktree 共用项目的边界,其中包含 `.git`。策略不读取任何 Git 文件,也不推导授权。 + +文件树、目录列举与监听、交付物与变更摘要、在应用中打开操作和 Session 行读取同一个目录。`WorkspaceChangesSummary.cwd` 是该轮次开始时所在的目录,不再是原始项目。 + +受影响者:在 `workspace-write` 下从 worktree Session 提交的运维人员与模型、依赖 worktree Session 仍可写入原始项目的运维人员,以及把 `WorkspaceChangesSummary.cwd` 当作原始项目读取的 Host 插件。 + +## 迁移 + +1. 要让 worktree Session 在 `workspace-write` 下提交,请在 `cordis.yml` 中把仓库的 Git 目录(例如 `/repo/.git`)加入 `@deepseek-ai/dsh-sandbox-policy` 的 `additionalWritableRoots`,或在 Host 插件中用 `ctx.sandboxPolicy.registerWritableRoot(session, directory)` 为单个 Session 注册。该授权也覆盖 `.git/hooks` 与 `.git/config`,只用于可信任务。Windows 的进程忽略额外可写目录,因此该授权在 Windows 上对 `git` 不生效。没有生效的授权时,在启用审批的环境里模型会为每条这类命令请求提权。 +2. 任务在进入 worktree 后仍需写入原始项目时,用 `exit_worktree()` 或 forge 面板的“在项目中继续”离开,或让 Session 留在原始项目中;边界跟随该变更。SDK 客户端若只是为了改变相对路径的解析位置而移动目录,请改传绝对路径或 shell 的 `workdir`。 +3. 在消费 `ctx.workspaceChanges.summary` 的 Host 插件中,从 Session header 的 `cwd` 读取原始项目;`WorkspaceChangesSummary.cwd` 是所列 `path` 值相对的目录。 +4. `cordis.yml` 若用沙箱策略的 `workspaceRoot` 限定 header 没有目录的 Session,请把 `@deepseek-ai/dsh-working-directory` 的 `defaultDirectory` 设为同一目录;现在由该目录限定这些 Session。 +5. 确认:`enter_worktree` 之后,对 worktree 之外原始项目的写入被拒绝;在 macOS 或 Linux 上完成第 1 步的授权后,worktree 内的 `git commit` 成功。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.i18n.yaml new file mode 100644 index 0000000000..830501c67a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/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-rc.5/archive-worktrees-without-sandbox-policy/guide.md +/: + en: 3665b6ec3aca78ed + zh: 4e2107594f2c4586 +/archive-cleanup-ignores-the-creator-s-sandbox-policy: + en: aabc06ab672bab22 + zh: 992c04ed13078e9c +/archive-cleanup-ignores-the-creator-s-sandbox-policy/change: + en: 0f6f9f29a08acc7f + zh: 2961fe146e9ac840 +/archive-cleanup-ignores-the-creator-s-sandbox-policy/migration: + en: 6e6a944e98c1475a + zh: edc32a22433870b3 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.md new file mode 100644 index 0000000000..5dfc431266 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "Archive cleanup removes a checkout whose creator's sandbox policy is read-only, and runs its Git commands outside the sandbox." +--- + +# Archive cleanup ignores the creator's sandbox policy + +English | [中文](guide.zh.md) + +## Change + +[v0.2.2-rc.1](../../v0.2.2-rc.1/archive-worktrees/guide.md) retained an archived Session's checkout while its creator's sandbox policy was read-only, and ran the removal's Git commands under that policy. Archiving now counts as the user's authorization to remove the checkout: cleanup reads no sandbox policy, removes the checkout whatever the creator's mode, and runs `git status` and `git worktree remove` outside the sandbox with the Host user's permissions. Git reads the repository's configuration as usual; hooks and the filesystem monitor stay disabled. + +The checks that bound removal are unchanged: the checkout lies in the configured pool of its source checkout, is registered on its recorded branch without locks or a detached HEAD, and has no tracked changes, untracked files, or initialized submodules; no unarchived Session refers to it; the branch and its commits remain. + +You are affected when you relied on a read-only creator to keep its checkout after archiving, or on the sandbox to confine cleanup. + +## Migration + +1. To keep every checkout on archive, set `retainOnArchive: true` on the worktree service, in `cordis.yml` or from the Forge panel's switch on the Plugins page. +2. To keep one checkout, leave a tracked change or an untracked file in it, or keep an unarchived Session working inside it, before archiving the creator. +3. Archive a test Session that created a clean worktree, then check `ctx.worktrees.cleanupOf(sessionId, null)`: `removed` confirms the new behavior, and `null` confirms `retainOnArchive` is in effect. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.zh.md new file mode 100644 index 0000000000..1284a4eb3e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/archive-worktrees-without-sandbox-policy/guide.zh.md @@ -0,0 +1,22 @@ +--- +kind: upgrade-guide +description: "归档清理会删除创建者沙箱策略为只读的检出目录,且其 Git 命令不经沙箱执行。" +--- + +# 归档清理不再参考创建者的沙箱策略 + +[English](guide.md) | 中文 + +## 变更 + +[v0.2.2-rc.1](../../v0.2.2-rc.1/archive-worktrees/guide.zh.md) 中,创建者的沙箱策略为只读时会保留被归档 Session 的检出目录,删除用的 Git 命令也受该策略约束。现在归档即视为用户授权删除该目录:清理不读取任何沙箱策略,无论创建者是什么模式都会删除,`git status` 与 `git worktree remove` 以 Host 用户的权限在沙箱外执行。Git 照常读取仓库配置;hooks 与文件系统监视器仍然关闭。 + +约束删除的检查不变:目录位于源检出目录配置的池中,登记在记录的分支上,没有锁也不是 detached HEAD,没有已跟踪改动、未跟踪文件或已初始化的子模块;没有未归档 Session 引用它;分支及其提交保留。 + +依赖只读创建者在归档后保留检出目录、或依赖沙箱约束清理的用户会受影响。 + +## 迁移 + +1. 要在归档时保留所有检出目录,在 `cordis.yml` 中为 worktree 服务设置 `retainOnArchive: true`,或在插件页 Forge 面板的开关中打开。 +2. 要保留某一个检出目录,在归档创建者之前让其中留有已跟踪改动或未跟踪文件,或让一个未归档 Session 在其中工作。 +3. 归档一个创建过干净 worktree 的测试 Session,再查看 `ctx.worktrees.cleanupOf(sessionId, null)`:`removed` 表示新行为生效,`null` 表示 `retainOnArchive` 生效。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.i18n.yaml new file mode 100644 index 0000000000..fbf727afa4 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/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-rc.5/sdk-prompt-time-zone/guide.md +/: + en: a07259d8388d4cac + zh: 2e52c1c30028a099 +/sdk-prompts-report-the-process-time-zone-by-default: + en: a05ff032b245d2a9 + zh: 65a504c65b00ed4f +/sdk-prompts-report-the-process-time-zone-by-default/change: + en: 6f9aa3d02e634b47 + zh: 9637bed97668d8d7 +/sdk-prompts-report-the-process-time-zone-by-default/migration: + en: f39441fa05c7a2fd + zh: 9f125d2d0f293f47 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md new file mode 100644 index 0000000000..a7e0bb0bba --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "SDK prompts without a time zone now report the runtime process zone to the model instead of an unavailable zone." +--- + +# SDK prompts report the process time zone by default + +English | [中文](guide.zh.md) + +## Change + +In earlier releases, every SDK prompt reached the model with `Browser time zone for this request: unavailable.`, so the model asked the user to clarify unqualified dates and times. Now each ordinary prompt reports a zone, as Web prompts do: the `timeZone` passed with the prompt, or else the runtime process zone sampled for that prompt. The model then interprets unqualified dates and times in that zone, for example `Browser time zone for this request: UTC. Interpret otherwise-unqualified dates and times in this zone.` + +This affects TypeScript and Python SDK applications, and direct JSON-RPC clients of `session/prompt` and `session/query`, that pass no zone. Containers usually run in `UTC`, which may not be the user's zone. A process zone that is not `UTC` or an IANA Area/Location name, such as `+00:00` under `TZ=GMT`, still reports `unavailable`. An explicit zone outside these formats now fails the request. Native slash commands are unchanged and record no zone. + +## Migration + +1. Pass the user's zone with each prompt when it differs from the runtime process zone: + - TypeScript: `session.run(input, { timeZone: 'Asia/Shanghai' })`, `harness.run(input, { timeZone })`, or `client.prompt(sessionId, blocks, { timeZone })`. + - Python: `session.run(input, time_zone="Asia/Shanghai")`, `harness.run(input, time_zone=...)`, or `client.session_prompt(session_id, blocks, time_zone=...)`. + - JSON-RPC: add `"timeZone": "Asia/Shanghai"` to `session/prompt` or `session/query` params. +2. Alternatively, when one runtime serves users in one zone, set `TZ` in the runtime environment, for example `TZ=Asia/Shanghai`. +3. Confirm with a prompt that asks for the current time: the model request contains `Browser time zone for this request: .`, and a request with an invalid zone such as `CST` fails with a JSON-RPC error naming the value. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md new file mode 100644 index 0000000000..fac68d067f --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/sdk-prompt-time-zone/guide.zh.md @@ -0,0 +1,23 @@ +--- +kind: upgrade-guide +description: "未指定时区的 SDK prompt 现在向模型上报运行时进程时区,而不再是时区不可用。" +--- + +# SDK prompt 默认上报进程时区 + +[English](guide.md) | 中文 + +## 变更 + +在早期版本中,每条 SDK prompt 送达模型时都带有 `Browser time zone for this request: unavailable.`,因此模型会请用户澄清未限定时区的日期与时间。现在每条普通 prompt 都像 Web prompt 一样上报时区:使用随 prompt 传入的 `timeZone`,否则使用运行时为这条 prompt 采样的进程时区。模型随后按该时区解释未限定的日期与时间,例如 `Browser time zone for this request: UTC. Interpret otherwise-unqualified dates and times in this zone.`。 + +受影响的是不传时区的 TypeScript 与 Python SDK 应用,以及直接调用 `session/prompt` 和 `session/query` 的 JSON-RPC 客户端。容器通常运行在 `UTC`,它可能不是用户的时区。进程时区既不是 `UTC` 也不是 IANA Area/Location 名称时(例如 `TZ=GMT` 下的 `+00:00`),仍上报 `unavailable`。不符合这些格式的显式时区现在会让请求失败。原生 slash 命令不变,不记录时区。 + +## 迁移 + +1. 用户时区与运行时进程时区不同时,为每条 prompt 传入用户时区: + - TypeScript:`session.run(input, { timeZone: 'Asia/Shanghai' })`、`harness.run(input, { timeZone })` 或 `client.prompt(sessionId, blocks, { timeZone })`。 + - Python:`session.run(input, time_zone="Asia/Shanghai")`、`harness.run(input, time_zone=...)` 或 `client.session_prompt(session_id, blocks, time_zone=...)`。 + - JSON-RPC:在 `session/prompt` 或 `session/query` 的 params 中加入 `"timeZone": "Asia/Shanghai"`。 +2. 如果一个运行时只服务同一时区的用户,也可以在运行时环境中设置 `TZ`,例如 `TZ=Asia/Shanghai`。 +3. 用一条询问当前时间的 prompt 确认:模型请求中包含 `Browser time zone for this request: <你的时区>.`;带非法时区(例如 `CST`)的请求以写明该值的 JSON-RPC 错误失败。 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.i18n.yaml new file mode 100644 index 0000000000..5eb8756539 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/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-rc.5/session-query-inspect-session-removed/guide.md +/: + en: dddfb5bf2fed957d + zh: e7af1103d0d94c43 +/ctx-sessionquery-inspectsession-is-removed: + en: a53d9621aedeeab7 + zh: 3ee8c33b78c7c717 +/ctx-sessionquery-inspectsession-is-removed/change: + en: 6a2bc607cff3fce9 + zh: 0b67af2e8a6c0122 +/ctx-sessionquery-inspectsession-is-removed/migration: + en: 120cf3ce967ce942 + zh: 93227b7e520e3678 diff --git a/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.md b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.md new file mode 100644 index 0000000000..191bd33c6e --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "ctx.sessionQuery.inspectSession is removed, so a plugin that reads a cold Session through a prepared Session object no longer compiles." +--- + +# `ctx.sessionQuery.inspectSession` is removed + +English | [中文](guide.zh.md) + +## Change + +`SessionQueryEngine.inspectSession(sessionId, read, signal?)` from `@deepseek-ai/dsh-session-query` is removed. It prepared an unpublished `Session` for a cold Session and passed it to a synchronous getter, so projection handles and owner services could read it. That object was not in the Session store, had no Agent, and could not be appended to. The only in-repository caller, worktree archive cleanup, now reads projection wire values through `observeSession`. + +A third-party plugin is affected when it calls `ctx.sessionQuery.inspectSession`; it fails to compile, and an untyped call rejects at run time. + +## Migration + +1. Search your plugin for `inspectSession(`. +2. Replace each call with an observation and read the projection's wire value by key: `using observation = await ctx.sessionQuery.observeSession(sessionId, { signal })`, then `observation.projections?.values[key]`. The value is computed to the end of the log for live and cold Sessions alike, without attaching or resuming a cold Session. +3. State without a wire view is private to its owner; read it through the owner's service, or ask the owner to add a wire view. +4. Run your typecheck; it passes once no call remains. diff --git a/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.zh.md new file mode 100644 index 0000000000..845726e1f1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.5/session-query-inspect-session-removed/guide.zh.md @@ -0,0 +1,21 @@ +--- +kind: upgrade-guide +description: "移除 ctx.sessionQuery.inspectSession,经预备 Session 对象读取冷会话的插件将无法通过编译。" +--- + +# 移除 `ctx.sessionQuery.inspectSession` + +[English](guide.md) | 中文 + +## 变更 + +`@deepseek-ai/dsh-session-query` 的 `SessionQueryEngine.inspectSession(sessionId, read, signal?)` 已移除。它为冷会话准备一个未发布的 `Session`,交给同步读取函数,让投影句柄和属主服务可以读取。这个对象不在 Session 存储中,没有 Agent,也不能追加事件。仓库内唯一的调用方 worktree 归档清理,现在经 `observeSession` 读取投影的对外值。 + +调用 `ctx.sessionQuery.inspectSession` 的第三方插件会受影响:无法通过编译,未标类型的调用会在运行时被拒绝。 + +## 迁移 + +1. 在插件中搜索 `inspectSession(`。 +2. 把每处调用改为观察会话,再按 key 读取投影的对外值:`using observation = await ctx.sessionQuery.observeSession(sessionId, { signal })`,然后读 `observation.projections?.values[key]`。活会话与冷会话的值都算到日志末尾,冷会话不会被挂载或恢复运行。 +3. 没有对外视图的状态归属方私有;经属主的服务读取,或请属主补上对外视图。 +4. 运行类型检查;不再有调用时即可通过。 diff --git a/package.json b/package.json index 4fa8fdb34e..44b7a97677 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-root", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "license": "MIT", "private": true, "type": "module", @@ -246,10 +246,17 @@ "@deepseek-ai/dsh-cua": "workspace:*", "@deepseek-ai/dsh-dingtalk": "workspace:*", "@deepseek-ai/dsh-experimental-claude-code-mods": "workspace:*", + "@deepseek-ai/dsh-feishu": "workspace:*", "@deepseek-ai/dsh-llm-replay": "workspace:*", "@deepseek-ai/dsh-subagent-dsh-sdk": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-wecom": "workspace:*", + "@deepseek-ai/dsh-tencent-meeting": "workspace:*", "@deepseek-ai/dsh-mcp-client": "workspace:*", + "@deepseek-ai/dsh-mcp-manager": "workspace:*", + "@deepseek-ai/dsh-linear": "workspace:*", + "@deepseek-ai/dsh-notion": "workspace:*", + "@deepseek-ai/dsh-tencent-docs": "workspace:*", "@deepseek-ai/dsh-tool-session-query": "workspace:*", "@deepseek-ai/dsh-web-fetch-http": "workspace:*", "@stylistic/eslint-plugin": "^5.10.0", diff --git a/packages/account/deepseek-account/package.json b/packages/account/deepseek-account/package.json index 08c283609c..393d9e89e2 100644 --- a/packages/account/deepseek-account/package.json +++ b/packages/account/deepseek-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deepseek-account", "description": "Sign in to DeepSeek and manage account credentials and notifications", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/account/deepseek-auth/package.json b/packages/account/deepseek-auth/package.json index e9592b8e18..dc910bc8aa 100644 --- a/packages/account/deepseek-auth/package.json +++ b/packages/account/deepseek-auth/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deepseek-auth", "description": "DeepSeek request authentication (ctx.deepseekAuth): choose between the API key and the account sign-in for one DeepSeek API request and release its headers", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/acp/acp/package.json b/packages/acp/acp/package.json index cdbd4be899..eb9f8d2887 100644 --- a/packages/acp/acp/package.json +++ b/packages/acp/acp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp", "description": "Automation-only Agent Client Protocol server for driving DeepSeek Harness agents over JSON-RPC stdio", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/gateway/package.json b/packages/api/gateway/package.json index e6d704eae8..87119aa46f 100644 --- a/packages/api/gateway/package.json +++ b/packages/api/gateway/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-gateway", "description": "Typert Remote Host dispatcher and Client API endpoint", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/job-controller/package.json b/packages/api/job-controller/package.json index 004d9306ee..dcbb1265f9 100644 --- a/packages/api/job-controller/package.json +++ b/packages/api/job-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-job-controller", "description": "Job Remote observation stream and the reference-counted client job-output service", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/remote-access/package.json b/packages/api/remote-access/package.json index e1f94ff22f..32cf8855d2 100644 --- a/packages/api/remote-access/package.json +++ b/packages/api/remote-access/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remote-access", "description": "Method-level Remote access control for non-owner Peers and the per-Peer access snapshot", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/remotes/package.json b/packages/api/remotes/package.json index abaafb19b4..f709148d93 100644 --- a/packages/api/remotes/package.json +++ b/packages/api/remotes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-remotes", "description": "Remote BFF assembly for application-selected Host capabilities", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 2408a24fa3..a0a541daae 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -18,8 +18,8 @@ en: 958951f6e7fdc5de zh: 73d73a5d51b45eba /session-controller/client-references: - en: d816da086dcda253 - zh: 0f6efc1efff58efb + en: 8c9fb80b590c47ff + zh: db2902daf76e46f8 /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 5810eb2c3b..a510935e0b 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -89,6 +89,8 @@ The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads onc 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. Every reference keeps the Session object and its scope. `connection`, `true` by default, also keeps the Session's own event connection and the event window it keeps current; when no reference keeps it, the Session disconnects, empties its window, and keeps local state such as pending submission echoes, and the next connected reference connects as a first open. A `connection: false` reference is ready once its binding exists. `facets` names owner-declared computations over that data, such as `conversation`. When the last facet is released while the connection remains, the Session keeps only its last Turn-aligned page visible and its event stream holds the older entries in memory, so page reads return them without a request before Host paging resumes. Owners declaration-merge `SessionRetainFacetMap`; a facet is retained only when its key is `true`, the set is fixed for the reference's lifetime, and `retainInfo(id)` reports positive per-facet counts in `retainedFacets` and the connected reference count in `connectionCount`, each absent while zero. The Controller counts facets without interpreting them or their dependencies. 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. +`@deepseek-ai/dsh-api-session-controller/client/directories` exports the import-free directory readers client plugins inline instead of importing this plugin's bundle: `selectSessionDirectory(state, sessionId)` selects a Session's directory from a list snapshot (the projected `workingDirectory`, else the row's header directory) for `useSessions` selectors, and `sessionDirectory(sessions, sessionId)` reads it at gesture time from the connected Session's projection face before the list snapshot. File views, address bases, open-in-app actions, and relative paths all use that directory. + ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index fa630322d3..8b2fdea121 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -89,6 +89,8 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。每个引用都保活 Session 对象及其作用域。`connection` 默认为 `true`,同时保活 Session 自己的事件连接及其维持最新的事件窗口;没有引用保留连接时,Session 断开连接、清空窗口并保留发送回显等本地状态,下一个保留连接的引用按首次打开的流程重新连接。`connection: false` 的引用在 binding 建好时即就绪。`facets` 指明由 owner 声明、基于这些数据的计算,例如 `conversation`。连接仍在而最后一个子要素被释放时,Session 只让按 Turn 对齐的最后一页可见,更早的条目由其事件流留在内存里,读页时先从本地返回、不发请求,用完后再走 Host 分页。owner 通过声明合并扩展 `SessionRetainFacetMap`;只有值为 `true` 的键才被保留,该集合在引用生命周期内固定,`retainInfo(id)` 在 `retainedFacets` 中报告各子要素的正计数,在 `connectionCount` 中报告保留连接的引用数,为零时字段不存在。控制器只计数,不解释子要素含义或其依赖。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 +`@deepseek-ai/dsh-api-session-controller/client/directories` 导出无运行时导入的目录读取函数,客户端插件内联它们而不是导入本插件的 bundle:`selectSessionDirectory(state, sessionId)` 从列表快照选出 Session 的目录(投影的 `workingDirectory`,否则为该行的 header 目录),供 `useSessions` 选择器使用;`sessionDirectory(sessions, sessionId)` 在手势发生时先读已连接 Session 的投影面、再读列表快照。文件视图、地址基准、在应用中打开操作和相对路径都使用这个目录。 + ## 会话媒体引用 diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index b5401a0920..093d6007a2 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-session-controller", "description": "Session Remote commands, cold reads, and live control transport", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -30,6 +30,10 @@ "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./client/directories": { + "types": "./lib/types/client/sessions/directories.d.ts", + "default": "./lib/types/client/sessions/directories.js" + }, "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" diff --git a/packages/api/session-controller/src/client/sessions/directories.ts b/packages/api/session-controller/src/client/sessions/directories.ts new file mode 100644 index 0000000000..5a9406b597 --- /dev/null +++ b/packages/api/session-controller/src/client/sessions/directories.ts @@ -0,0 +1,41 @@ +/** + * The directory one Session works in, as the Client knows it: the projected + * `workingDirectory`. Pure reads with type-only imports, so client plugins + * inline this module instead of requesting a module-table row this package + * does not publish. + * @module @deepseek-ai/dsh-api-session-controller/client/directories + */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ISessions } from '../contract/sessions.ts' +import type { SessionListState } from './service.ts' + +/** A projected string value by key, from a values object whose keys the Client compilation does not declare. */ +function projectedString(values: object | undefined, key: string): string | undefined { + if (values === undefined) return undefined + const value: unknown = Reflect.get(values, key) + return typeof value === 'string' ? value : undefined +} + +/** + * Select a Session's directory from a list snapshot, for `useSessions` selectors. File views, address + * bases, and relative paths all use it; the header directory stays the original project. + * @param state - the sessions list snapshot. + * @param sessionId - the Session whose directory is selected. + * @returns the projected `workingDirectory`, else the header directory, else undefined for an unknown row. + */ +export function selectSessionDirectory(state: SessionListState, sessionId: SessionId): string | undefined { + return projectedString(state.projectionsBySession[sessionId]?.values, 'workingDirectory') + ?? projectedString(state.byId[sessionId]?.projectionValues, 'workingDirectory') + ?? state.byId[sessionId]?.cwd +} + +/** + * Read a Session's directory at gesture time: the connected Session's projection face first, then the list snapshot. + * @param sessions - the sessions service. + * @param sessionId - the Session whose directory is read. + * @returns the directory, or undefined when unknown. + */ +export function sessionDirectory(sessions: ISessions, sessionId: SessionId): string | undefined { + const live: unknown = sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() + return (typeof live === 'string' ? live : undefined) ?? selectSessionDirectory(sessions.list.getSnapshot(), sessionId) +} diff --git a/packages/api/settings-controller/package.json b/packages/api/settings-controller/package.json index 343e01daa4..a55db0a905 100644 --- a/packages/api/settings-controller/package.json +++ b/packages/api/settings-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-settings-controller", "description": "Remote owner for the configuration surfaces over the settings-domain seams", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/terminal-controller/package.json b/packages/api/terminal-controller/package.json index c39ddc927a..7202f08028 100644 --- a/packages/api/terminal-controller/package.json +++ b/packages/api/terminal-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-terminal-controller", "description": "Session-owned interactive terminals with shell discovery, screen recovery and typed Remote control", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-controller/package.json b/packages/api/workspace-controller/package.json index a1dbf632c7..dab06b4523 100644 --- a/packages/api/workspace-controller/package.json +++ b/packages/api/workspace-controller/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-controller", "description": "Workspace Remote commands and reconnect-safe state transport", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/api/workspace-files/README.i18n.yaml b/packages/api/workspace-files/README.i18n.yaml index 596997972c..d8f8bad8bd 100644 --- a/packages/api/workspace-files/README.i18n.yaml +++ b/packages/api/workspace-files/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-api-workspace-files/use-this-package: - en: a7cf7f26d6183666 - zh: 832b0b33fd389771 + en: 742a72d5336e3d62 + zh: 1bb66e5274ab2e96 /deepseek-ai-dsh-api-workspace-files/use-this-package/addressing-and-paths: en: b9565cfa7a1da451 zh: fc4078a58322fc7f @@ -48,8 +48,8 @@ en: 42b15ac6321706aa zh: ce1d25bffb6948cd /deepseek-ai-dsh-api-workspace-files/understand-the-implementation/design-concept: - en: c3a8852c33dcc0e9 - zh: d24fd47da7faaa29 + en: b4a0124b26db9dda + zh: de46ef79afc294fa /deepseek-ai-dsh-api-workspace-files/understand-the-implementation/source-map: en: c18e235fbd03e6be zh: da1c4d03bf34657d diff --git a/packages/api/workspace-files/README.md b/packages/api/workspace-files/README.md index 23cbaddcf7..64a978b70c 100644 --- a/packages/api/workspace-files/README.md +++ b/packages/api/workspace-files/README.md @@ -25,7 +25,7 @@ Use this package to preview files readable through a Session's filesystem from t ## Use this package -Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, `search(sessionId, request, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session header or uses persistence `stat` for a cold Session; it does not activate an Agent, read the event body, or borrow a parent Session's root. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. +Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, `search(sessionId, request, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host uses the workspace root the sandbox policy resolves for a live Session, or a cold Session's recorded directory from the projection cache beside its persisted header, falling back to the header directory; it does not activate an Agent, read the event body, or borrow a parent Session's root. `workspaceFiles.scopeOf(sessionId, signal)` offers that resolution to other Host services that open the same `session//` addresses. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. | Method | Returns | Purpose | |---|---|---| @@ -107,7 +107,7 @@ One supervised `changes` stream serves each Session and requested path; consumer ### Design concept -Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session header or the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports. +Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session's sandbox workspace root or a stored Session's cached directory beside the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports. Complete-file reads delegate size enforcement to `fs.readBytes` and return raw bytes through the binary Remote. diff --git a/packages/api/workspace-files/README.zh.md b/packages/api/workspace-files/README.zh.md index 938fe8ba9d..8ffb646100 100644 --- a/packages/api/workspace-files/README.zh.md +++ b/packages/api/workspace-files/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)`、`search(sessionId, request, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 读取 live Session header,cold Session 则使用持久层 `stat`;它不会激活 Agent、读取事件正文或借用父 Session 的根。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 +把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)`、`search(sessionId, request, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 对 live Session 使用沙箱策略解析出的工作区根,cold Session 则读取持久化 header 旁投影缓存中记录的目录,再回退到 header 目录;它不会激活 Agent、读取事件正文或借用父 Session 的根。`workspaceFiles.scopeOf(sessionId, signal)` 把这一解析提供给打开同一种 `session//` 地址的其他 Host 服务。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 | 方法 | 返回 | 用途 | |---|---|---| @@ -107,7 +107,7 @@ kind: "package-reference" ### 设计概念 -经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session header 或持久层的 header-only `stat` 导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。 +经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session 的沙箱工作区根,或 stored Session 在持久层 header-only `stat` 旁缓存的目录导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。 完整文件读取将大小上限检查交给 `fs.readBytes`,并通过二进制 Remote 返回原始字节。 diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index 41307df21b..4e48b38355 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-api-workspace-files", "description": "Workspace file service and Client resource provider: bounded reads, directory listing, and live metadata over the workspaceFiles Remote namespace", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -75,9 +75,11 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-persistence": "workspace:*", - "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", - "@deepseek-ai/dsh-subprocess-local": "workspace:*" + "@deepseek-ai/dsh-subprocess-local": "workspace:*", + "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/api/workspace-files/src/index.ts b/packages/api/workspace-files/src/index.ts index 66b25581f3..d6bb632d98 100644 --- a/packages/api/workspace-files/src/index.ts +++ b/packages/api/workspace-files/src/index.ts @@ -4,11 +4,11 @@ * filesystem-observation change feed, exposed as `workspaceFiles`. * * File reads follow the composed filesystem's read access, including paths - * outside the workspace. The selected Session header supplies the base for - * relative paths, with the sandbox policy root as its no-cwd fallback, not a - * read-containment restriction. Directory listings, searches, and change - * observations remain workspace-scoped; a search reports workspace-relative - * paths. File-kind checks and configured read caps apply to + * outside the workspace. The selected Session's workspace root supplies the + * base for relative paths, with the header directory and then the sandbox + * policy root as fallbacks, not a read-containment restriction. Directory + * listings, searches, and change observations remain workspace-scoped; a + * search reports workspace-relative paths. File-kind checks and configured read caps apply to * every preview; this service exposes no mutations. * * A page is cut from `streamText`, which decodes and rejects non-UTF-8 as it @@ -28,8 +28,10 @@ import type { FsDirEntry, FsInfo, FsPathInfo, FsTarget } from '@deepseek-ai/dsh- import type {} from '@deepseek-ai/dsh-sandbox-policy' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-persistence' +import type {} from '@deepseek-ai/dsh-session-projection-cache' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { Remote, RemoteError, TypertRemoteService, type TypertLookup } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-working-directory' import { WorkspaceChangeFeed } from './changes.ts' import { searchWorkspace, type SearchLimits } from './search.ts' import type { @@ -59,10 +61,34 @@ declare module '@deepseek-ai/cordis' { export interface WorkspaceFileScope { /** Session identity received on the wire. */ readonly sessionId: SessionId - /** Session workspace root, or the deployment fallback when its header has no cwd. */ + /** + * Session workspace root: for a live Session the root the sandbox policy + * bounds it by; for a stored one its directory in the projection cache, else + * its header directory, else the deployment fallback. + */ readonly workspaceRoot: string } +/** + * Resolve the workspace root a Session's file views and directory listings + * use, without loading its event body or activating an Agent. + * @param ctx - Host context carrying the Session store and the sandbox policy, and optionally persistence + * and the projection cache. + * @param sessionId - Session identity received on the wire. + * @param signal - cancellation for the persistence read of a stored Session. + * @returns the scope, or undefined when no live or stored Session has that identity. + */ +async function workspaceFileScopeOf( + ctx: Context, sessionId: SessionId, signal?: AbortSignal, +): Promise { + const live = ctx.get('sessions')?.get(sessionId) + if (live !== undefined) return { sessionId, workspaceRoot: ctx.sandboxPolicy.resolve({ session: live }).workspaceRoot } + const stored = await ctx.get('sessionPersistence')?.stat(sessionId, signal === undefined ? undefined : { signal }) + if (stored === undefined) return undefined + const cached = ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header, ['workingDirectory'])?.values.workingDirectory + return { sessionId, workspaceRoot: cached ?? stored.header.cwd ?? ctx.sandboxPolicy.workspaceRoot } +} + declare module '@deepseek-ai/dsh-typert-protocol' { interface TypertLookupMap { /** Resolve a Session id to its workspace root without loading its event body or activating an Agent. */ @@ -219,22 +245,22 @@ export class WorkspaceFiles extends TypertRemoteService { resource: 'session', hostTypeSymbol: '@deepseek-ai/dsh-api-workspace-files#WorkspaceFileScope', wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId', - resolve: async (sessionId) => { - const live = scope.sessions.get(sessionId)?.header - const stored = live === undefined - ? await scope.get('sessionPersistence')?.stat(sessionId) - : undefined - const header = live ?? stored?.header - if (header === undefined) return undefined - return { - sessionId, - workspaceRoot: header.cwd ?? scope.sandboxPolicy.workspaceRoot, - } - }, + resolve: sessionId => workspaceFileScopeOf(scope, sessionId), }) }) } + /** + * Resolve the scope other Host services use to open the same `session//` addresses: + * a live Session's sandbox workspace root, else a stored Session's cached directory, else its header directory. + * @param sessionId - Session identity received on the wire. + * @param signal - cancellation for the persistence read of a stored Session. + * @returns the scope, or undefined when no live or stored Session has that identity. + */ + scopeOf(sessionId: SessionId, signal?: AbortSignal): Promise { + return workspaceFileScopeOf(this.ctx, sessionId, signal) + } + /** * Read one page of lines from a UTF-8 file readable by the filesystem backend. * @param workspaceFileScope - header-derived workspace root for the Session identity on the wire. diff --git a/packages/api/workspace-files/tests/scope.spec.ts b/packages/api/workspace-files/tests/scope.spec.ts index d1b3d377eb..21ac7e1920 100644 --- a/packages/api/workspace-files/tests/scope.spec.ts +++ b/packages/api/workspace-files/tests/scope.spec.ts @@ -26,10 +26,53 @@ function header(id: SessionId, cwd?: string): SessionHeader { } describe('Workspace Files Session scope lookup', () => { + it('prefers the recorded workspace root of a live or stored Session over its header directory', async () => { + const liveId = brandString('live-relocated') + const coldId = brandString('cold-relocated') + const plainId = brandString('cold-plain') + const liveRoot = resolve('live-workspace') + const liveWorktree = resolve('live-workspace', '.agents', 'worktrees', 'topic') + const coldRoot = resolve('cold-workspace') + const coldWorktree = resolve('elsewhere', 'cold-topic') + const stat = vi.fn(async (id: SessionId) => { + if (id === coldId) return { header: header(coldId, coldRoot) } + if (id === plainId) return { header: header(plainId, coldRoot) } + return undefined + }) + const cachedSnapshot = vi.fn((meta: SessionHeader) => + meta.id === coldId ? { asOfSeq: 4, values: { workingDirectory: coldWorktree } } : undefined) + const ctx = new Context() + ctx.provide('fs', {} as never) + // A live Session's root is the one the sandbox policy bounds it by. + const resolvePolicy = vi.fn(() => ({ mode: 'workspace-write', workspaceRoot: liveWorktree })) + ctx.provide('sandboxPolicy', { workspaceRoot: resolve('fallback-workspace'), resolve: resolvePolicy } as never) + ctx.provide('sessionPersistence', { stat } as never) + ctx.provide('sessionProjectionCache', { cachedSnapshot } as never) + const sessions = await ctx.plugin(SessionStore) + const typert = await ctx.plugin(TypertRegistry) + const workspaceFiles = await ctx.plugin(WorkspaceFiles, CAPS) + try { + const live = ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } }) + await expect(ctx.workspaceFiles.scopeOf(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveWorktree }) + expect(resolvePolicy).toHaveBeenCalledWith({ session: live }) + await expect(ctx.workspaceFiles.scopeOf(coldId)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldWorktree }) + await expect(ctx.workspaceFiles.scopeOf(plainId)).resolves.toEqual({ sessionId: plainId, workspaceRoot: coldRoot }) + expect(cachedSnapshot).toHaveBeenCalledWith(expect.objectContaining({ id: coldId }), ['workingDirectory']) + const lookup = ctx.typert.lookups.get('workspaceFileScope') + if (lookup === undefined) throw new Error('workspaceFileScope lookup did not register') + await expect(lookup.resolve(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveWorktree }) + } finally { + await workspaceFiles.dispose() + await sessions.dispose() + await typert.dispose() + } + }) + it('uses live or stored headers without an Agent and leaves with its plugin', async () => { const liveId = brandString('live-subagent') const coldId = brandString('cold-subagent') const fallbackId = brandString('cold-without-cwd') + const liveFallbackId = brandString('live-without-cwd') const missingId = brandString('missing') const liveRoot = resolve('live-workspace') const coldRoot = resolve('cold-workspace') @@ -41,7 +84,8 @@ describe('Workspace Files Session scope lookup', () => { }) const ctx = new Context() ctx.provide('fs', {} as never) - ctx.provide('sandboxPolicy', { workspaceRoot: fallbackRoot } as never) + const resolvePolicy = ({ session }: { session: { header: SessionHeader } }) => ({ mode: 'read-only', workspaceRoot: session.header.cwd ?? fallbackRoot }) + ctx.provide('sandboxPolicy', { workspaceRoot: fallbackRoot, resolve: resolvePolicy } as never) ctx.provide('sessionPersistence', { stat } as never) const sessions = await ctx.plugin(SessionStore) const typert = await ctx.plugin(TypertRegistry) @@ -49,6 +93,7 @@ describe('Workspace Files Session scope lookup', () => { try { ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } }) + ctx.sessions.create(liveFallbackId, { meta: { origin: 'subagent' } }) expect(ctx.get('agents')).toBeUndefined() const lookup = ctx.typert.lookups.get('workspaceFileScope') expect(lookup).toMatchObject({ @@ -62,11 +107,15 @@ describe('Workspace Files Session scope lookup', () => { if (lookup === undefined) throw new Error('workspaceFileScope lookup did not register') await expect(lookup.resolve(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveRoot }) + await expect(lookup.resolve(liveFallbackId)).resolves.toEqual({ sessionId: liveFallbackId, workspaceRoot: fallbackRoot }) expect(stat).not.toHaveBeenCalled() + const signal = new AbortController().signal + await expect(ctx.workspaceFiles.scopeOf(coldId, signal)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldRoot }) + expect(stat).toHaveBeenLastCalledWith(coldId, { signal }) await expect(lookup.resolve(coldId)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldRoot }) await expect(lookup.resolve(fallbackId)).resolves.toEqual({ sessionId: fallbackId, workspaceRoot: fallbackRoot }) await expect(lookup.resolve(missingId)).resolves.toBeUndefined() - expect(stat.mock.calls.map(([id]) => id)).toEqual([coldId, fallbackId, missingId]) + expect(stat.mock.calls.map(([id]) => id)).toEqual([coldId, coldId, fallbackId, missingId]) await workspaceFiles.dispose() expect(ctx.typert.lookups.get('workspaceFileScope')).toBeUndefined() diff --git a/packages/api/workspace-files/tsconfig.host.json b/packages/api/workspace-files/tsconfig.host.json index 572cac209c..89da5a19ee 100644 --- a/packages/api/workspace-files/tsconfig.host.json +++ b/packages/api/workspace-files/tsconfig.host.json @@ -36,6 +36,12 @@ { "path": "../../util/deque" }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/working-directory" + }, { "path": "../../util/ripgrep" }, diff --git a/packages/attachment/attachment-local/package.json b/packages/attachment/attachment-local/package.json index b586db2b40..773772c2c8 100644 --- a/packages/attachment/attachment-local/package.json +++ b/packages/attachment/attachment-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment-local", "description": "Private content-addressed DSH_HOME attachment storage", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/attachment/attachment/package.json b/packages/attachment/attachment/package.json index b4614f5c1f..8489a846d1 100644 --- a/packages/attachment/attachment/package.json +++ b/packages/attachment/attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-attachment", "description": "Durable immutable attachment storage seam for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/app-boot/package.json b/packages/boot/app-boot/package.json index ab1f6ceab8..65562ad335 100644 --- a/packages/boot/app-boot/package.json +++ b/packages/boot/app-boot/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-app-boot", "description": "Shared boot glue for the app bins: .env loading, fail-loud Loader guards, snapshot-aware config resolution, and the Loader boot sequence", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/cmdline/package.json b/packages/boot/cmdline/package.json index 3a0ef14e60..dd92ad0bb2 100644 --- a/packages/boot/cmdline/package.json +++ b/packages/boot/cmdline/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cmdline", "description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/config-editor/package.json b/packages/boot/config-editor/package.json index f902372019..0ec3e5d1fb 100644 --- a/packages/boot/config-editor/package.json +++ b/packages/boot/config-editor/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-config-editor", "description": "Persist plugin configuration through profile patches and Loader reconciliation", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/hmr/package.json b/packages/boot/hmr/package.json index 791b92add7..eddc80cd8b 100644 --- a/packages/boot/hmr/package.json +++ b/packages/boot/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-hmr", "description": "Coordinated module and profile configuration hot reload", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/plugin-manager/package.json b/packages/boot/plugin-manager/package.json index 464c101f0e..981196600f 100644 --- a/packages/boot/plugin-manager/package.json +++ b/packages/boot/plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-manager", "description": "Current-profile plugin and bundle management shared by dsh CLI, Web and agent tools", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/boot/plugin-market/package.json b/packages/boot/plugin-market/package.json index 982ab1bbeb..2413b1087a 100644 --- a/packages/boot/plugin-market/package.json +++ b/packages/boot/plugin-market/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-plugin-market", "description": "Configured plugin market indexes for the Web Discover page and the plugin_market agent tool", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/browser-use/browser-use/package.json b/packages/browser-use/browser-use/package.json index 0b95d0e976..e270d99f7c 100644 --- a/packages/browser-use/browser-use/package.json +++ b/packages/browser-use/browser-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-browser-use", "description": "Exclusive named browser-use provider registration", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/acp-app/package.json b/packages/bundle/acp-app/package.json index 219acd7f7c..d04b8e395f 100644 --- a/packages/bundle/acp-app/package.json +++ b/packages/bundle/acp-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-acp-app", "description": "The dsh ACP profile bundle: automation-only JSON-RPC stdio and process lifecycle over dsh-base", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 7145434867..c1aa70ec84 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -352,7 +352,7 @@ Explore first. Use non-mutating reads, searches, static analysis, and checks to ground the plan in the actual repository. Do not edit or write files, change configuration, run formatters or code generation that rewrites tracked files, commit, or otherwise carry out the plan. Prefer existing functions and patterns over new machinery. - The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed only to keep the request shape stable. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode. + The tool catalog stays the same across modes for request-cache stability. These plan-mode rules override any later tool description or guidance that suggests using mutation tools; those tools remain listed to keep the tool catalog unchanged. Do not use todo_write to track this planning phase: it tracks implementation after an approved plan, while the plan itself belongs in exit_plan_mode. Resolve discoverable facts by inspection. Use ask_user_question only for user-owned choices or material ambiguity that inspection cannot answer. Do not ask the user where code lives or how current behavior works when you can find out. @@ -475,7 +475,11 @@ # The shared base enables the stable model-facing web_search and web_fetch # tools. The Web app disables this host row and composes both tools per agent # preset; products with a stricter network policy override tool-web. Search - # defaults to the DeepSeek Search API (deepseek-search-api) and fetch to the + # composes no fixed provider, so dsh-web selects per model provider route: + # legacy Messages search (deepseek-official) for a conversation on a DeepSeek + # model route, because DeepSeek makes no per-search charge for it, and the + # DeepSeek Search API (deepseek-search-api) for every other route. Fetch + # defaults to the # anonymous local fetcher (http). The DeepSeek Search and Fetch APIs # (deepseek-search-api, deepseek-fetch-api) follow the conversation: on the # deepseek-account route they send the account token to that route's @@ -483,8 +487,8 @@ # origin, so a DEEPSEEK_API_KEY alone serves both without a sign-in. # searchBaseURL / searchApiKeyEnv (fetch* for Fetch) pin one capability to # its own endpoint and key instead. - # Legacy Messages search (deepseek-official) is selectable separately and - # uses its own endpoint, with the account token or DEEPSEEK_API_KEY. + # Legacy Messages search uses its own endpoint, with the account token or + # DEEPSEEK_API_KEY. # Anonymous fetch accepts only public # HTTP(S) destinations, resolves and validates every destination, and pins # every actual connection. This composition gives web_search 60s whichever @@ -495,7 +499,6 @@ - id: web name: '@deepseek-ai/dsh-web' config: - searchProvider: deepseek-search-api fetchProvider: http - id: web-search-deepseek diff --git a/packages/bundle/base/package.json b/packages/bundle/base/package.json index 26592cd2c4..62c16843b3 100644 --- a/packages/bundle/base/package.json +++ b/packages/bundle/base/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-base", "description": "The shared dsh core as a profile bundle: the first patch layer of base-backed profiles, inserting core rows over the empty profile root", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/base/tests/base.spec.ts b/packages/bundle/base/tests/base.spec.ts index fdd22df18c..e471ddac8c 100644 --- a/packages/bundle/base/tests/base.spec.ts +++ b/packages/bundle/base/tests/base.spec.ts @@ -37,7 +37,7 @@ describe('dsh-base bundle', () => { }) expect(rows.filter(row => row.id === 'subagent-codex')).toHaveLength(0) expect(rows.filter(row => row.id === 'subagent-claude-code')).toHaveLength(0) - expect(rows.find(row => row.id === 'web')?.config).toEqual({ searchProvider: 'deepseek-search-api', fetchProvider: 'http' }) + expect(rows.find(row => row.id === 'web')?.config).toEqual({ fetchProvider: 'http' }) expect(rows.find(row => row.id === 'web-deepseek-api')).toEqual({ id: 'web-deepseek-api', name: '@deepseek-ai/dsh-web-deepseek-api' }) expect(rows.find(row => row.id === 'web-fetch-http')).toBeDefined() expect(rows.find(row => row.id === 'web-search-deepseek')).toMatchObject({ diff --git a/packages/bundle/headless/package.json b/packages/bundle/headless/package.json index cff85512ad..4a52d0dca9 100644 --- a/packages/bundle/headless/package.json +++ b/packages/bundle/headless/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-headless", "description": "The dsh one-shot bundle: a direct core Agent/Session runner over dsh-base with no Host, HTTP, or browser layer", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/sdk-app/README.i18n.yaml b/packages/bundle/sdk-app/README.i18n.yaml index 6a9acc36cf..d808749914 100644 --- a/packages/bundle/sdk-app/README.i18n.yaml +++ b/packages/bundle/sdk-app/README.i18n.yaml @@ -24,17 +24,17 @@ en: 4f88e647c6df4f42 zh: 2bd3e4b0bdfe9412 /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/what-the-model-sees: - en: 2beeaec08b6e1a6d - zh: 9b98b0ae6be6c1bc + en: 2c54cdab827df6dc + zh: 575a00d86ecea5aa /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/token-effect: - en: cef8efe97fe1ff16 - zh: c052ab3e6706efa6 + en: 7bb67dfbf1621d73 + zh: 71414a307ccf3f7b /deepseek-ai-dsh-sdk-app/model-experience/sdk-model-context/kv-cache-effect: - en: b1169743449b2272 - zh: 98d465d802bf55c1 + en: ccce9395f246ba39 + zh: d758f8a78f03878d /deepseek-ai-dsh-sdk-app/known-limitations-and-deferred-work: - en: d1d4567b7d2b9d8d - zh: c1618617d1562d8b + en: 9c42e75920483b74 + zh: 0e9ff65a001a5919 /deepseek-ai-dsh-sdk-app/known-limitations-and-deferred-work/dev-note: en: b9b4e27513ebba78 zh: 51b123ac60ff28c6 diff --git a/packages/bundle/sdk-app/README.md b/packages/bundle/sdk-app/README.md index 9eef06c769..3101c4fbac 100644 --- a/packages/bundle/sdk-app/README.md +++ b/packages/bundle/sdk-app/README.md @@ -48,22 +48,22 @@ The Python runtime exposes explicitly downloaded authoring resources and Office #### What the model sees -The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, `plugin_manager`, schedule tools, shared file-reference guidance, and time context. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. The skill catalog always lists the Office skills; their Python environment section names `load_workspace_dependencies` with an authoring payload and the user's existing Python without one. +The profile inherits the base system prompt, including the `You are an AI agent powered by DeepSeek Harness.` identity, and adds the same model-interpolated coding persona as the Web and headless profiles. Each Session receives its current directory in required user-role context from [`dsh-working-directory`](../../session/working-directory/README.md). Default file tool schemas include `read`, `write`, and `edit`; they omit `str_replace_editor`. The model also receives `present`, `ask_user_question`, `plugin_manager`, schedule tools, shared file-reference guidance, and time context. Child agents cannot use schedule tools. The [`time-context`](../../context/time-context/README.md) row accepts a fallback time zone. Each ordinary prompt reports its zone like a Web prompt: the client's `timeZone` (`time_zone` in Python) when given, otherwise the runtime process zone sampled for that prompt, so the model sees `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.` A process zone that is not UTC or an IANA Area/Location name, such as the `+00:00` that `TZ=GMT` produces, reports `unavailable`. The skill catalog always lists the Office skills; their Python environment section names `load_workspace_dependencies` with an authoring payload and the user's existing Python without one. The catalog also lists `dsh-doc`, the DSH documentation skill that the Desktop standard, PTC, and Creator presets list; see the [Web app](../web-app/README.md#model-experience) for what it guides. #### Token effect -The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. The `plugin_manager` description and parameter schema add input tokens even when an operation cannot be approved; an embedding that does not use plugin management can disable its row. +The profile adds a coding-persona sentence, the mounted tool definitions and guidance, and logged runtime-context and time messages. The `plugin_manager` description and parameter schema add input tokens even when an operation cannot be approved; an embedding that does not use plugin management can disable its row. The `dsh-doc` catalog entry adds about 125 heuristic tokens to the first request; its instructions and references enter context only when the model loads the skill. #### KV Cache effect -Enabling `plugin_manager` changes the tool-schema prefix from earlier SDK versions. The static prefix is stable for a fixed profile, provider, model, and tool roster. Runtime values append to logged user context. Profile changes take effect on the next process because the shipped SDK profile uses startup-only patches. +Enabling `plugin_manager` changes the tool-schema prefix from earlier SDK versions, and the `dsh-doc` entry changes the skill catalog logged at the first step. The static prefix is stable for a fixed profile, provider, model, and tool roster. Runtime values append to logged user context. Profile changes take effect on the next process because the shipped SDK profile uses startup-only patches. ## Known Limitations and Deferred Work - **No graphical client** — file cards, native file opening, and browser state require an embedding client; the SDK starts no Web server. -- **User time zone is unknown** — the SDK protocol does not carry a user time zone, so time context reports `Browser time zone for this request: unavailable.` The process or container time zone may differ from the user's. The `time-context.timeZone` setting only controls fallback timestamp formatting; it does not establish the user's time zone. Automatic detection and SDK time-zone input are deferred. +- **The process zone stands in for the user** — a prompt without `timeZone` reports the runtime process zone, which may differ from the user's; containers usually run in UTC. Pass the user's zone per prompt or set `TZ` for the runtime. The `time-context.timeZone` setting only controls fallback timestamp formatting; it does not establish the user's time zone. Native commands record no zone, matching Web commands, so a turn opened by `/plan ` reports `unavailable`. - **Questions require an answerer** — configure `onUserQuestion` in TypeScript or `on_user_question` in Python, or supply a native `user-questions/request` handler; otherwise `ask_user_question` returns `NO_PROVIDER`. - **Schedules share the runtime lifetime** — delivery needs a running process and its persistent Session storage. - **A profile can omit the SDK server** — a custom profile selected by the TypeScript client must retain this bundle or another `dsh-sdk-jsonrpc-server` row; client initialization fails when no peer answers. diff --git a/packages/bundle/sdk-app/README.zh.md b/packages/bundle/sdk-app/README.zh.md index 2693d31def..a24c4f4358 100644 --- a/packages/bundle/sdk-app/README.zh.md +++ b/packages/bundle/sdk-app/README.zh.md @@ -48,22 +48,22 @@ Python 运行时向本 profile 提供显式下载的创作资源和 Office sidec #### 模型看到什么 -profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、`plugin_manager`、定时任务工具、共用文件引用说明和时间上下文。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。技能目录总是列出 Office skills;有创作载荷时其 Python 环境说明指向 `load_workspace_dependencies`,没有时指向用户已有的 Python。 +profile 继承 base 系统提示词,包括 `You are an AI agent powered by DeepSeek Harness.` 身份说明,并添加与 Web 和 headless profile 相同、按当前模型插值的 coding persona。每个 Session 通过 [`dsh-working-directory`](../../session/working-directory/README.zh.md) 提供的必需 user-role 上下文接收当前目录。默认文件工具 schema 包含 `read`、`write` 和 `edit`,不包含 `str_replace_editor`。模型还会收到 `present`、`ask_user_question`、`plugin_manager`、定时任务工具、共用文件引用说明和时间上下文。子 agent 不能使用定时任务工具。[`time-context`](../../context/time-context/README.zh.md) 配置项接受回退时区。每条普通 prompt 像 Web prompt 一样上报时区:传入了客户端的 `timeZone`(Python 中为 `time_zone`)时用它,否则用运行时为这条 prompt 采样的进程时区,因此模型看到 `Browser time zone for this request: . Interpret otherwise-unqualified dates and times in this zone.`。进程时区既不是 UTC 也不是 IANA Area/Location 名称时(例如 `TZ=GMT` 产生的 `+00:00`),上报 `unavailable`。技能目录总是列出 Office skills;有创作载荷时其 Python 环境说明指向 `load_workspace_dependencies`,没有时指向用户已有的 Python。技能目录还列出 `dsh-doc`,即 Desktop 标准模式、PTC 模式和创造模式列出的 DSH 文档 skill;其用途参见 [Web app](../web-app/README.zh.md#model-experience)。 #### Token 影响 -此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 即使操作无法获批,`plugin_manager` 的描述和参数 schema 仍增加输入 token;不使用插件管理的嵌入方可禁用该条目。 +此 profile 添加一句 coding persona、所挂载的工具定义与说明,以及记录在日志中的运行时上下文和时间消息。 即使操作无法获批,`plugin_manager` 的描述和参数 schema 仍增加输入 token;不使用插件管理的嵌入方可禁用该条目。`dsh-doc` 目录项使首个请求增加约 125 个启发式估算 token;其指令和参考资料仅在模型加载该 skill 时进入上下文。 #### KV Cache 影响 -启用 `plugin_manager` 会改变早期 SDK 版本的工具 schema 前缀。对固定 profile、提供方、模型与工具清单,静态前缀保持稳定。运行时值追加到已记录的 user 上下文中。由于随附 SDK profile 使用仅启动时 patch,profile 变化会在下一个进程生效。 +启用 `plugin_manager` 会改变早期 SDK 版本的工具 schema 前缀,`dsh-doc` 目录项会改变第一个步骤记录的技能目录。对固定 profile、提供方、模型与工具清单,静态前缀保持稳定。运行时值追加到已记录的 user 上下文中。由于随附 SDK profile 使用仅启动时 patch,profile 变化会在下一个进程生效。 ## 已知限制与延期工作 - **没有图形客户端**:文件卡片、本地文件打开和浏览器状态需要嵌入客户端;SDK 不启动 Web server。 -- **用户时区未知**:SDK 协议不携带用户时区,因此时间上下文显示 `Browser time zone for this request: unavailable.`。进程或容器的时区可能与用户时区不同。`time-context.timeZone` 配置只控制回退时间戳的显示格式,不能据此确定用户时区。自动检测和 SDK 时区传参暂缓支持。 +- **进程时区代替用户时区**:不带 `timeZone` 的 prompt 上报运行时进程时区,它可能与用户时区不同;容器通常运行在 UTC。请为每条 prompt 传入用户时区,或为运行时设置 `TZ`。`time-context.timeZone` 配置只控制回退时间戳的显示格式,不能据此确定用户时区。原生命令与 Web 命令一样不记录时区,因此由 `/plan ` 开启的轮次上报 `unavailable`。 - **提问需要回答方**:在 TypeScript 中配置 `onUserQuestion`、在 Python 中配置 `on_user_question`,或提供原生 `user-questions/request` handler;否则 `ask_user_question` 返回 `NO_PROVIDER`。 - **定时任务依赖运行时生命周期**:投递需要运行中的进程及其持久化 Session 存储。 - **profile 可能省略 SDK server**:TypeScript client 选择的自定义 profile 必须保留本组合包或另一个 `dsh-sdk-jsonrpc-server` 配置项;没有 peer 响应时,client 初始化会失败。 diff --git a/packages/bundle/sdk-app/cordis.patch.yml b/packages/bundle/sdk-app/cordis.patch.yml index e53d193129..2ac50b906e 100644 --- a/packages/bundle/sdk-app/cordis.patch.yml +++ b/packages/bundle/sdk-app/cordis.patch.yml @@ -53,6 +53,15 @@ config: pythonEnvironment: !!js "process.env.DSH_PRIMARY_RUNTIME ? 'workspace-dependencies' : 'user'" +# The skill catalog lists dsh-doc, as the Desktop standard, PTC, and Creator +# presets do; its instructions load only when the model calls `skill`. The +# path resolves through this package's `@deepseek-ai/dsh-agent-preset` +# dependency, which no plugin row names. +- id: skill-filesystem + config: + customSkillDirs: + - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills') + # Share native desktop tools and model context without starting a Web server. - insert: - id: connection diff --git a/packages/bundle/sdk-app/package.json b/packages/bundle/sdk-app/package.json index 9870f83080..c0f7ad01e5 100644 --- a/packages/bundle/sdk-app/package.json +++ b/packages/bundle/sdk-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-app", "description": "The dsh SDK profile bundle: stdio JSON-RPC serving and process lifecycle over dsh-base", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -39,6 +39,7 @@ } }, "dependencies": { + "@deepseek-ai/dsh-agent-preset": "workspace:*", "@deepseek-ai/dsh-cmdline": "workspace:*", "@deepseek-ai/dsh-office-kit": "workspace:*", "@deepseek-ai/dsh-sdk-jsonrpc-server": "workspace:*", diff --git a/packages/bundle/sdk-minimal/package.json b/packages/bundle/sdk-minimal/package.json index ad249ecae5..97b6462b72 100644 --- a/packages/bundle/sdk-minimal/package.json +++ b/packages/bundle/sdk-minimal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-sdk-minimal", "description": "The standalone minimal SDK profile bundle: JSON-RPC, one DeepSeek adapter, persistent shell, and JSONL sessions", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index ed254d7226..502d2c2f3f 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -30,8 +30,8 @@ en: df205a26b6d49168 zh: e46ed7cf9e06248a /deepseek-ai-dsh-web-app/use-this-package/per-session-agent-setup: - en: 23cd05a35a675076 - zh: 6f32ef8a4a6a2c4d + en: 1e33a677bcad2e4e + zh: 7a69b71a6b98c432 /deepseek-ai-dsh-web-app/understand-the-implementation: en: 567cf3afa68e6b68 zh: f065cdb56c28d4e6 @@ -57,8 +57,8 @@ en: 276322084b9659d1 zh: 759aae367669520a /deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/what-the-model-sees: - en: 120d7eb063f9d498 - zh: 4960aab0c5e89535 + en: 5424de598384be21 + zh: b218ac12f252e6a6 /deepseek-ai-dsh-web-app/model-experience/dsh-documentation-skill/token-effect: en: a639f2167f49dd3d zh: 7b627d16829f1c75 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index 1d8bb92a3c..a4e642cb4c 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -96,7 +96,7 @@ When you launch `dsh --profile web` over SSH, the URL line still prints but the Each browser session selects a shipped preset (`standard` by default). The Agent presets settings page changes the default and edits preset child plugins; saves persist in `$DSH_HOME/profiles/web/cordis.patch.yml`. Standard and Creator enable the plugin-management tool only when the Host provides an editable profile. -Both modes expose read-only runtime inspection through `cordis_inspect`; see [its context effects](../../extensions/tool-cordis/README.md#model-experience). Standard and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. +Both modes expose read-only runtime inspection through `cordis_inspect`; see [its context effects](../../extensions/tool-cordis/README.md#model-experience). Standard, PTC, and Creator include the `dsh-doc` skill for questions about DSH and requested plugin or preset work. It guides the agent to the installed version's documentation and source. See [Model Experience](#model-experience) for loading and context effects. The packaged skill uses the custom skill root: a same-named project skill overrides it, and it overrides same-named user skills. One catalog entry wins without an error; see [skill-root priority](../../skill/skill-filesystem/README.md). @@ -161,7 +161,7 @@ Read these pages when you want to go deeper into the shared core, the browser re #### What the model sees -Standard and Creator list `dsh-doc` in the skill catalog. The `skill` tool loads its instructions and directs the agent to references for the current task. Other presets retain their own skill sources. Loading the skill does not modify workspace files or profile settings. +Standard, PTC, and Creator list `dsh-doc` in the skill catalog, as the SDK profile does. The `skill` tool loads its instructions and directs the agent to references for the current task. Other presets retain their own skill sources. Loading the skill does not modify workspace files or profile settings. #### Token effect diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index ffc1eed63d..00d349c3a1 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -96,7 +96,7 @@ dsh --profile web --no-open --host "$(hostname -i | awk '{print $1}')" --public- 每个浏览器会话选择一个随发行版交付的 preset(默认 `standard`)。Agent 预设设置页可更改默认项并编辑预设的子插件;保存结果持久化到 `$DSH_HOME/profiles/web/cordis.patch.yml`。只有 Host 提供可编辑的 profile 时,标准模式和 Creator 才会启用插件管理工具。 -两种模式均通过 `cordis_inspect` 提供只读运行时检查;参见[其上下文影响](../../extensions/tool-cordis/README.zh.md#model-experience)。标准模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 +两种模式均通过 `cordis_inspect` 提供只读运行时检查;参见[其上下文影响](../../extensions/tool-cordis/README.zh.md#model-experience)。标准模式、PTC 模式和创造模式包含 `dsh-doc` skill,用于 DSH 相关问题以及你要求的插件或预设工作。该 skill 引导 agent 查阅已安装版本的文档和源码。加载方式及其对上下文的影响参见[模型体验](#model-experience)。 打包的 skill 使用自定义 skill 根目录:同名的项目 skill 会覆盖打包的 skill,打包的 skill 又会覆盖同名的用户 skill。skill 目录中只保留优先级最高的一个条目,不会报错;参见 [skill 根目录优先级](../../skill/skill-filesystem/README.zh.md)。 @@ -161,7 +161,7 @@ URL 行与浏览器交接都是就绪信号:监督方一观察到该行就发 #### 模型看到什么 -标准模式和创造模式的 skill 目录都列出 `dsh-doc`。`skill` 工具加载其指令,并引导 agent 查阅当前任务所需的参考资料。其他 preset 保留各自的 skill 来源。加载该 skill 不会修改工作区文件或 profile 设置。 +标准模式、PTC 模式和创造模式的 skill 目录都列出 `dsh-doc`,与 SDK profile 相同。`skill` 工具加载其指令,并引导 agent 查阅当前任务所需的参考资料。其他 preset 保留各自的 skill 来源。加载该 skill 不会修改工作区文件或 profile 设置。 #### Token 影响 diff --git a/packages/bundle/web-app/package.json b/packages/bundle/web-app/package.json index cccc4b7e2e..7b8e134034 100644 --- a/packages/bundle/web-app/package.json +++ b/packages/bundle/web-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-web-app", "description": "The dsh browser-surface bundle: the web patch layer over dsh-base plus the runtime glue plugin (frontend dist serving, bash runtime variables, URL line)", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 7a9329e5db..dd935b1edd 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -39,6 +39,9 @@ name: '@deepseek-ai/dsh-tool-schedule' - id: skill-filesystem name: '@deepseek-ai/dsh-skill-filesystem' + config: + customSkillDirs: + - !!js process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(baseUrl).resolve('@deepseek-ai/dsh-agent-preset/package.json')), 'skills') - id: tool-skill name: '@deepseek-ai/dsh-tool-skill' - id: command-goal diff --git a/packages/client/config/package.json b/packages/client/config/package.json index 6e3afd0662..c079112fec 100644 --- a/packages/client/config/package.json +++ b/packages/client/config/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-config", "description": "Types of browser-synced plugin configuration", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index c744b0052d..0c9ddd05d7 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-connection", "description": "Authenticated RPC transport and generation lifecycle", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/file-upload/package.json b/packages/client/file-upload/package.json index cef51235dd..4705fc45b1 100644 --- a/packages/client/file-upload/package.json +++ b/packages/client/file-upload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-file-upload", "description": "Agent-scoped browser file upload, streaming intake, and staged receipt service", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/hmr/package.json b/packages/client/hmr/package.json index d62839c23b..7f83d5b37d 100644 --- a/packages/client/hmr/package.json +++ b/packages/client/hmr/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-hmr", "description": "Web client graph and rebuilt-bundle delivery over an authenticated Remote stream", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/locale/package.json b/packages/client/locale/package.json index 6a27962537..0210821ae8 100644 --- a/packages/client/locale/package.json +++ b/packages/client/locale/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-locale", "description": "Locale plugin: Host-backed preference, extensible language catalog, browser fallback, and typed built-in dictionaries", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/modules/package.json b/packages/client/modules/package.json index 822bb51664..827c6193e3 100644 --- a/packages/client/modules/package.json +++ b/packages/client/modules/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-modules", "description": "Client module system, dual-face: node half composes the __DSH_BOOT__ entry graph (incremental dsh.client scan, bundle route, index tap, webPlugins service); browser half is the lazy-CJS module table the vendored cordis Loader consumes as its internal seam", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/product-analytics/package.json b/packages/client/product-analytics/package.json index 4ee05c7424..c4a8b15545 100644 --- a/packages/client/product-analytics/package.json +++ b/packages/client/product-analytics/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-product-analytics", "description": "Desktop product event collection and authenticated Host reporting", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/resources/package.json b/packages/client/resources/package.json index a6d919e545..fe0f823424 100644 --- a/packages/client/resources/package.json +++ b/packages/client/resources/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-resources", "description": "Unified client resource model: protocol-registered providers turn URL addresses into live values, consumed through the useResource global standard hook", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/script-realm-iframe/package.json b/packages/client/script-realm-iframe/package.json index 2a6dbf4a93..7d9796d7a7 100644 --- a/packages/client/script-realm-iframe/package.json +++ b/packages/client/script-realm-iframe/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-script-realm-iframe", "description": "Optional iframe ScriptRealm provider", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/script-realm/package.json b/packages/client/script-realm/package.json index 711e22e7d8..ece84f9160 100644 --- a/packages/client/script-realm/package.json +++ b/packages/client/script-realm/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-script-realm", "description": "Direct-reference script environments and Cordis-owned provider registration", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/shortcuts/package.json b/packages/client/shortcuts/package.json index 454dc9b4d1..07a942986d 100644 --- a/packages/client/shortcuts/package.json +++ b/packages/client/shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-shortcuts", "description": "Application keyboard command registry and physical-key routing", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/store/package.json b/packages/client/store/package.json index a1946a15ac..f0bda23d05 100644 --- a/packages/client/store/package.json +++ b/packages/client/store/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-store", "description": "React-free observable and snapshot-store contracts with the shared Zustand/Immer engine", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 0d1bce4c42..42817527ce 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -97,7 +97,7 @@ function compiledClientStyle( * 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|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-text-search|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-plugin-market-index\/source$|@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|fs-patch|session|llm|tools|brand|error|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-text-search|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-plugin-market-index\/source$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-api-session-controller\/client\/directories$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/client/ui-account-notifications/package.json b/packages/client/ui-account-notifications/package.json index 4622c47dc0..d5d09452ee 100644 --- a/packages/client/ui-account-notifications/package.json +++ b/packages/client/ui-account-notifications/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-account-notifications", "description": "Display account notifications and refresh localized content", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-agent-preset/package.json b/packages/client/ui-agent-preset/package.json index 25e49e166c..4772b595d6 100644 --- a/packages/client/ui-agent-preset/package.json +++ b/packages/client/ui-agent-preset/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-preset", "description": "Agent-preset surfaces: the default for later sessions, this session's seat, and the composition editor", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-agent-team/package.json b/packages/client/ui-agent-team/package.json index 57d662c94a..40007537dc 100644 --- a/packages/client/ui-agent-team/package.json +++ b/packages/client/ui-agent-team/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-agent-team", "description": "Web shared task board for a subagent tree", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-approval/package.json b/packages/client/ui-approval/package.json index 4de4c4de44..ce7797df05 100644 --- a/packages/client/ui-approval/package.json +++ b/packages/client/ui-approval/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-approval", "description": "Approval composer takeover over the scoped Remote Event waterfall", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-attachment/package.json b/packages/client/ui-attachment/package.json index 8d7d0544f0..d0e06353cf 100644 --- a/packages/client/ui-attachment/package.json +++ b/packages/client/ui-attachment/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-attachment", "description": "Dynamic attachment presentation plugin for conversation input, message-image, and trajectory image slots", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-brand-official/package.json b/packages/client/ui-brand-official/package.json index 85432f41d5..b5b5d59a97 100644 --- a/packages/client/ui-brand-official/package.json +++ b/packages/client/ui-brand-official/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-brand-official", "description": "Official DeepSeek Harness brand artwork and click-triggered home background", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/package.json b/packages/client/ui-chat/package.json index 7d7f19ea05..8409f91e9f 100644 --- a/packages/client/ui-chat/package.json +++ b/packages/client/ui-chat/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-chat", "description": "Chat Conversation target, node definitions, renderers, and details surface", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 3c40e7ef5d..9c54cd1753 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -6,6 +6,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type {} from '@deepseek-ai/dsh-api-remotes/client' import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -290,9 +291,8 @@ export function apply(ctx: Context): void { // its top or at line 400, so the same tab is revealed and told where // to land. openFile: async (path, options) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - const url = fileAddressFor(sessionId, cwd, resolveWorkspacePath(current ?? undefined, path)) + const directory = sessionDirectory(ctx.sessions, sessionId) + const url = fileAddressFor(sessionId, directory, resolveWorkspacePath(directory, path)) if (options?.line === undefined) ctx.sidebarRight.openResource(url) else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() diff --git a/packages/client/ui-chat/src/client/file-path.ts b/packages/client/ui-chat/src/client/file-path.ts index 9c23fdc21d..96d39d5000 100644 --- a/packages/client/ui-chat/src/client/file-path.ts +++ b/packages/client/ui-chat/src/client/file-path.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' -import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' /** * Bind path resolution to the originating Session without capturing its current directory. @@ -11,9 +11,5 @@ import type {} from '@deepseek-ai/dsh-api-session-controller/client' * @returns Resolver using the live working directory, falling back to the workspace root. */ export function sessionFilePath(ctx: Context, sessionId: SessionId): (path: string) => string { - return (path) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - return resolveWorkspacePath(current ?? cwd, path) - } + return path => resolveWorkspacePath(sessionDirectory(ctx.sessions, sessionId), path) } diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 8e9595985c..a680f0bf90 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -326,8 +326,9 @@ describe('Chat inject API', () => { const { injected } = b.chatViewApi(b.rootReference) vi.spyOn(b.runtime.ctx.contextMenus, 'open') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/proj/.agents/worktrees/w') + // The address is relative to the same directory the Host resolves it from. await injected.openFile('src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') expect(injected.resolveFilePath('src/a.ts')).toBe('/proj/.agents/worktrees/w/src/a.ts') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', null) expect(injected.resolveFilePath('file.ts')).toBe('/proj/file.ts') @@ -335,14 +336,14 @@ describe('Chat inject API', () => { // A leading `./` names the same file, so the Sidebar reuses its tab. await injected.openFile('./src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/.agents/worktrees/w/src/a.ts') - await injected.openFile('/proj/src/a.ts') expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') - // Outside the workspace, the address carries the absolute path after the Session id. + // Outside the Session's directory, the address carries the absolute path after the Session id. + await injected.openFile('/proj/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1//proj/src/a.ts') await b.runtime.sessions.setProjection(ROOT, 'workingDirectory', '/elsewhere') await injected.openFile('src/a.ts') - expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1//elsewhere/src/a.ts') + expect(b.sidebarRight.openResource).toHaveBeenLastCalledWith('dsh-resource://file/session/root-1/src/a.ts') await b.runtime.dispose() }) diff --git a/packages/client/ui-commands/package.json b/packages/client/ui-commands/package.json index 9a0a2e3256..61a9dd2738 100644 --- a/packages/client/ui-commands/package.json +++ b/packages/client/ui-commands/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-commands", "description": "Client command surface: global directory cache, '/' source, three command UI kinds, popupSelect registry", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-connector-account/package.json b/packages/client/ui-connector-account/package.json index 6b4c9ac777..d1c87ca5ac 100644 --- a/packages/client/ui-connector-account/package.json +++ b/packages/client/ui-connector-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-connector-account", "description": "Connector account surfaces: the Host registry CLI app plugins and MCP connectors register their accounts with, and the Plugins page section, title tag, activation prompt, and notices it serves over one Remote", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-context-menu/package.json b/packages/client/ui-context-menu/package.json index 8bbbaa13d3..e175007861 100644 --- a/packages/client/ui-context-menu/package.json +++ b/packages/client/ui-context-menu/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-context-menu", "description": "Typed, plugin-extensible context menus with captured targets and shared Web presentation", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 93fb959b52..4ea34ddaa5 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -21,8 +21,8 @@ en: 4a094cd97426ad18 zh: 5faadddb7e2b0a43 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props: - en: 8ad7f24bef08474a - zh: 23accc0d5e837714 + en: 5914222b76430956 + zh: 0eefa0c999bc17a7 /deepseek-ai-dsh-client-ui-conversation/shell-and-standard-props/control-geometry: en: 876be274c65b56d9 zh: c3adbf5a16e0e38e diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 358a1c0d46..87e68b0a19 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -108,7 +108,7 @@ A claimed command is one atomic chip at the start of the draft, and the claim la Workspace selection uses `uiWorkspace.openWorkspace` to prepare the target and commit navigation. Draft content, including structured references, and attachments move in its synchronous preparation callback only while that request is current and no submission is in flight; later navigation, owner disposal, or a submission in flight leaves the original draft in its Session. -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. +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. Every occurrence passes `onWorkspaceSelected`, which decides what a Workspace picked in the Hero does. It receives the Workspace and an `adopt` function, resolves that Workspace's blank Session, shows it in place of the Session shown before, and calls `adopt` with it in the same step while it retains both Sessions; `adopt` moves the draft. The main occurrence opens the blank as the main Session, and an embedded owner may show it itself. A pick the owner no longer wants resolves without calling `adopt`; a failed pick rejects, its owner reports the failure, and the Hero returns to the Workspace it showed. An embedded occurrence may also pass `headline`, which replaces the Hero headline and preview badge. 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 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. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index a493dcb319..8302065571 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -108,7 +108,7 @@ root 作用域的 `conversation.session.header.views.actions` list 有注册项 工作区选择使用 `uiWorkspace.openWorkspace` 准备目标并提交导航。草稿内容(包括结构化引用)和附件仅在该请求仍为当前请求、且没有在途提交时,通过它的同步准备回调搬移;后续导航、所有者释放或在途提交都会把原草稿留在它的 Session 中。 -本包占据 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 提供。 +本包占据 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。每个 occurrence 都传入 `onWorkspaceSelected`,由它决定在 Hero 中选择工作区后做什么。它接收工作区和一个 `adopt` 函数:解析该工作区的空白 Session,用它替换此前显示的 Session,并在同一步、仍保留两个 Session 时以它调用 `adopt`;`adopt` 负责移动草稿。主 occurrence 把这个空白 Session 打开为主 Session,嵌入方可以自己显示它。属主不再需要的选择在不调用 `adopt` 的情况下完成;失败的选择会 reject,由属主报告失败,Hero 回到此前显示的工作区。嵌入式 occurrence 也可以传入 `headline`,用来替换 Hero 的标题与预览徽标。共享正文与 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 在所有平台都保留与 blank Session 相同的 40px 行,因此绑定 Workspace 前后 Hero 输入卡片的高度位置不变;在 macOS 桌面上,这一行同时是窗口拖拽行。侧栏各入口仍遵循自身的数据与执行环境要求。 已开始的 Session 在可用 View 少于两个时使用单行标题栏,仅在渲染标签行时保留其高度。标题与 actions 放不下时,标题区域会裁剪它们,并在 utilities 之前渐隐其末端;utilities 始终完整可见且可点击;标题与 actions slot 中的浮层通过 portal 渲染,不受该裁剪影响。 diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index eabdc3ac5a..73bcc2f2f3 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-conversation", "description": "Target-neutral Conversation assembly, shell, composer, queue, and view navigation", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index b7b32009ed..2ed062b42f 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -22,7 +22,7 @@ import { sessionReferenceRule } from './user-text/session-reference-rule.ts' import { collapseWhitespaceRule, trimWhitespaceRule } from './user-text/whitespace-rules.ts' import type { ViewTab } from './contract/views.ts' import type { - ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, + ComposerBarInjected, ConversationInjected, ConversationSessionHeaderInjected, ConversationShellInjected, ConversationSessionInjected, DraftFileUploads, UserTextInjected, } from './contract/slots.ts' import type { InputNotice } from './contract/input.ts' @@ -112,7 +112,7 @@ function hostPathBridge(): HostPathBridge | undefined { interface WorkspaceNavigation { openSession(sessionId: SessionId): void openWorkspace( - workspaceId: Parameters[0], + workspaceId: Parameters[0], beforeOpen: (sessionId: SessionId) => void, ): Promise } @@ -329,6 +329,10 @@ export function apply(ctx: Context, config: SyncedConfig): v }, }) + const shellInjected: ConversationShellInjected = { + openWorkspace: (workspaceId, adopt) => workspaceNavigation.openWorkspace(workspaceId, adopt), + } + const registerConversationRoot = () => slots.register({ name: 'main.conversation', children: { @@ -359,7 +363,7 @@ export function apply(ctx: Context, config: SyncedConfig): v hooks: { composerBlock: sessionId === undefined ? ABSENT_BLOCK : composerBlocks.storeFor(sessionId), }, - selectWorkspace: workspaceId => workspaceNavigation.openWorkspace(workspaceId, (nextId) => { + moveDraft: (nextId) => { if (sessionId !== undefined && nextId !== sessionId) { const from = inputHub.shell(sessionId) // A draft with a submission in flight stays with the Session that is admitting it. @@ -384,7 +388,7 @@ export function apply(ctx: Context, config: SyncedConfig): v } } } - }), + }, }), }, ConversationContent) @@ -580,7 +584,7 @@ export function apply(ctx: Context, config: SyncedConfig): v yield slots.register({ name: 'main', key: 'conversation', - children: { 'main.conversation': { kind: 'single', scope: 'session-maybe' } }, + children: { 'main.conversation': { kind: 'single', scope: 'session-maybe', inject: shellInjected } }, }, ConversationPanel) yield registerConversationRoot() yield registerConversationContent() diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index f8bbf67c5b..4efcee6601 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -226,7 +226,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { keyProps: { [Id in UserTextId]: { node: UserTextNode } } } /** Conversation shell beneath its root-scoped main-panel entry. */ - 'main.conversation': { kind: 'single'; scope: 'session-maybe' } + 'main.conversation': { kind: 'single'; scope: 'session-maybe'; inject: ConversationShellInjected } /** Strict per-Session Conversation body. */ 'conversation.session': { kind: 'single' @@ -466,10 +466,32 @@ export interface ConvViewOwnerProps { /** Base props of one target-owned Conversation View entry. */ export type ConvViewProps = PropsRuntime<'conversation.view'> -/** Business callbacks injected into the resident Conversation shell. */ +/** + * Moves the draft of the Session a Hero shows to the Session that replaces it. The occurrence owner calls it at most + * once per pick, synchronously with the step that shows the new Session, while it still retains both Sessions. + */ +export type WorkspaceSessionAdopter = (sessionId: SessionId) => void + +/** + * Handles a Workspace the Hero's picker chose: resolves that Workspace's blank Session, shows it in place of the + * Session shown before, and calls `adopt` with it in the same step. A pick the owner no longer wants resolves + * without calling `adopt`; a pick that failed rejects, and the owner reports the failure. + */ +export type WorkspaceSelectedHandler = (workspaceId: WorkspaceId, adopt: WorkspaceSessionAdopter) => Promise + +/** Business callbacks injected into the main Conversation shell. */ +export interface ConversationShellInjected { + /** Open the Workspace's blank Session as the main Session. */ + openWorkspace: WorkspaceSelectedHandler +} + +/** Business callbacks injected into the shared Conversation content. */ export interface ConversationInjected { - /** Connect and open a blank Session in the selected Workspace. */ - selectWorkspace: (workspaceId: WorkspaceId) => Promise + /** + * Move this occurrence's draft text and attachments to another Session. Both Sessions must be retained; a draft + * with a submission in flight stays where it is. + */ + moveDraft: WorkspaceSessionAdopter /** Session-addressed composer block source, or the stable absent source. */ hooks: { composerBlock: ObservableSnapshot } } @@ -683,6 +705,10 @@ export interface ConversationContentInputProps { variant: 'main' | 'embedded' phase: 'settling' | 'hero' | 'active' hero: boolean + /** What a Workspace picked in the Hero does in this occurrence; the main occurrence opens it as the main Session. */ + onWorkspaceSelected: WorkspaceSelectedHandler + /** Text the blank-session Hero shows instead of its default headline and preview badge. */ + headline?: string | undefined } /** Values passed from shared content to its occurrence-selected width controls. */ diff --git a/packages/client/ui-conversation/src/client/index.ts b/packages/client/ui-conversation/src/client/index.ts index b2ce918f76..2aa335183b 100644 --- a/packages/client/ui-conversation/src/client/index.ts +++ b/packages/client/ui-conversation/src/client/index.ts @@ -86,7 +86,7 @@ export type { ComposerBarInjected, ComposerBarOwnerProps, ComposerBarProps, ComposerChainProps, ConversationHeaderActionOwnerProps, ConversationHeaderCornerOwnerProps, ConversationHeaderLineageOwnerProps, ConversationContentInputProps, ConversationContentProps, - ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, + ConversationInjected, ConversationSessionHeaderInjected, ConversationSessionHeaderSlotProps, ConversationShellInjected, ConversationSessionInjected, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionEntry, ConversationViewActionsOwnerProps, ConversationViewsProps, ConversationWidthControlsInputProps, ConversationWidthControlsProps, @@ -94,6 +94,7 @@ export type { HeroAgentPresetOwnerProps, HeroBrandMarkOwnerProps, HeroFrameOwnerProps, InputControlOwnerProps, InputZone, MessageImageLabels, MessageImageLoader, MessageImageSource, MessageImagesContentInput, MessageImagesOwnerProps, UseConversation, UserTextInput, UserTextInjected, UserTextNodeOwnerProps, UserTextNodeProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, UseConversationViews, } from './contract/slots.ts' export type { diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx index 5c5d1149f8..17ab15294e 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationContent.tsx @@ -23,7 +23,7 @@ export function ConversationContent(props: ConversationContentProps) { const { sessionId, phase, hero, useSession, useSessions, useSessionStatus, useWorkspaces, useInput, useComposerBlock, renderSlot, renderSlotChain, - selectWorkspace, t, useFactorySlot, + moveDraft, t, useFactorySlot, } = props const session = useSession(snapshot => snapshot) const Views = useFactorySlot('views', ConversationSessionView) @@ -123,7 +123,7 @@ export function ConversationContent(props: ConversationContentProps) { onPick: (workspaceId) => { setPickerOpen(false) setPendingWorkspaceId(workspaceId) - void selectWorkspace(workspaceId).catch(() => { + void props.onWorkspaceSelected(workspaceId, moveDraft).catch(() => { setPendingWorkspaceId(current => current === workspaceId ? undefined : current) }) }, @@ -164,7 +164,7 @@ export function ConversationContent(props: ConversationContentProps) { const composerBar = (
- {hero && } + {hero && } {hero && heroWorkspaceRow} {zone !== undefined && renderSlot('conversation.input.dock', zone)} {inputBar} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx index dc82d99775..ef0f2ad583 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationMainPanel.tsx @@ -11,7 +11,7 @@ const CONTENT_SLOTS = { widthControls: ConversationWidthControls } * @returns the unchanged root, Header, content, and width-control subtree. */ export function ConversationMainPanel(props: ConversationSlotProps) { - const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot } = props + const { sessionId, useSession, useSessions, useConversation, renderSlot, renderFactorySlot, openWorkspace } = props const session = useSession(s => s) const conversation = useConversation(s => s) const shellPhase = session === undefined || conversation === undefined @@ -41,6 +41,7 @@ export function ConversationMainPanel(props: ConversationSlotProps) { variant: 'main', phase, hero, + onWorkspaceSelected: openWorkspace, }, { slots: CONTENT_SLOTS, })} diff --git a/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx index b46db926da..9adcf1e0ac 100644 --- a/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/EmptyHero.tsx @@ -67,6 +67,8 @@ export interface HeroShellProps { t: HeroTranslate /** Authorized renderer for the hero brand-mark slot. */ renderSlot: ConversationContentProps['renderSlot'] + /** Text shown instead of the default headline and preview badge. */ + headline?: string | undefined /** Overlay content after the stack (modals). */ children?: ReactNode } @@ -129,7 +131,7 @@ function HeroFish({ hovering }: { hovering: boolean }) { * @param props - see {@link HeroShellProps}. * @returns the centered hero element tree. */ -export function HeroShell({ t, renderSlot, children }: HeroShellProps) { +export function HeroShell({ t, renderSlot, headline, children }: HeroShellProps) { const [hovering, setHovering] = useState(false) return (
@@ -152,8 +154,8 @@ export function HeroShell({ t, renderSlot, children }: HeroShellProps) { {/* Own element: keeps the headline text addressable apart from the badge. */} - {t('hero.headline')} - {t('hero.preview')} + {headline ?? t('hero.headline')} + {headline === undefined && {t('hero.preview')}}
diff --git a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx index 701616957f..7634435bea 100644 --- a/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.client.spec.tsx @@ -18,7 +18,7 @@ import { } from '@deepseek-ai/dsh-client-test-runtime' import type { SessionBehaviorOverrides } from '@deepseek-ai/dsh-client-test-runtime' import { - apply, inject, type ComposerBarInjected, type ConversationInjected, + apply, inject, type ComposerBarInjected, type ConversationInjected, type ConversationShellInjected, type ConversationSessionHeaderInjected, type ConversationSessionInjected, type ViewTab, } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -141,6 +141,11 @@ async function bench(renderQuote = false) { sessionId: SessionId | undefined, ) => ConversationInjected)(id) } + /** Pick a Workspace as the main occurrence does: the shell opens it and adopts the draft of the Session shown. */ + const selectWorkspace = (id: SessionId | undefined, workspaceId: WorkspaceId): Promise => { + const shell = runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + return shell.inject.openWorkspace(workspaceId, residentApi(id).moveDraft) + } const headerApi = (id: SessionId) => { const entry = entryOf('conversation.session.header') const instance = runtime.storeOf('conversation.session.header', references.get(id)) as ConversationInstance @@ -161,7 +166,7 @@ async function bench(renderQuote = false) { const viewSource = (id: SessionId): ObservableSnapshot => conversationApi(id).injected.hooks.conversationViews return { - runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, + runtime, feature, slots: runtime.slots, entryOf, conversationApi, headerApi, residentApi, composerApi, selectWorkspace, inputApi, viewSource, sessionFake, connectWorkspace, rootUpload, uploads, rootReference, references, opened, } } @@ -666,7 +671,6 @@ describe('Conversation inject API', () => { it('moves a draft only when Workspace navigation changes Session', async () => { const b = await bench() - const resident = b.residentApi(ROOT) const { state, actions } = b.inputApi(ROOT) actions.setDraft('carry me') expect(b.composerApi(ROOT).addFiles?.([ @@ -675,7 +679,7 @@ describe('Conversation inject API', () => { await vi.waitFor(() => { expect(b.rootUpload).toHaveBeenCalledOnce() }) b.connectWorkspace.mockResolvedValueOnce(ROOT) - await resident.selectWorkspace('workspace-1' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-1' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) expect(state.getSnapshot().draft).toBe('carry me') @@ -690,7 +694,7 @@ describe('Conversation inject API', () => { b.uploads.set(other, targetUpload) await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await resident.selectWorkspace('workspace-2' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-2' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(state.getSnapshot().draft).toBe('') expect(b.inputApi(other).state.getSnapshot().draft).toBe('carry me') @@ -711,7 +715,7 @@ describe('Conversation inject API', () => { const other = 'sending-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-sending' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-sending' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(other) expect(b.inputApi(other).state.getSnapshot().draft).toBe('') expect(state.getSnapshot().draft).toBe('in flight') @@ -732,7 +736,7 @@ describe('Conversation inject API', () => { const other = 'structured-target' as SessionId await b.runtime.sessions.add({ id: other, session: {} }) b.connectWorkspace.mockResolvedValueOnce(other) - await b.residentApi(ROOT).selectWorkspace('workspace-structured' as WorkspaceId) + await b.selectWorkspace(ROOT, 'workspace-structured' as WorkspaceId) expect(b.inputApi(other).state.getSnapshot().draft).toBe(draft.text) expect(b.inputApi(other).state.getSnapshot().occurrences).toMatchObject(draft.references) expect(b.inputApi(ROOT).state.getSnapshot().draft).toBe('') @@ -743,12 +747,12 @@ describe('Conversation inject API', () => { it('supports no-Session navigation and propagates Workspace connection failure', async () => { const b = await bench() b.connectWorkspace.mockResolvedValueOnce(ROOT) - await b.residentApi(undefined).selectWorkspace('workspace-0' as WorkspaceId) + await b.selectWorkspace(undefined, 'workspace-0' as WorkspaceId) expect(b.opened).toHaveBeenCalledWith(ROOT) const opens = b.opened.mock.calls.length b.connectWorkspace.mockRejectedValueOnce(new Error('offline')) - await expect(b.residentApi(ROOT).selectWorkspace('workspace-4' as WorkspaceId)) + await expect(b.selectWorkspace(ROOT, 'workspace-4' as WorkspaceId)) .rejects.toThrow('offline') expect(b.opened).toHaveBeenCalledTimes(opens) await b.runtime.dispose() diff --git a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx index 907b6ec015..5a0adbffb0 100644 --- a/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-wiring.client.spec.tsx @@ -8,7 +8,7 @@ import { import { LocaleRuntime } from '@deepseek-ai/dsh-client-locale/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { apply, inject, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' +import { apply, inject, type ConversationShellInjected, type ViewTab } from '@deepseek-ai/dsh-client-ui-conversation/client' usePinnedBrowserLanguages('zh-CN') @@ -103,8 +103,9 @@ describe('target-neutral Conversation apply wiring', () => { b.runtime.renderRoot() expect(b.runtime.slots.entries('main').map(row => row.options.key)).toEqual(['conversation']) expect(b.runtime.slots.entries('main.conversation')).toHaveLength(1) - expect(b.runtime.slots.spec('main.conversation')) - .toEqual({ kind: 'single', scope: 'session-maybe' }) + const shell = b.runtime.slots.spec('main.conversation') as { inject: ConversationShellInjected } + expect(shell.inject.openWorkspace).toBeTypeOf('function') + expect(shell).toEqual({ kind: 'single', scope: 'session-maybe', inject: shell.inject }) expect(b.runtime.factoryOf('conversation.content').slots) .toMatchObject({ views: { scope: 'session' } }) expect(b.runtime.slots.entries('conversation.session')).toHaveLength(1) diff --git a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx index e3efe6510e..41c2c9ea9a 100644 --- a/packages/client/ui-conversation/tests/skeleton.client.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.client.spec.tsx @@ -32,6 +32,7 @@ import { InputBar } from '../src/client/skeleton/InputBar.tsx' import type { InputBarProps } from '../src/client/skeleton/InputBar.tsx' import type { ComposerBarOwnerProps, ConversationContentInputProps, ConversationContentProps, + WorkspaceSelectedHandler, WorkspaceSessionAdopter, ConversationHeaderLineageOwnerProps, ConversationSessionHeaderSlotProps, ConversationSessionSlotProps, ConversationSlotProps, ConversationViewActionsOwnerProps, ConversationViewsProps, HeroFrameOwnerProps, } from '../src/client/contract/slots.ts' @@ -124,7 +125,7 @@ function sessionSnapshotOf(overrides: Partial = {}): SessionSna function mount( snapshot: SessionSnapshot, workspaceRows: WorkspaceView[] = [{ ...workspace('one'), sessionIds: [SID] }], - retargetWorkspace = vi.fn(async (_workspaceId: WorkspaceId) => {}), + retargetWorkspace = vi.fn(async () => {}), options: { /** Explicit undefined exercises the shell before a Session is selected. */ sessionId?: SessionId | undefined @@ -351,6 +352,7 @@ function mount( : (opts?.fallback ?? null) )) as ConversationContentProps['renderSlotChain'] const SessionProvider: ConversationContentProps['SessionProvider'] = ({ children }) => children + const moveDraft = vi.fn() const renderFactorySlot = ((_name: string, input: ConversationContentInputProps, factoryOptions?: { slots?: Record ReactNode> }) => { @@ -377,7 +379,7 @@ function mount( renderSlot, renderSlotChain, renderFactorySlot, - selectWorkspace: retargetWorkspace, + moveDraft, t, } const useFactorySlot = ((name: string, fallback: (props: never) => ReactNode) => ( @@ -393,6 +395,7 @@ function mount( usePanelInfo: selector => selector({ activePanelId: null }), sessionId, SessionProvider, + openWorkspace: retargetWorkspace, useSession: sessionId === undefined ? () => undefined : useSession, useConversation: sessionId === undefined ? () => undefined : useConversation, useSessions: bindSnapshotSelector(sessions), @@ -409,7 +412,8 @@ function mount( const props: ConversationSlotProps = { ...runtimeProps, renderSlot, renderFactorySlot } const view = render() return { - view, store, wiring, sink, retargetWorkspace, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, open, + view, store, wiring, sink, retargetWorkspace, moveDraft, session, conversation, slotCalls, headerFactory, lineageOwners, seatOwners, + open, pickerOwner: () => pickerOwner, frameOwner: () => frameOwners.at(-1), setPinned, @@ -437,6 +441,13 @@ describe('Hero chrome', () => { expect(brandMarkOwner.className).toBeTypeOf('string') expect(renderSlot.mock.calls[0]?.[2]?.fallback).toBeTruthy() }) + + it('shows an owner headline instead of the default headline and preview badge', () => { + const view = render( null) as never} headline="Review demo #42" />) + expect(view.getByText('Review demo #42')).toBeTruthy() + expect(view.queryByText('Into the Unknown')).toBeNull() + expect(view.queryByText('Preview')).toBeNull() + }) }) describe('ConversationRoot resident composer', () => { @@ -611,7 +622,7 @@ describe('ConversationRoot resident composer', () => { const owner = b.pickerOwner() as { open: boolean; onPick(id: WorkspaceId): void } expect(owner.open).toBe(true) act(() => { owner.onPick(wid('second')) }) - expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second')) + expect(b.retargetWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.getByText('Selected Folder')).toBeTruthy() }) @@ -892,7 +903,7 @@ describe('ConversationRoot resident composer', () => { }) it('rolls the pending workspace label back when switching fails', async () => { - const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) + const selectWorkspace = vi.fn(async () => { throw new Error('connect failed') }) const b = mount( sessionSnapshotOf({ blank: true }), [ @@ -904,7 +915,7 @@ describe('ConversationRoot resident composer', () => { fireEvent.click(b.view.getByRole('button', { name: '选择工作区' })) const owner = b.pickerOwner() as { onPick(id: WorkspaceId): void } await act(async () => { owner.onPick(wid('second')); await Promise.resolve() }) - expect(selectWorkspace).toHaveBeenCalledWith(wid('second')) + expect(selectWorkspace).toHaveBeenCalledWith(wid('second'), b.moveDraft) expect(b.view.queryByText('Selected Folder')).toBeNull() expect(b.view.getByText('one')).toBeTruthy() }) diff --git a/packages/client/ui-deliverables/README.i18n.yaml b/packages/client/ui-deliverables/README.i18n.yaml index 675bcff105..21a04d23f1 100644 --- a/packages/client/ui-deliverables/README.i18n.yaml +++ b/packages/client/ui-deliverables/README.i18n.yaml @@ -21,8 +21,8 @@ en: 5fc6e2d7926f08c0 zh: 18cdb7450add873e /deepseek-ai-dsh-client-ui-deliverables/use-this-package/the-changed-files-card: - en: 4b279e2bddddc083 - zh: a3135393299c935b + en: 95d8ac2bddeaf524 + zh: 463f2c7826c8913d /deepseek-ai-dsh-client-ui-deliverables/use-this-package/the-review-tab: en: 231547659321f3a8 zh: bc5935cdd46ada56 diff --git a/packages/client/ui-deliverables/README.md b/packages/client/ui-deliverables/README.md index 0632574d83..b6b3a12538 100644 --- a/packages/client/ui-deliverables/README.md +++ b/packages/client/ui-deliverables/README.md @@ -42,7 +42,7 @@ The `present` tool row retains its document icon and recorded result across prog Coding Tools must be enabled to show this card or request its summary. Turning the preference off removes the card immediately while explicit delivery cards, inline file links, and recorded workspace changes remain available. -The card renders the summary the Host serves for the turn's latest `workspace/changes` announcement, read once per announcement through the authenticated summary route; while the read is pending, once the Host answers that the summary is gone, or when it lists no file, there is no card. A single changed file shows “Edited” and its basename with its file-type icon, without a file list; its header retains the counts or binary/oversized status and the file’s accessible full path. Multiple files use a code-file icon and a header naming the complete changed-file count and summed added and deleted lines; hovering or focusing it replaces the counts with “Preview in sidebar”. Each row shows one file's display path in the regular UI font with its own monospace counts, “binary” for a binary file, or “too large” for a file the Host did not capture. Rows appear in the recorded display order, so repository files above the working directory and files outside it sort first. Four rows show before a fold; the control reveals every recorded file and, once expanded, collapses the list again from the bottom. Each row opens the turn's review in the right Sidebar on that file, and the header opens it on the first file. Hovering a file row or the single-file header for 500ms opens a scrollable, single-column preview of the comparison, independent of the Sidebar’s view. Its full path uses muted monospace text and scrolls horizontally when needed. File-status notes accompanying code and hunk headers are hidden in the preview; comparisons without hunks retain their status text. Each row exposes the full path as its accessible description. The preview is 48px narrower than the card, inset 24px on each side, and at most 420px high, further constrained by the viewport. The whole preview fades in and out over 100ms. Moving into the preview keeps it open; leaving it, pressing Escape, or activating the row by pointer or keyboard dismisses it. Comparisons load only when the preview opens and share the review tab’s cache and retry states. +The card renders the summary the Host serves for the turn's latest `workspace/changes` announcement, read once per announcement through the authenticated summary route; while the read is pending, once the Host answers that the summary is gone, or when it lists no file, there is no card. The summary names the directory the turn started in; full paths and the review tab's Sidebar file addresses resolve against it, wherever the Session works when they are read. A single changed file shows “Edited” and its basename with its file-type icon, without a file list; its header retains the counts or binary/oversized status and the file’s accessible full path. Multiple files use a code-file icon and a header naming the complete changed-file count and summed added and deleted lines; hovering or focusing it replaces the counts with “Preview in sidebar”. Each row shows one file's display path in the regular UI font with its own monospace counts, “binary” for a binary file, or “too large” for a file the Host did not capture. Rows appear in the recorded display order, so repository files above the working directory and files outside it sort first. Four rows show before a fold; the control reveals every recorded file and, once expanded, collapses the list again from the bottom. Each row opens the turn's review in the right Sidebar on that file, and the header opens it on the first file. Hovering a file row or the single-file header for 500ms opens a scrollable, single-column preview of the comparison, independent of the Sidebar’s view. Its full path uses muted monospace text and scrolls horizontally when needed. File-status notes accompanying code and hunk headers are hidden in the preview; comparisons without hunks retain their status text. Each row exposes the full path as its accessible description. The preview is 48px narrower than the card, inset 24px on each side, and at most 420px high, further constrained by the viewport. The whole preview fades in and out over 100ms. Moving into the preview keeps it open; leaving it, pressing Escape, or activating the row by pointer or keyboard dismisses it. Comparisons load only when the preview opens and share the review tab’s cache and retry states. ### The review tab diff --git a/packages/client/ui-deliverables/README.zh.md b/packages/client/ui-deliverables/README.zh.md index 2951888e72..46a7e18f51 100644 --- a/packages/client/ui-deliverables/README.zh.md +++ b/packages/client/ui-deliverables/README.zh.md @@ -42,7 +42,7 @@ Web 的 `standard`、`ptc` 与 `cordis` preset 提供 `present`,用于声明 只有开启代码工作工具才展示此卡片并请求其摘要。关闭该偏好会立即隐藏卡片,同时保留显式交付卡片、行内文件链接和已记录的工作区改动。 -卡片渲染 Host 为本轮最新一条 `workspace/changes` 宣告提供的摘要,每条宣告通过经过认证的摘要路由读取一次;读取尚未完成、Host 答复摘要已不存在,或摘要没有列出任何文件时,没有卡片。仅改动一个文件时,标题显示“已编辑”和文件名,配合对应的文件类型图标,不展示文件列表;标题保留增删行数或二进制/过大状态,并通过无障碍描述提供完整路径。多个文件使用代码文件图标,标题给出改动文件总数与增删行数合计;鼠标悬停或键盘聚焦时,统计信息替换为“在侧边栏预览”。每一行使用普通界面字体显示文件路径,增删行数保留等宽字体,二进制文件显示“二进制”,Host 没有捕获的文件显示“过大”。行按记录的展示顺序排列,因此仓库内位于工作目录之上的文件与工作区外的文件排在最前。折叠前显示四行;控件展开全部记录文件,展开后从底部收起列表。每一行在右侧 Sidebar 中打开本轮的 review 并选中该文件,标题则在第一个文件上打开它。 在文件行或单文件标题上悬停 500ms 后,会出现可滚动的单列改动浮层,不受 Sidebar 视图设置影响。顶部完整路径使用较浅的等宽字体,超出宽度时可横向滚动。浮层不显示代码旁的文件状态说明和 hunk 头;没有 hunk 的对比仍显示状态文字。每行通过无障碍描述提供完整路径。浮层比卡片窄 48px,左右各内缩 24px,高度最多 420px,并受视口可用空间限制。整个浮层的淡入和淡出各持续 100ms。鼠标移入浮层后保持打开;移出、按 Escape 或通过鼠标和键盘激活文件行会关闭浮层。对比只在浮层打开时加载,与 review tab 共用缓存及重试状态。 +卡片渲染 Host 为本轮最新一条 `workspace/changes` 宣告提供的摘要,每条宣告通过经过认证的摘要路由读取一次;读取尚未完成、Host 答复摘要已不存在,或摘要没有列出任何文件时,没有卡片。摘要给出该轮开始时所在的目录;完整路径与 review tab 的 Sidebar 文件地址都相对它解析,与读取时 Session 所在的目录无关。仅改动一个文件时,标题显示“已编辑”和文件名,配合对应的文件类型图标,不展示文件列表;标题保留增删行数或二进制/过大状态,并通过无障碍描述提供完整路径。多个文件使用代码文件图标,标题给出改动文件总数与增删行数合计;鼠标悬停或键盘聚焦时,统计信息替换为“在侧边栏预览”。每一行使用普通界面字体显示文件路径,增删行数保留等宽字体,二进制文件显示“二进制”,Host 没有捕获的文件显示“过大”。行按记录的展示顺序排列,因此仓库内位于工作目录之上的文件与工作区外的文件排在最前。折叠前显示四行;控件展开全部记录文件,展开后从底部收起列表。每一行在右侧 Sidebar 中打开本轮的 review 并选中该文件,标题则在第一个文件上打开它。 在文件行或单文件标题上悬停 500ms 后,会出现可滚动的单列改动浮层,不受 Sidebar 视图设置影响。顶部完整路径使用较浅的等宽字体,超出宽度时可横向滚动。浮层不显示代码旁的文件状态说明和 hunk 头;没有 hunk 的对比仍显示状态文字。每行通过无障碍描述提供完整路径。浮层比卡片窄 48px,左右各内缩 24px,高度最多 420px,并受视口可用空间限制。整个浮层的淡入和淡出各持续 100ms。鼠标移入浮层后保持打开;移出、按 Escape 或通过鼠标和键盘激活文件行会关闭浮层。对比只在浮层打开时加载,与 review tab 共用缓存及重试状态。 ### review tab diff --git a/packages/client/ui-deliverables/package.json b/packages/client/ui-deliverables/package.json index 3db67ca376..2936cd4d39 100644 --- a/packages/client/ui-deliverables/package.json +++ b/packages/client/ui-deliverables/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-deliverables", "description": "Changed-files card with per-file comparison tabs, delivery cards, and clickable final-response file references for Web", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-deliverables/src/changes.ts b/packages/client/ui-deliverables/src/changes.ts index 2124b41ff1..a7877149a3 100644 --- a/packages/client/ui-deliverables/src/changes.ts +++ b/packages/client/ui-deliverables/src/changes.ts @@ -26,8 +26,11 @@ export const CHANGES_OPEN_ROUTE = CHANGES_OPEN_PATH.slice(1) /** Resource-address prefix of a turn's review tab in the right Sidebar. */ export const CHANGES_REVIEW_ADDRESS = 'dsh-resource://changes-review/session/' -/** The summary fields the route serves; the Host keeps the working directory and snapshot ids to itself. */ -export type ChangesSummary = Pick +/** + * The summary fields the route serves; the Host keeps the snapshot ids to itself. `cwd` is the directory the + * turn started in, which the listed paths are relative to; the Session may work elsewhere by the time it is read. + */ +export type ChangesSummary = Pick /** The comparison the route serves, as the Host computed it. */ export type ChangesDiff = WorkspaceFileDiff @@ -60,12 +63,12 @@ export function isChangedFile(value: unknown): value is WorkspaceChangedFile { /** * Validate a summary read from the summary route. * @param value - decoded JSON. - * @returns whether the value identifies a turn, a complete file list, the total count, and the line totals. + * @returns whether the value identifies a turn, its directory, a complete file list, the total count, and the line totals. */ export function isChangesSummary(value: unknown): value is ChangesSummary { if (!isRecord(value)) return false - const { turn, files, total, added, deleted } = value - return Number.isSafeInteger(turn) && (turn as number) >= 1 && Number.isSafeInteger(total) + const { turn, cwd, files, total, added, deleted } = value + return Number.isSafeInteger(turn) && (turn as number) >= 1 && typeof cwd === 'string' && Number.isSafeInteger(total) && Number.isSafeInteger(added) && Number.isSafeInteger(deleted) && Array.isArray(files) && files.every(isChangedFile) } diff --git a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx index e4500c4a52..3dbd4ad8ec 100644 --- a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx +++ b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx @@ -34,10 +34,9 @@ function Counts({ added, deleted, t }: { added: number; deleted: number } & Prop * @param props - the recorded summary, the review opener, and localized copy. * @returns the card. */ -export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { - /** The served summary with the sequence of the event that announced it. */ - changes: Pick & { seq: number } - cwd: string | undefined +export function ChangedFiles({ changes, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { + /** The served summary with the sequence of the event that announced it; paths resolve against its `cwd`. */ + changes: Pick & { seq: number } /** Open the turn's review on the file at an original summary index. */ openReview: (index: number) => void } & PropsLocale & PreviewProps) { @@ -70,16 +69,17 @@ export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChange {singleFile === undefined ? header : <> } /> - + } {singleFile === undefined &&
    {rows.map((file, index) => (
  • } + display={resolveWorkspacePath(changes.cwd, file.path)} + useChangesDiff={useChangesDiff} loadChangesDiff={loadChangesDiff} t={t} />} anchor={} /> - +
  • ))}
} diff --git a/packages/client/ui-deliverables/src/client/Deliverables.tsx b/packages/client/ui-deliverables/src/client/Deliverables.tsx index 89cfa24afa..22013035ec 100644 --- a/packages/client/ui-deliverables/src/client/Deliverables.tsx +++ b/packages/client/ui-deliverables/src/client/Deliverables.tsx @@ -1,4 +1,5 @@ /** The changed-files card, shown only while the Host serves the turn's summary, and explicitly declared files for a closing turn. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useEffect, useState } from 'react' import type { TurnTailOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import { Button, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' @@ -74,7 +75,7 @@ export function Deliverables({ const { getTriggerProps } = useContextMenu() const [expanded, setExpanded] = useState(false) const showCodeDiff = useShowCodeDiff(value => value) - const cwd = useSessions(state => state.byId[sessionId]?.cwd) + const cwd = useSessions(state => selectSessionDirectory(state, sessionId)) const states = usePresentedOpen(value => value) const host = usePresentedHost(value => value) const announced = showCodeDiff ? matched.changes : null @@ -93,7 +94,7 @@ export function Deliverables({ if (host === null) void reloadPresentedHost() }, [host, reloadPresentedHost]) return <> - {changes !== null && { openChangesReview({ sessionId, seq: changes.seq, turn: changes.turn }, index) }} />} {matched.presented.length > 0 &&
parseChangesReviewAddress(tab.contentId), [tab.contentId]) if (coordinates === undefined) throw new Error(`ui-deliverables: not a review address "${tab.contentId}"`) const { seq } = coordinates - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const summary = useChangesSummary(value => value[changesSummaryUrl(sessionId, seq)]) const state = useStore(store => store.byTab[tab.id]) const host = usePresentedHost(value => value) @@ -95,6 +96,8 @@ export function ReviewTab({ if (host === null) void reloadPresentedHost() }, [host, reloadPresentedHost]) const files = typeof summary === 'object' ? summary.files : [] + // Listed paths are relative to the directory the turn started in, which the Session may have left since. + const turnCwd = typeof summary === 'object' ? summary.cwd : undefined // A navigated index the summary does not list falls back to the first file. const index = state !== undefined && files[state.index] !== undefined ? state.index : 0 const file = files[index] @@ -142,7 +145,9 @@ export function ReviewTab({ {file !== undefined && + onClick={() => { tab.actions.openResource(fileAddressFor(sessionId, cwd, resolveWorkspacePath(turnCwd, file.path))) }}> + + } {file !== undefined && renderSlot('deliverables.review.file.actions', { actionUrl: changedFileUrl(sessionId, seq, index), available: native, diff --git a/packages/client/ui-deliverables/src/present-open.ts b/packages/client/ui-deliverables/src/present-open.ts index 6023625644..4ad451db96 100644 --- a/packages/client/ui-deliverables/src/present-open.ts +++ b/packages/client/ui-deliverables/src/present-open.ts @@ -112,14 +112,13 @@ async function handlePresentOpen(ctx: Context, request: Request): Promise select(useSyncExternalStore(subscribe, getSnapshot))} />) return { view, diffs, loadChangesDiff, openReview, row: screen.getByRole('button', { name: 'View changes to main.ts' }) } diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 4e809d6289..f0295fa626 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -85,14 +85,14 @@ async function fixture() { } describe('change summary route', () => { - it('serves the Host-held summary without its working directory, and 404 once it is gone', async () => { - const { read, data, summary } = await fixture() + it('serves the Host-held summary with the directory its paths are relative to, and 404 once it is gone', async () => { + const { read, data, summary, cwd } = await fixture() expect(changesSummaryUrl(brandString('owner'), 9)).toBe('api/changes.summary?sessionId=owner&seq=9') const response = await read() expect(response.status).toBe(200) expect(response.headers.get('cache-control')).toBe('no-store') - // The working directory and snapshot ids stay on the Host. - expect(await response.json()).toEqual({ turn: 1, total: 3, added: 3, deleted: 0, files: data.files }) + // The snapshot ids stay on the Host. + expect(await response.json()).toEqual({ turn: 1, cwd, total: 3, added: 3, deleted: 0, files: data.files }) expect((await read('?sessionId=owner&seq=8')).status).toBe(404) expect((await read('?sessionId=other&seq=9')).status).toBe(404) for (const bad of ['', '?seq=9', '?sessionId=owner', '?sessionId=owner&seq=x', '?sessionId=owner&seq=1.5']) { @@ -193,14 +193,15 @@ describe('changed files native open route', () => { expect(isChangedFile({ path: 'a', display: '', added: 1, deleted: 2 })).toBe(false) expect(isChangedFile({ path: 'a', display: 'a', added: 1.5, deleted: 2 })).toBe(false) expect(isChangedFile([])).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 0, files: [] })).toBe(true) - expect(isChangesSummary({ turn: 1, total: 1, added: 1, deleted: 0, files: [{ path: 'a', display: 'a', added: 1, deleted: 0 }] })).toBe(true) - expect(isChangesSummary({ turn: '1', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 0, total: 0, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 1.5, added: 0, deleted: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 'x', files: [] })).toBe(false) - expect(isChangesSummary({ turn: 1, total: 1, added: 1, deleted: 0, files: [{ path: 'a' }] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(true) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1, added: 1, deleted: 0, files: [{ path: 'a', display: 'a', added: 1, deleted: 0 }] })).toBe(true) + expect(isChangesSummary({ turn: '1', cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 0, cwd: '/w', total: 0, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1.5, added: 0, deleted: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 0, added: 0, deleted: 'x', files: [] })).toBe(false) + expect(isChangesSummary({ turn: 1, cwd: '/w', total: 1, added: 1, deleted: 0, files: [{ path: 'a' }] })).toBe(false) + expect(isChangesSummary({ turn: 1, total: 0, added: 0, deleted: 0, files: [] })).toBe(false) expect(isChangesSummary([])).toBe(false) expect(isChangesEvent({ turn: 1 })).toBe(true) expect(isChangesEvent({ turn: 1, extra: true })).toBe(true) diff --git a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx index b9a141b1b7..d30f484942 100644 --- a/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/deliverables.client.spec.tsx @@ -596,7 +596,7 @@ describe('ChangedFiles card', () => { changedFile('~/.zshrc', 0, 0, { binary: true, path: '/home/u/.zshrc' }), ] const changes = { seq: 5 } - const served: ChangesSummary = { turn: 1, files, total: 11, added: 1232, deleted: 326 } + const served: ChangesSummary = { turn: 1, cwd: '/workspace', files, total: 11, added: 1232, deleted: 326 } /** A store already holding the summary the Host served for the announced sequence. */ function servedStore(summary: ChangesSummary = served, seq = 5) { @@ -616,7 +616,7 @@ describe('ChangedFiles card', () => { } it.each([en, zh])('shows one edited filename without a list and opens its review', (locale) => { - const single = servedStore({ turn: 1, files: [changedFile('src/example.scss', 3, 1)], total: 1, added: 3, deleted: 1 }) + const single = servedStore({ turn: 1, cwd: '/workspace', files: [changedFile('src/example.scss', 3, 1)], total: 1, added: 3, deleted: 1 }) const { props, view } = renderCard(new PresentedOpenController(), locale, { changes, presented: [] }, single) const t = makeTranslate(locale) const card = view.container.querySelector('[data-changed-files]')! @@ -631,7 +631,7 @@ describe('ChangedFiles card', () => { }) it.each(['binary', 'oversized'] as const)('keeps the %s status in a single-file header', (flag) => { - const single = servedStore({ turn: 1, files: [changedFile('asset.bin', 0, 0, { [flag]: true })], total: 1, added: 0, deleted: 0 }) + const single = servedStore({ turn: 1, cwd: '/workspace', files: [changedFile('asset.bin', 0, 0, { [flag]: true })], total: 1, added: 0, deleted: 0 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [] }, single) expect(view.getByText(en[`changes.${flag}`])).toBeTruthy() expect(view.queryByText('+0')).toBeNull() @@ -656,7 +656,7 @@ describe('ChangedFiles card', () => { const fetchMock = vi.fn(async (input: string | URL | Request) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url if (url.endsWith('seq=5')) return Response.json(served) - if (url.endsWith('seq=6')) return Response.json({ turn: 1, files: [], total: 0, added: 0, deleted: 0 }) + if (url.endsWith('seq=6')) return Response.json({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) return new Response('gone', { status: 404 }) }) vi.stubGlobal('fetch', fetchMock) @@ -690,7 +690,7 @@ describe('ChangedFiles card', () => { }) it('sums the header from the Host totals, not from the capped list', () => { - const capped = servedStore({ turn: 1, files: files.slice(0, 1), total: 2, added: 50, deleted: 20 }) + const capped = servedStore({ turn: 1, cwd: '/workspace', files: files.slice(0, 1), total: 2, added: 50, deleted: 20 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [] as never[] }, capped) expect(view.getByText('Edited 2 files')).toBeTruthy() expect(view.getByText('+50')).toBeTruthy() @@ -809,7 +809,7 @@ describe('ChangedFiles card', () => { }) it('renders without a fold for three files or fewer and beside delivery cards', () => { - const short = servedStore({ turn: 1, files: [...files.slice(0, 1), changedFile('huge.bin', 0, 0, { oversized: true })], total: 2, added: 185, deleted: 43 }) + const short = servedStore({ turn: 1, cwd: '/workspace', files: [...files.slice(0, 1), changedFile('huge.bin', 0, 0, { oversized: true })], total: 2, added: 185, deleted: 43 }) const { view } = renderCard(new PresentedOpenController(), en, { changes, presented: [{ path: 'report.pdf', seq: 6, index: 0 }] as never[] }, short) expect(view.getByText('Edited 2 files')).toBeTruthy() expect(view.getByText('too large')).toBeTruthy() @@ -964,9 +964,9 @@ describe('plugin registration', () => { fetcher.mockResolvedValueOnce(Response.json({ name: 'desktop', available: true, fileManager: 'finder' })) await face.reloadPresentedHost() expect(face.hooks.presentedHost.getSnapshot()).toMatchObject({ name: 'desktop' }) - fetcher.mockResolvedValueOnce(Response.json({ turn: 1, files: [], total: 0, added: 0, deleted: 0 })) + fetcher.mockResolvedValueOnce(Response.json({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 })) await face.loadChangesSummary(brandString('child-session'), 5) - expect(face.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=5']).toEqual({ turn: 1, files: [], total: 0, added: 0, deleted: 0 }) + expect(face.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=5']).toEqual({ turn: 1, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) ctx.emit('connection/reset') expect(face.hooks.presentedHost.getSnapshot()).toBeNull() // The replaced connection may reach a Host that no longer serves the summaries read so far. @@ -979,9 +979,9 @@ describe('plugin registration', () => { expect(openResource).toHaveBeenCalledWith('dsh-resource://changes-review/session/child-session/5/3', { params: { index: 1 } }) expect((registered as { title(address: string): string }).title('dsh-resource://changes-review/session/child-session/5/3')).toBe('Review · turn 3') const tabFace: ReviewInjected = tabEntry!.inject!(brandString('child-session') as never) as Record & ReviewInjected - fetcher.mockResolvedValueOnce(Response.json({ turn: 3, files: [], total: 0, added: 0, deleted: 0 })) + fetcher.mockResolvedValueOnce(Response.json({ turn: 3, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 })) await tabFace.loadChangesSummary(brandString('child-session'), 6) - expect(tabFace.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=6']).toEqual({ turn: 3, files: [], total: 0, added: 0, deleted: 0 }) + expect(tabFace.hooks.changesSummary.getSnapshot()['api/changes.summary?sessionId=child-session&seq=6']).toEqual({ turn: 3, cwd: '/workspace', files: [], total: 0, added: 0, deleted: 0 }) fetcher.mockResolvedValueOnce(Response.json({ kind: 'binary', path: 'src/a.ts', display: 'src/a.ts' })) await face.loadChangesDiff(brandString('child-session'), 5, 1) expect(face.hooks.changesDiff).toBe(tabFace.hooks.changesDiff) @@ -1098,7 +1098,7 @@ it.each([{}, { turn: '1', callId: 'bad', files: [] }, const owner = tailOwner(deliverablesOf(value), 6) const matched = selectDeliverables(owner)! const summaries = new ChangesSummaryStore() - summaries.state.set({ [changesSummaryUrl(brandString('session'), 5)]: { turn: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 0 }], total: 1, added: 1, deleted: 0 } }) + summaries.state.set({ [changesSummaryUrl(brandString('session'), 5)]: { turn: 1, cwd: '/workspace', files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 0 }], total: 1, added: 1, deleted: 0 } }) const view = render(('session')} t={makeTranslate(en)} />) expect(view.getByText('Edited a.txt')).toBeTruthy() expect(view.queryByText('Deliverables')).toBeNull() diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index e30c18936b..3e94bc81a2 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -33,7 +33,9 @@ async function fixture() { cleanups.push(() => ctx.fiber.dispose()) const session: { cwd?: string } = { cwd } await ctx.plugin(LocalFileSystem, { cwd }) - ctx.provide('sandboxPolicy', { workspaceRoot: cwd } as never) + // The workspace scope asks the policy for a live Session's root; this one applies the header directory, then the deployment root. + const resolvePolicy = ({ session: live }: { session: { header: { cwd?: string } } }) => ({ mode: 'read-only', workspaceRoot: live.header.cwd ?? cwd }) + ctx.provide('sandboxPolicy', { workspaceRoot: cwd, resolve: resolvePolicy } as never) await ctx.plugin({ inject: ['fs', 'sandboxPolicy'], apply: (scope) => { @@ -53,6 +55,9 @@ async function fixture() { return { session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'present-call', files: [file] } } as SessionEvent } }) ctx.provide('sessionQuery', { readEvent } as never) + // Every viewed Session is live with that header, so the workspace scope reads its original project without an Agent. + const live = vi.fn((id: SessionId) => ({ id, header: session })) + ctx.provide('sessions', { get: live } as never) const opener = vi.fn(async (_request: { path: string; action?: 'reveal' }, _signal: AbortSignal) => ({ opened: true as const })) const applications = vi.fn(async () => [{ id: 'player', name: 'Player', default: true, icon: null }]) ctx.provide('sessionController', { workspacePathApplications: applications, resolveAgent, openWorkspacePath: opener, workspaceDesktop: () => ({ name: 'desktop', available: true, fileManager: 'finder' }) } as never) @@ -65,7 +70,8 @@ async function fixture() { `http://localhost${PRESENT_OPEN_PATH}${query}`, { method: 'POST', signal: signal ?? null }, ), connection.browserPeer) return { - browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, resolveAgent, + browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, + resolveAgent, live, } } @@ -239,6 +245,14 @@ it('opens a viewed child Session without activating an Agent', async () => { expect(resolveAgent).not.toHaveBeenCalled() }) +it('refuses a presented file whose Session is neither live nor stored once its event was read', async () => { + const { session, readEvent, live, open, opener } = await fixture() + readEvent.mockResolvedValueOnce({ session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'gone', files: [{ path: '日记模板.docx' }] } } as SessionEvent }) + live.mockReturnValueOnce(undefined as never) + expect((await open('?sessionId=gone&seq=7&index=0')).status).toBe(404) + expect(opener).not.toHaveBeenCalled() +}) + it('uses the deployment workspace root when the viewed Session has no cwd', async () => { const { session, open, cwd, file, opener } = await fixture() delete session.cwd diff --git a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx index 04543c2a6f..bbc5514a7f 100644 --- a/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/review-tab.client.spec.tsx @@ -38,7 +38,7 @@ const ADDRESS = changesReviewAddress(COORDINATES) const SUMMARY_URL = changesSummaryUrl(SESSION, 5) const summary: ChangesSummary = { - turn: 2, total: 4, added: 4, deleted: 2, + turn: 2, cwd: '/work/app', total: 4, added: 4, deleted: 2, files: [ { path: 'src/app/main.ts', display: 'src/app/main.ts', added: 3, deleted: 1 }, { path: '/tmp/out/big.bin', display: '~/out/big.bin', added: 0, deleted: 0, oversized: true }, @@ -331,6 +331,23 @@ describe('ReviewTab', () => { expect(view.getByText('after')).toBeTruthy() }) + it('opens a file against the directory its turn started in after the Session moved', () => { + const summaries = new ChangesSummaryStore() + summaries.state.set({ [SUMMARY_URL]: { ...summary, files: [ + { path: 'notes.txt', display: 'notes.txt', added: 1, deleted: 1 }, + { path: '.agents/worktrees/topic/src/a.ts', display: '.agents/worktrees/topic/src/a.ts', added: 1, deleted: 0 }, + ] } }) + const moved = '/work/app/.agents/worktrees/topic' + const outside = mount({ summaries, cwd: moved, params: { index: 0 } }) + fireEvent.click(outside.view.getByRole('button', { name: 'Open notes.txt in sidebar' })) + // The Session's directory no longer contains the file, so its address carries the absolute path. + expect(outside.tabActions.openResource).toHaveBeenCalledWith(fileAddressFor(SESSION, moved, '/work/app/notes.txt')) + outside.view.unmount() + const inside = mount({ summaries, cwd: moved, params: { index: 1 } }) + fireEvent.click(inside.view.getByRole('button', { name: 'Open .agents/worktrees/topic/src/a.ts in sidebar' })) + expect(inside.tabActions.openResource).toHaveBeenCalledWith(fileAddressFor(SESSION, moved, 'src/a.ts')) + }) + it('opens the whole file in the sidebar and the native open only with a desktop', () => { const summaries = new ChangesSummaryStore() summaries.state.set({ [SUMMARY_URL]: summary }) diff --git a/packages/client/ui-directory-picker-browse/package.json b/packages/client/ui-directory-picker-browse/package.json index 0ac768e2f1..48d7be33ec 100644 --- a/packages/client/ui-directory-picker-browse/package.json +++ b/packages/client/ui-directory-picker-browse/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-browse", "description": "In-app directory browsing surface: the workspace directory-flow owner rendering the host's listing and creation primitives", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-directory-picker-native/package.json b/packages/client/ui-directory-picker-native/package.json index 9008103bf8..27230a7f4c 100644 --- a/packages/client/ui-directory-picker-native/package.json +++ b/packages/client/ui-directory-picker-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-directory-picker-native", "description": "Native directory-picker surface: the renderless workspace directory-flow occupant driving the local Desktop or Host OS chooser", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-dockkit/package.json b/packages/client/ui-dockkit/package.json index 0748e9a937..4a90eac624 100644 --- a/packages/client/ui-dockkit/package.json +++ b/packages/client/ui-dockkit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-dockkit", "description": "Docking layout kit: split-tree engine with invertible operations, and the React components that render and drive it (zero cordis)", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-entry-customization/package.json b/packages/client/ui-entry-customization/package.json index 74a782600f..1ea121bf38 100644 --- a/packages/client/ui-entry-customization/package.json +++ b/packages/client/ui-entry-customization/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-client-ui-entry-customization", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "description": "Customize plugin entries in the left sidebar, conversation views, and right sidebar, and quickly create new plugins.", "publishConfig": { "access": "public" }, "repository": { diff --git a/packages/client/ui-file-actions/package.json b/packages/client/ui-file-actions/package.json index af0aa02f72..e1d9354154 100644 --- a/packages/client/ui-file-actions/package.json +++ b/packages/client/ui-file-actions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-file-actions", "description": "Original-file saving and image clipboard actions for Web and Desktop", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-file-drag/package.json b/packages/client/ui-file-drag/package.json index c22402cb63..8bb94445b5 100644 --- a/packages/client/ui-file-drag/package.json +++ b/packages/client/ui-file-drag/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-file-drag", "description": "Application-owned file drag transfers and localized failure feedback", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-goal/package.json b/packages/client/ui-goal/package.json index 9bc03d5a0b..96cd613c25 100644 --- a/packages/client/ui-goal/package.json +++ b/packages/client/ui-goal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-goal", "description": "Session goal surface: GoalBar docked above the composer, read from the goal session projection", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-input-trigger/package.json b/packages/client/ui-input-trigger/package.json index f49eab1f10..3a2a64688c 100644 --- a/packages/client/ui-input-trigger/package.json +++ b/packages/client/ui-input-trigger/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-input-trigger", "description": "Input trigger pipeline: '/' and '@' detection, candidate menu, pick routing to registered sources", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-jobs/package.json b/packages/client/ui-jobs/package.json index eaacd0b2d6..3bfe852704 100644 --- a/packages/client/ui-jobs/package.json +++ b/packages/client/ui-jobs/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-jobs", "description": "Session panel background-job list with on-demand streaming record panels", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", diff --git a/packages/client/ui-layout/package.json b/packages/client/ui-layout/package.json index 4e65d01264..5340f9cf54 100644 --- a/packages/client/ui-layout/package.json +++ b/packages/client/ui-layout/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-layout", "description": "Shell plugin: three-column AppFrame with drag handles, ctx.layout viewing-state service (navigation + panels)", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-message-feedback/package.json b/packages/client/ui-message-feedback/package.json index 82e50698b1..8d1ba31801 100644 --- a/packages/client/ui-message-feedback/package.json +++ b/packages/client/ui-message-feedback/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-message-feedback", "description": "The Web feedback surface: per-message Like/Dislike in the assistant-message action strip and the feedback dialog behind both ratings and /feedback, backed by the messageFeedback and sessionFeedback Host Remotes", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-model-selection/package.json b/packages/client/ui-model-selection/package.json index 84dcf1e19b..81b193f270 100644 --- a/packages/client/ui-model-selection/package.json +++ b/packages/client/ui-model-selection/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-model-selection", "description": "Model selection over the shared model catalog, Session projection, and session.selectModel", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-open-in-app/package.json b/packages/client/ui-open-in-app/package.json index 9d7f228a14..b543754dea 100644 --- a/packages/client/ui-open-in-app/package.json +++ b/packages/client/ui-open-in-app/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-open-in-app", "description": "Session application submenus and native opening controls for directories and previewed files", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index aa69108391..7b8ec935dd 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -11,6 +11,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppController } from './controller.ts' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' @@ -89,7 +90,7 @@ export function registerContextMenus( id: 'open-in-app.directory', target: 'directory', order: 100, resolve: async ({ sessionId, path }, signal) => { await paths.load() - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) const absolutePath = resolveWorkspacePath(cwd, path) signal.throwIfAborted() return [ @@ -114,7 +115,7 @@ export function registerContextMenus( : apps === undefined ? () => open(absolutePath, 'open') : undefined // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { destination, ...(line === undefined ? {} : { params: { line } }), }) @@ -129,7 +130,7 @@ export function registerContextMenus( disabled: openApplication === undefined, ...openApplication === undefined ? {} : { run: openApplication } }, { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) ctx.contextMenus.notify(t('menu.copied'), true) } }, diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index 84bdc9168e..c857f48779 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -18,6 +18,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-files/client' import type {} from '@deepseek-ai/dsh-api-gateway/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type {} from '@deepseek-ai/dsh-api-session-controller/remote' import { OPEN_IN_APP_ICON_PREFIX_ROUTE } from '@deepseek-ai/dsh-host-open-in-app/shared' import { OpenInAppController } from './controller.ts' @@ -76,10 +77,11 @@ export function apply(ctx: ClientContext): void { }, OpenInAppToast)) const target = () => { if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return undefined - const session = Object.values(ctx.sessions.list.getSnapshot().byId) - .find(row => (row.retainedBy.mainView ?? 0) > 0) + const list = ctx.sessions.list.getSnapshot() + const session = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0) + const root = session === undefined ? undefined : selectSessionDirectory(list, session.id) const appId = controller.currentApp() - return session?.cwd && appId !== undefined ? { appId, path: session.cwd } : undefined + return root && appId !== undefined ? { appId, path: root } : undefined } ctx.effect(() => ctx.shortcuts.register({ id: 'workspace.openLocal' as ShortcutCommandId, label: () => t('open.tooltip'), aliases: ['open workspace locally', 'open in app'], diff --git a/packages/client/ui-open-in-app/src/client/session-open-with.ts b/packages/client/ui-open-in-app/src/client/session-open-with.ts index 7119958e9e..854ce2a523 100644 --- a/packages/client/ui-open-in-app/src/client/session-open-with.ts +++ b/packages/client/ui-open-in-app/src/client/session-open-with.ts @@ -2,6 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ContextMenuTargetMap, MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { OPEN_IN_APP_ICON_PREFIX_ROUTE } from '@deepseek-ai/dsh-host-open-in-app/shared' import { APP_LABEL_KEY } from './applications.ts' import type { OpenInAppController } from './controller.ts' @@ -21,7 +22,8 @@ export function registerSessionOpenWith( report: OpenInAppToastSource['report'], ): void { const resolve = ({ sessionId }: ContextMenuTargetMap['sessionHeader']): readonly MenuAction[] => { - const directory = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + // The Session menu opens the checkout the Session works in, not the directory it was created in. + const directory = selectSessionDirectory(ctx.sessions.list.getSnapshot(), sessionId) const applications = (controller.apps.getSnapshot() ?? []).flatMap((id) => { const key = APP_LABEL_KEY[id] return key === undefined ? [] : [{ id, name: t(key) }] diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index dabe99a530..a0adda272b 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -47,7 +47,7 @@ async function boot() { .mockResolvedValue({ status: 'saved', path: '/downloads/file.svg' }) const copyImage = vi.fn<(source: FileActionSource) => Promise>().mockResolvedValue() const fileActions = { save, copyImage, canSaveAs: true } - const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } } }) + const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) const sidebar = { openResourceIn: vi.fn(), openTabIn: vi.fn() } const browserTab = vi.fn(() => ({})) const directoryFetch = vi.fn(async () => new Response(JSON.stringify({ apps: ['vscode', 'finder'] }))) @@ -406,10 +406,10 @@ it('offers only folder reveal and path copy, retaining the captured directory', const menu = await h.resolve(target) expect(menu.source.getSnapshot().map(item => item.id)).toEqual(['open-in-app.directory/reveal', 'open-in-app.directory/copyPath']) expect(h.remote.workspaceFiles.stat).not.toHaveBeenCalled() - h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } }, projectionsBySession: {} }) menu.select('open-in-app.directory/reveal') await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/src', action: 'reveal' }) }) - h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) await h.choose(target, 'open-in-app.directory/copyPath') expect(h.writeText).toHaveBeenLastCalledWith('/workspace/src') h.paths.desktop.set(false) diff --git a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts index 1f2a1a2704..0bd58224cd 100644 --- a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts @@ -35,7 +35,7 @@ it('offers image actions on file targets, copies absolute paths, and keeps save } } ctx.provide('remote', remote as never) ctx.provide('contextMenus', { register: registry.register.bind(registry), notify } as never) - ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } } }) } as never) + ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } }, projectionsBySession: {} }) } as never) ctx.provide('fileActions', { save, copyImage: copy, canSaveAs: true } as never) const paths = new OpenInAppPathController(remote) const directories = new OpenInAppController() diff --git a/packages/client/ui-permission-presets/package.json b/packages/client/ui-permission-presets/package.json index 43647850f1..cc7b76c5f4 100644 --- a/packages/client/ui-permission-presets/package.json +++ b/packages/client/ui-permission-presets/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-permission-presets", "description": "Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plan/package.json b/packages/client/ui-plan/package.json index 4c225e9ad4..3be9696a78 100644 --- a/packages/client/ui-plan/package.json +++ b/packages/client/ui-plan/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plan", "description": "Plan mode controls, persistent transcript plan cards, and sidebar Markdown previews", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-manager/README.i18n.yaml b/packages/client/ui-plugin-manager/README.i18n.yaml index 7504ba8b5b..f196cffcd5 100644 --- a/packages/client/ui-plugin-manager/README.i18n.yaml +++ b/packages/client/ui-plugin-manager/README.i18n.yaml @@ -24,8 +24,8 @@ en: 2a44a378364912db zh: 8c514ce17469747f /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-a-bundle: - en: 902e109f3315d1ca - zh: d508c17983d1fe2e + en: 76b0e8af85db92f7 + zh: 3bb566e8f3c6c80b /deepseek-ai-dsh-client-ui-plugin-manager/use-this-package/switching-one-row-of-a-bundle: en: 2c338faf806bd469 zh: fe947a1b27382e5d diff --git a/packages/client/ui-plugin-manager/README.md b/packages/client/ui-plugin-manager/README.md index 71c0508a0f..0b4fe9f29f 100644 --- a/packages/client/ui-plugin-manager/README.md +++ b/packages/client/ui-plugin-manager/README.md @@ -80,7 +80,7 @@ After the checks, the list toolbar says how many plugins can be updated, that al ### Switching a bundle -A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes built-in profile bundles and the persistent-terminal bundle from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete. +A bundle's page shows its full package name under the title. Its **Source** section, after the rows, names the spec that installs it elsewhere, as `pnpm add` accepts it, or **Built in** for an official bundle the installation ships, then its current version. A bundle's switch changes its layer selection. A displayed detail document stays visible while a profile change triggers a fresh read; the result replaces it when ready. While the Host applies the change, the switch stays disabled and a spinner appears beside it; the action area permanently reserves 22px to the left of the switch. A persistent status region announces the pending change to screen readers. A profile with HMR recomposes before the operation completes; one without HMR, and a bundle a higher layer overrides, say so in a toast. A bundle the Host cannot read carries a problem tag and its reason on its page and cannot be switched on; one that provides the management components stays locked. A selected bundle whose layer the Host skipped, reported as an error with none of its rows carrying a live entry, keeps its switch on and carries a not-running tag instead, and its card states the reason without the requirement list. A bundle's page omits the component list when the Host reports an error and no rows, since the Host may not have read its patch. The Host answers with error codes, which the page's dictionary words; pnpm's and the Loader's own diagnostics are shown as they are. The page excludes bundles in [`HIDDEN_BUNDLES`](../../util/official-bundles/README.md#plugin-manager-lists) from cards and detail pages, regardless of activation, dependency declarations, or Host errors. Hiding a bundle preserves its Host availability and activation. The Host inventory remains complete. ### Switching one row of a bundle diff --git a/packages/client/ui-plugin-manager/README.zh.md b/packages/client/ui-plugin-manager/README.zh.md index 325815001f..ca9e0b4fb3 100644 --- a/packages/client/ui-plugin-manager/README.zh.md +++ b/packages/client/ui-plugin-manager/README.zh.md @@ -80,7 +80,7 @@ Host 将网络失败或超时归因于 GitHub 地址,且提供 npmmirror 时 ### 切换一个组合包 -组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除内置 profile 组合包和持久终端组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据。 +组合包页面在标题下方显示完整包名。组件列表之后的「来源信息」给出在别处安装它所需的 spec(`pnpm add` 接受的形式),安装随附的官方组合包显示「内置」,随后是当前版本。组合包开关改变其层选择。profile 变更触发重新读取时,已显示的详情文档保持可见,直到新结果返回。Host 应用更改期间,开关保持禁用,旁边显示旋转指示器;操作区在开关左侧固定预留 22px。常驻状态区域向屏幕阅读器播报进行中的更改。启用了 HMR 的 profile 在操作完成前重组;没有 HMR 的 profile,以及被更高层覆盖的组合包,会以 toast 说明。Host 读不了的组合包带异常标签,其页面给出原因,且不能打开;提供管理组件的组合包保持锁定。已选中组合包的层被 Host 跳过时(Host 将其报告为错误,且该组合包没有带存活条目的行),该组合包的开关保持打开,改带未运行标签,其卡片给出原因,但不列出未满足的版本要求。Host 报告错误且没有报告任何行时,组合包页面不显示组件列表,因为 Host 可能未读取其 patch。Host 以错误码作答,由页面字典措辞;pnpm 与 Loader 自己的诊断原样显示。页面从卡片和详情页中排除 [`HIDDEN_BUNDLES`](../../util/official-bundles/README.zh.md#plugin-manager-lists) 中的组合包,无论其启用状态、依赖声明或 Host 异常如何。隐藏组合包保留其在 Host 中的可用性和启用状态。Host 清单仍保留完整数据。 ### 切换组合包里的一行 diff --git a/packages/client/ui-plugin-manager/package.json b/packages/client/ui-plugin-manager/package.json index 73c728f858..5888d7fa84 100644 --- a/packages/client/ui-plugin-manager/package.json +++ b/packages/client/ui-plugin-manager/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-manager", "description": "Plugin management for the dsh web client: the sidebar Plugins panel installs, enables, disables, retries, and composes installed plugin packages", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx index 8d5dbec36c..85235c8671 100644 --- a/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx +++ b/packages/client/ui-plugin-manager/src/client/PluginManagerPage.tsx @@ -1624,8 +1624,6 @@ export function PluginManagerPage(props: PluginManagerPageProps): ReactNode { }, [highlight, clearHighlight]) const noticeLine = state.notice === null || state.notice.kind === 'refresh-failed' ? null : noticeText(state.notice, t) - // The page omits profile bundles and persistent terminals. Other installed or offered bundles and - // unreadable selections remain manageable. const listed = state.packages.filter(pkg => !HIDDEN_BUNDLES.has(pkg.name) && (pkg.listedByDefault !== false || pkg.enabled || pkg.installed || rowsRunning(pkg)) && (pkg.installed || pkg.official || pkg.error !== undefined)) 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 c75dac7440..babc8e04ff 100644 --- a/packages/client/ui-plugin-manager/tests/components.client.spec.tsx +++ b/packages/client/ui-plugin-manager/tests/components.client.spec.tsx @@ -794,7 +794,7 @@ describe('PluginManagerPage', () => { expect(locked.getAttribute('title')).toBe(en.reasonManagementRequired) }) - it('omits profile and persistent-terminal bundles while retaining other optional and third-party bundles', () => { + it('omits hidden bundles while retaining other optional and third-party bundles', () => { renderTab({ packages: [ ...[ @@ -804,7 +804,7 @@ describe('PluginManagerPage', () => { '@deepseek-ai/dsh-sdk-app', '@deepseek-ai/dsh-acp-app', '@deepseek-ai/dsh-sdk-minimal', - '@deepseek-ai/dsh-experimental-terminal-bundle', + '@deepseek-ai/dsh-experimental-tool-worktree', ].map(name => pkg({ name })), pkg({ name: '@acme/dsh-base', readOnlyReason: 'management-required' }), pkg({ name: 'dsh-better-sidebar' }), @@ -817,22 +817,31 @@ describe('PluginManagerPage', () => { expect(document.querySelector('[data-plugin-count]')).toBeNull() }) - it.each([false, true])('hides persistent terminals from both lists and direct navigation without changing enabled=%s', (enabled) => { + it.each([false, true])('offers persistent terminals after Timeline with enabled=%s', (enabled) => { const name = '@deepseek-ai/dsh-experimental-terminal-bundle' const b = renderTab({ packages: [ - pkg({ name, official: true, enabled, rows: [row()] }), + pkg({ name, optional: true, installed: false, removable: false, enabled, rows: [row()] }), + pkg({ name: '@deepseek-ai/dsh-timeline', optional: true, installed: false, removable: false, enabled: false }), pkg({ name: '@deepseek-ai/dsh-experimental-voice-input-bundle', official: true }), ] }) - expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + expect(document.querySelector(`[data-plugin-package="${name}"]`) !== null).toBe(enabled) fireEvent.click(screen.getByRole('button', { name: en.moreAction })) expect(screen.getByRole('heading', { name: en.moreTitle, level: 1 })).toBeTruthy() - expect(document.querySelector(`[data-plugin-package="${name}"]`)).toBeNull() + expect(Array.from(document.querySelectorAll('[data-plugin-package]'), card => card.getAttribute('data-plugin-package'))).toEqual([ + '@deepseek-ai/dsh-experimental-voice-input-bundle', '@deepseek-ai/dsh-timeline', name, + ]) + const card = document.querySelector(`[data-plugin-package="${name}"]`) as HTMLElement + expect(within(card).getByText(en.statusBeta)).toBeTruthy() + expect(within(card).getByRole('switch').getAttribute('aria-checked')).toBe(String(enabled)) + fireEvent.click(within(card).getByRole('button', { name: en.openDetail.replace('{name}', name) })) + const detail = document.querySelector(`[data-plugin-detail="${name}"]`) as HTMLElement + expect(within(detail).getByText(en.statusBeta)).toBeTruthy() + fireEvent.click(within(detail).getByRole('switch', { name: en.enableToggle.replace('{name}', name) })) + expect(b.actions.setEnabled).toHaveBeenCalledExactlyOnceWith(name, !enabled) act(() => { b.navigation.actions.setView({ kind: 'package', name }) }) - expect(document.querySelector('[data-plugin-detail]')).toBeNull() + expect(document.querySelector(`[data-plugin-detail="${name}"]`)).not.toBeNull() act(() => { b.navigation.actions.setView({ kind: 'row', name, rowId: 'sidebar' }) }) - expect(document.querySelector('[data-plugin-row-detail]')).toBeNull() - expect(screen.queryByRole('switch', { name: en.enableToggle.replace('{name}', name) })).toBeNull() - expect(b.actions.setEnabled).not.toHaveBeenCalled() + expect(document.querySelector('[data-plugin-row-detail]')).not.toBeNull() expect(b.actions.setRowEnabled).not.toHaveBeenCalled() expect(b.actions.uninstall).not.toHaveBeenCalled() }) @@ -893,7 +902,7 @@ describe('PluginManagerPage', () => { it.each([false, true])('shows an empty list for hidden bundles with errors and installed=%s', (installed) => { renderTab({ - packages: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/dsh-experimental-terminal-bundle'].map(name => pkg({ + packages: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app', '@deepseek-ai/dsh-experimental-tool-worktree'].map(name => pkg({ name, installed, error: { code: 'operation-error', diagnostic: 'Unreadable bundle' }, })), }) diff --git a/packages/client/ui-plugin-market/package.json b/packages/client/ui-plugin-market/package.json index 5e0dffaf9c..75929dc90c 100644 --- a/packages/client/ui-plugin-market/package.json +++ b/packages/client/ui-plugin-market/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-plugin-market", "description": "Discover tab of the dsh web Plugins page: browse configured plugin market indexes and install their bundles", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-primitives/package.json b/packages/client/ui-primitives/package.json index 8e6396cbd9..acaaca5d2e 100644 --- a/packages/client/ui-primitives/package.json +++ b/packages/client/ui-primitives/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-primitives", "description": "Pure React atoms for the dsh web UI: controls, icons, markdown, and JSON inspectors (zero cordis)", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-reference/package.json b/packages/client/ui-reference/package.json index ca3240f4be..13f5a90342 100644 --- a/packages/client/ui-reference/package.json +++ b/packages/client/ui-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-reference", "description": "Unified Web @file and @session reference source", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-reference/src/client/context-menu.ts b/packages/client/ui-reference/src/client/context-menu.ts index 7e13b3d876..efab708f13 100644 --- a/packages/client/ui-reference/src/client/context-menu.ts +++ b/packages/client/ui-reference/src/client/context-menu.ts @@ -1,5 +1,6 @@ /** File references contributed to the shared file menu. */ import type { Context } from '@deepseek-ai/cordis' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { ContextMenuTargetMap } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' import { IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' @@ -30,7 +31,7 @@ export function registerReferenceMenu(ctx: Context, t: (key: ReferenceKey) => st observe: () => [ctx.locale], resolve: (target) => { const current = targetInput(target) - const path = resolveWorkspacePath(ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd, target.path) + const path = resolveWorkspacePath(sessionDirectory(ctx.sessions, target.sessionId), target.path) const mention = formatFileMention({ path, kind: 'file' }, false) return [{ id: 'addToChat', label: t('menu.addToChat'), icon: { key: 'reference.addToChat' }, separatorBefore: true, diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index 85a18ce72b..ff58b82471 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -26,6 +26,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { @@ -78,10 +79,9 @@ export function apply(ctx: ClientContext): void { name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS, inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({ ...presenceFor(sessionId), - resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path), + resolveFilePath: path => resolveWorkspacePath(sessionDirectory(sessions, sessionId), path), openFile: (path) => { - const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path)) + ctx.sidebarRight.openResource(fileAddressFor(sessionId, sessionDirectory(sessions, sessionId), path)) }, }), }, FileReference) @@ -185,8 +185,7 @@ export function apply(ctx: ClientContext): void { openReference(session, { ref, appearance }) { if (appearance !== 'file') return false const path = mentionPath(ref) - const cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path)) + ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, sessionDirectory(sessions, session.sessionId), path)) return true }, codec: { diff --git a/packages/client/ui-reference/tests/browser-plugin.client.spec.ts b/packages/client/ui-reference/tests/browser-plugin.client.spec.ts index 17d71a5875..76a22827b1 100644 --- a/packages/client/ui-reference/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-reference/tests/browser-plugin.client.spec.ts @@ -728,7 +728,7 @@ describe('reference preview', () => { const file = factory(session.sessionId) await sessions.updateSummary(session.sessionId, { cwd: '/workspace' }) await sessions.setProjection(session.sessionId, 'workingDirectory', '/workspace/elsewhere') - expect(file.resolveFilePath('docs/a b.md')).toBe('/workspace/docs/a b.md') + expect(file.resolveFilePath('docs/a b.md')).toBe('/workspace/elsewhere/docs/a b.md') expect(factory(sid('other')).resolveFilePath('/absolute.md')).toBe('/absolute.md') expect(openResource.mock.calls).toEqual([ ['dsh-resource://file/session/target/docs/a%20b.md'], diff --git a/packages/client/ui-reference/tests/context-menu.client.spec.ts b/packages/client/ui-reference/tests/context-menu.client.spec.ts index aa67881729..8d654b45fa 100644 --- a/packages/client/ui-reference/tests/context-menu.client.spec.ts +++ b/packages/client/ui-reference/tests/context-menu.client.spec.ts @@ -82,6 +82,14 @@ it('appends the final action after other providers and inserts the captured file expect(b.failed).not.toHaveBeenCalled() }) +it('resolves the captured path against the directory the Session works in', async () => { + const b = await bench() + await b.runtime.sessions.setProjection(id, 'workingDirectory', '/workspace/elsewhere') + const menu = await b.menu() + menu.select(actionId) + expect(b.shell.snapshot.draft).toBe('@"/workspace/elsewhere/docs/a b.md" ') +}) + it.each(['bad"name.txt', 'bad\nname.txt'])('disables paths outside the mention grammar: %j', async (path) => { const b = await bench() const menu = await b.menu({ path }) diff --git a/packages/client/ui-renderer/package.json b/packages/client/ui-renderer/package.json index f23fad3028..4f3134e6c0 100644 --- a/packages/client/ui-renderer/package.json +++ b/packages/client/ui-renderer/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-renderer", "description": "Browser UI renderer: React slot bindings, ctx.uiRenderer, and the assembled application root", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-schedule/package.json b/packages/client/ui-schedule/package.json index 4155b140ce..07299251bd 100644 --- a/packages/client/ui-schedule/package.json +++ b/packages/client/ui-schedule/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-schedule", "description": "Host task management page and Session reminder catalog", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", diff --git a/packages/client/ui-secret-mask/package.json b/packages/client/ui-secret-mask/package.json index 75ac2897cb..717a2edb68 100644 --- a/packages/client/ui-secret-mask/package.json +++ b/packages/client/ui-secret-mask/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-secret-mask", "description": "Web display masking for recognized credentials in sent user text", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-session-panel/package.json b/packages/client/ui-session-panel/package.json index d59129ae0b..39fd319726 100644 --- a/packages/client/ui-session-panel/package.json +++ b/packages/client/ui-session-panel/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session-panel", "description": "Floating Session panel opened from the Session header, composed of sections that plugins register", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "type": "module", "main": "lib/index.js", "types": "lib/types/index.d.ts", diff --git a/packages/client/ui-session-status/package.json b/packages/client/ui-session-status/package.json index e0decb54f9..e659250b86 100644 --- a/packages/client/ui-session-status/package.json +++ b/packages/client/ui-session-status/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session-status", "description": "Client Session status table over Host reading records: running state, the effective pending interaction, and read or unread reminders shared by clients of one Host", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-session/package.json b/packages/client/ui-session/package.json index d8901a69bb..321be1874f 100644 --- a/packages/client/ui-session/package.json +++ b/packages/client/ui-session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-session", "description": "Session Controller adapter for React and session-scoped slots", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-account/package.json b/packages/client/ui-settings-account/package.json index de257cfd5c..19ba0a0eca 100644 --- a/packages/client/ui-settings-account/package.json +++ b/packages/client/ui-settings-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-account", "description": "Manage DeepSeek login and open Platform billing pages", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-agent-loop/package.json b/packages/client/ui-settings-agent-loop/package.json index 41dce23dca..797158beaa 100644 --- a/packages/client/ui-settings-agent-loop/package.json +++ b/packages/client/ui-settings-agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-agent-loop", "description": "Settings page of the agent loop on the dsh web client's Plugins page: the parallel tool-call cap of the agent-loop namespace", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-general/package.json b/packages/client/ui-settings-general/package.json index 3efadad6a0..23330a5bb3 100644 --- a/packages/client/ui-settings-general/package.json +++ b/packages/client/ui-settings-general/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-general", "description": "Settings ownerless-copy and product onboarding plugin: the General section, shell trigger/header chrome content, settings dictionaries, and the versioned welcome notice", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-models/package.json b/packages/client/ui-settings-models/package.json index e0957334ec..289db193f9 100644 --- a/packages/client/ui-settings-models/package.json +++ b/packages/client/ui-settings-models/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-models", "description": "Models settings and shared product-onboarding dialogs over existing settings and credential joins", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-session-log/package.json b/packages/client/ui-settings-session-log/package.json index e2eb9d5130..7b1376cbe6 100644 --- a/packages/client/ui-settings-session-log/package.json +++ b/packages/client/ui-settings-session-log/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-session-log", "description": "General settings control for Session-log upload with DeepSeek API requests", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-shell/package.json b/packages/client/ui-settings-shell/package.json index 99a79d4bc2..76492686cb 100644 --- a/packages/client/ui-settings-shell/package.json +++ b/packages/client/ui-settings-shell/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-shell", "description": "Settings page of the shell executor on the dsh web client's Plugins page: the command timeout and the per-stream output cap of the shell namespace", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-subagent/package.json b/packages/client/ui-settings-subagent/package.json index e9bf2018d3..fcc7670ea5 100644 --- a/packages/client/ui-settings-subagent/package.json +++ b/packages/client/ui-settings-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-subagent", "description": "Settings page of Subagent delegation on the dsh web client's Plugins page: recursion depth, parallel capacity, and the models agents may choose for subagents", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-web-search/README.i18n.yaml b/packages/client/ui-settings-web-search/README.i18n.yaml index 89cc974777..fbc13ee1ce 100644 --- a/packages/client/ui-settings-web-search/README.i18n.yaml +++ b/packages/client/ui-settings-web-search/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-settings-web-search/use-this-package: - en: b00497ce4cf39d47 - zh: 9663997b7a4cc959 + en: 51188b15f7c1549a + zh: 4504aa62dd90cd9e /deepseek-ai-dsh-client-ui-settings-web-search/understand-the-implementation: en: 836d3f3032033148 zh: f5b5c1ee14450ab5 @@ -30,8 +30,8 @@ en: ca75c51c89c2c9b0 zh: 6e1c9a8fdde89577 /deepseek-ai-dsh-client-ui-settings-web-search/known-limitations-and-deferred-work: - en: 5c6dad603abec1c3 - zh: a594f9def4ef8215 + en: 2e6d123d575e854b + zh: cbcbc049d1f4a03b /deepseek-ai-dsh-client-ui-settings-web-search/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-settings-web-search/README.md b/packages/client/ui-settings-web-search/README.md index e86187abe7..83c4dd06d9 100644 --- a/packages/client/ui-settings-web-search/README.md +++ b/packages/client/ui-settings-web-search/README.md @@ -25,11 +25,11 @@ Open **Plugins** in the sidebar and select **Web search and fetch** in the Offic ## Use this package -The **Web search and fetch** card in the Official group opens the page. It has a **Web search provider** section and a **Web fetch provider** section, each with a provider menu directly under its title. A menu lists every provider the Host registers, including providers that plugins register, so a newly installed provider needs no change to this page; [Add another provider](../../web/web/README.md#adding-a-provider) shows how to mount one in a profile. The official ones come first while registered: the Search menu lists **DeepSeek Search API** (`deepseek-search-api`) followed by **DeepSeek (legacy)** (`deepseek-official`), and the Fetch menu lists **Direct fetch** (`http`) and then **DeepSeek Fetch API** (`deepseek-fetch-api`); every other provider follows in registration order and shows its registered title or id. The shipped composition selects DeepSeek Search API for Search and Direct fetch for Fetch, and a selection stored in settings or composed by the deployment still applies; opening the page writes nothing. Each menu has no label of its own; its accessible name is its section title followed by the selected provider, such as **Web search provider DeepSeek Search API**. A selected id the Host does not register appears as an extra **(not loaded)** entry and stays selected. While the deployment composes no provider for a capability, its menu starts with **Automatic**, which clears the stored selection so the Host chooses again. Selecting the deployment's composed provider clears the stored selection instead of writing a copy. When the provider list cannot be read, each section says its menu may be incomplete and offers **Retry**; the menus keep the last list read, or only the selected ids before any list arrives. Under each menu, the section shows the `description` the selected provider registered, in the active language, as plain text; a provider that registers none, or a selected id the Host does not register, shows no description. The official providers' descriptions state each one's credentials, charges, model calls, reachable addresses, and content limits, and Direct fetch's ends by suggesting DeepSeek Fetch API as plain text. A plugin provider's section adds, after its description, that it is configured in that plugin's own settings. +The **Web search and fetch** card in the Official group opens the page. It has a **Web search provider** section and a **Web fetch provider** section, each with a provider menu directly under its title. A menu lists every provider the Host registers, including providers that plugins register, so a newly installed provider needs no change to this page; [Add another provider](../../web/web/README.md#adding-a-provider) shows how to mount one in a profile. The official ones come first while registered: the Search menu lists **DeepSeek Search API** (`deepseek-search-api`) followed by **DeepSeek server-side search** (`deepseek-official`), and the Fetch menu lists **Direct fetch** (`http`) and then **DeepSeek Fetch API** (`deepseek-fetch-api`); every other provider follows in registration order and shows its registered title or id. The shipped composition selects no Search provider and Direct fetch for Fetch, and a selection stored in settings or composed by the deployment still applies; opening the page writes nothing. Each menu has no label of its own; its accessible name is its section title followed by the selected provider, such as **Web search provider Automatic**. A selected id the Host does not register appears as an extra **(not loaded)** entry and stays selected. While the deployment composes no provider for a capability, its menu starts with **Automatic**, which clears the stored selection so the Host chooses again. Under automatic Search selection the section states the Host's choice: DeepSeek server-side search, which has no per-search charge, for a conversation on a DeepSeek model and DeepSeek Search API for other models ([provider selection](../../web/web/README.md#provider-selection)), followed by the DeepSeek Search & Fetch guide link, which states the Search API's charges; it shows no provider panel, so the settings of either provider are edited after selecting it. Selecting the deployment's composed provider clears the stored selection instead of writing a copy. When the provider list cannot be read, each section says its menu may be incomplete and offers **Retry**; the menus keep the last list read, or only the selected ids before any list arrives. Under each menu, the section shows the `description` the selected provider registered, in the active language, as plain text; a provider that registers none, or a selected id the Host does not register, shows no description. The official providers' descriptions state each one's credentials, charges, model calls, reachable addresses, and content limits, and Direct fetch's ends by suggesting DeepSeek Fetch API as plain text. A plugin provider's section adds, after its description, that it is configured in that plugin's own settings. Under **Web search provider**, DeepSeek Search API adds a link to the DeepSeek search and fetch guide after its description, and a gray panel below the menu holds **Results per search** (an integer from 1 through 50, default 10; invalid counts block saving). The DeepSeek Fetch API section shows its provider menu and description. Each API's panel holds a **Billing** menu, writing `web-deepseek-api.searchBilling` or `fetchBilling`, with the selected billing's explanation below it: **Automatic** (`auto`, the default) uses the conversation's DeepSeek account or API key when it chats on DeepSeek, and otherwise the DeepSeek API key, then the signed-in DeepSeek account; **Signed-in DeepSeek account** (`account`) and **DeepSeek API key** (`api-key`) use only that credential. Selecting the deployment's composed billing, `auto` when it composes none, clears the stored billing. The page does not show whether the selected credential is available. The APIs' own endpoint fields are YAML-only and take precedence over billing ([web-deepseek-api authentication](../../web/web-deepseek-api/README.md#authentication)); while a capability has a non-empty `*BaseURL` or `*ApiKeyEnv`, its **Billing** label carries an **Overridden by** tag naming the set fields, and its menu is disabled. The page reads these fields and never writes or clears them. A provider with no settings on this page, such as Direct fetch or a plugin provider, shows no panel. Every control sits directly in its section; nothing is collapsed. -**DeepSeek (legacy)** shows its API key, independent Messages Base URL, and **Maximum searches per request** (`maxUses`, a positive integer, default 5) in the same panel layout. The key writes the `web-search-deepseek.apiKeyEnv` reference (`DEEPSEEK_API_KEY` by default); endpoint and limit writes stay in `web-search-deepseek`, separate from API settings. Switching away drops an unsaved key but preserves endpoint and limit settings. +**DeepSeek server-side search** shows its API key, independent Messages Base URL, and **Maximum searches per request** (`maxUses`, a positive integer, default 5) in the same panel layout. The key writes the `web-search-deepseek.apiKeyEnv` reference (`DEEPSEEK_API_KEY` by default); endpoint and limit writes stay in `web-search-deepseek`, separate from API settings. Switching away drops an unsaved key but preserves endpoint and limit settings. Value fields render the effective value, carry an **Overridden** badge with **Reset to default** once overridden, and save as a reset when emptied; a value equal to the deployment default saves as an override. The provider menus are disabled while an invalid edit or a failed save is staged, so a field the change would hide stays visible. @@ -74,7 +74,7 @@ None; this package neither assembles nor sends a provider request. -- **Automatic selection reads only the deployment composition** — a menu offers it when the composition layer sets no provider for that capability. While automatic selection applies, the Host's `DSH_WEB_SEARCH_PROVIDER` or `DSH_WEB_FETCH_PROVIDER` environment variable picks the provider instead, and the page does not show that choice. Without either, automatic selection with more than one usable registered provider makes each operation fail with `WEB_PROVIDER_AMBIGUOUS`. +- **Automatic selection reads only the deployment composition** — a menu offers it when the composition layer sets no provider for that capability. While automatic selection applies, the Host's `DSH_WEB_SEARCH_PROVIDER` or `DSH_WEB_FETCH_PROVIDER` environment variable picks the provider instead, and the page does not show that choice. Without either, automatic Fetch selection with more than one usable registered provider makes each operation fail with `WEB_PROVIDER_AMBIGUOUS`, and so does automatic Search selection when the Host does not register the DeepSeek provider it prefers for the conversation's model. The line under automatic Search selection is fixed copy that describes the Host with both DeepSeek search providers registered. - **Billing availability is not shown** — the page does not report that the selected billing has no signed-in account or no configured key; reading sign-in state needs the account remote, and the key reference of the DeepSeek API-key model provider is not visible to this page. An unavailable billing withholds the web tool from the model. diff --git a/packages/client/ui-settings-web-search/README.zh.md b/packages/client/ui-settings-web-search/README.zh.md index e09a21179e..0ec7d99811 100644 --- a/packages/client/ui-settings-web-search/README.zh.md +++ b/packages/client/ui-settings-web-search/README.zh.md @@ -25,11 +25,11 @@ kind: "package-reference" ## 使用本包 -官方分组里的**网页搜索与获取**卡片打开这一页。页面分为**网页搜索提供方**与**网页获取提供方**两节,每节标题下方紧接一个提供方下拉框。下拉框列出 Host 注册的全部提供方,包括插件注册的提供方,因此新安装的提供方无需修改本页;在 profile 中挂载提供方的方法见[添加其他提供方](../../web/web/README.zh.md#adding-a-provider)。已注册的官方提供方排在最前:搜索下拉框依次为 **DeepSeek Search API**(`deepseek-search-api`)与 **DeepSeek(旧版)**(`deepseek-official`),获取下拉框依次为**本机直接获取**(`http`)和 **DeepSeek Fetch API**(`deepseek-fetch-api`);其他提供方按注册顺序排在其后,显示其注册的标题或 id。随附组合默认搜索选择 DeepSeek Search API、获取选择本机直接获取,设置中已存的选择或部署组合的选择仍然生效;打开页面不会写入任何内容。下拉框没有单独的标签,其无障碍名称由所在节的标题和当前选中的提供方组成,例如**网页搜索提供方 DeepSeek Search API**。Host 未注册的已选 id 额外显示为一项**(未加载)**,并保持选中。部署没有为某项能力组合提供方时,其下拉框首项为**自动选择**,选中它会清除已存的选择,由 Host 重新选择。选择部署组合的提供方时清除已存的选择,而不写入一份副本。提供方列表读取失败时,每节提示其下拉框可能不完整并提供**重试**;下拉框保留上一次读到的列表,尚未读到任何列表时只包含已选 id。每节在下拉框下方以纯文本显示所选提供方注册的 `description`(按当前语言);未注册说明的提供方或 Host 未注册的已选 id 不显示说明。官方提供方的说明写明各自的凭据、计费、模型调用、可访问的地址和内容限制,本机直接获取的说明末尾以纯文本建议改用 DeepSeek Fetch API。插件提供方所在的节在其说明之后提示到该插件自己的设置中配置。 +官方分组里的**网页搜索与获取**卡片打开这一页。页面分为**网页搜索提供方**与**网页获取提供方**两节,每节标题下方紧接一个提供方下拉框。下拉框列出 Host 注册的全部提供方,包括插件注册的提供方,因此新安装的提供方无需修改本页;在 profile 中挂载提供方的方法见[添加其他提供方](../../web/web/README.zh.md#adding-a-provider)。已注册的官方提供方排在最前:搜索下拉框依次为 **DeepSeek Search API**(`deepseek-search-api`)与 **DeepSeek 服务端搜索**(`deepseek-official`),获取下拉框依次为**本机直接获取**(`http`)和 **DeepSeek Fetch API**(`deepseek-fetch-api`);其他提供方按注册顺序排在其后,显示其注册的标题或 id。随附组合不为搜索选择提供方、获取选择本机直接获取,设置中已存的选择或部署组合的选择仍然生效;打开页面不会写入任何内容。下拉框没有单独的标签,其无障碍名称由所在节的标题和当前选中的提供方组成,例如**网页搜索提供方 自动选择**。Host 未注册的已选 id 额外显示为一项**(未加载)**,并保持选中。部署没有为某项能力组合提供方时,其下拉框首项为**自动选择**,选中它会清除已存的选择,由 Host 重新选择。搜索为自动选择时,该节说明 Host 的选择:会话使用 DeepSeek 模型时用不按次收费的 DeepSeek 服务端搜索,使用其他模型时用 DeepSeek Search API([提供方选择](../../web/web/README.zh.md#provider-selection)),其后是说明 Search API 收费方式的 DeepSeek 网页搜索与获取指南链接;此时不显示提供方面板,因此两个提供方的设置都要在选中它之后编辑。选择部署组合的提供方时清除已存的选择,而不写入一份副本。提供方列表读取失败时,每节提示其下拉框可能不完整并提供**重试**;下拉框保留上一次读到的列表,尚未读到任何列表时只包含已选 id。每节在下拉框下方以纯文本显示所选提供方注册的 `description`(按当前语言);未注册说明的提供方或 Host 未注册的已选 id 不显示说明。官方提供方的说明写明各自的凭据、计费、模型调用、可访问的地址和内容限制,本机直接获取的说明末尾以纯文本建议改用 DeepSeek Fetch API。插件提供方所在的节在其说明之后提示到该插件自己的设置中配置。 **网页搜索提供方**一节中,DeepSeek Search API 在说明之后显示 DeepSeek 网页搜索与获取指南链接,下拉框下方的灰色面板中是**每次搜索结果数**(1–50 的整数,默认 10;无效值阻止保存)。DeepSeek Fetch API 所在节显示提供方下拉框及说明。每个 API 的面板中有一个**计费方式**下拉框,写入 `web-deepseek-api.searchBilling` 或 `fetchBilling`,下方显示所选计费方式的说明:**自动**(`auto`,默认)在会话使用 DeepSeek 模型时沿用其账号或 API Key,否则依次使用 DeepSeek API Key、已登录的 DeepSeek 账号;**已登录的 DeepSeek 账号**(`account`)和 **DeepSeek API Key**(`api-key`)只使用该凭据。选择部署组合的计费方式(未组合时为 `auto`)会清除已存的计费方式。页面不显示所选凭据当前是否可用。两个 API 单独配置的端点字段只能在 YAML 中设置,并优先于计费方式([web-deepseek-api 鉴权](../../web/web-deepseek-api/README.zh.md#authentication));某一能力的 `*BaseURL` 或 `*ApiKeyEnv` 非空时,其**计费方式**标题旁显示**已被…覆盖**标签并列出已设置的字段,下拉框不可用。页面只读取这些字段,从不写入或清除。在本页没有设置项的提供方(例如本机直接获取或插件提供方)不显示面板。所有控件直接位于所在节中,没有折叠区。 -**DeepSeek(旧版)**在同样的面板布局中显示 API Key、独立的 Messages Base URL 与**单次请求最多搜索次数**(`maxUses`,正整数,默认 5)。密钥写入 `web-search-deepseek.apiKeyEnv` 指向的引用(默认 `DEEPSEEK_API_KEY`);端点和次数上限写入 `web-search-deepseek`,与 API 设置分开。切换其他提供方会丢弃未保存的密钥,但保留端点和次数设置。 +**DeepSeek 服务端搜索**在同样的面板布局中显示 API Key、独立的 Messages Base URL 与**单次请求最多搜索次数**(`maxUses`,正整数,默认 5)。密钥写入 `web-search-deepseek.apiKeyEnv` 指向的引用(默认 `DEEPSEEK_API_KEY`);端点和次数上限写入 `web-search-deepseek`,与 API 设置分开。切换其他提供方会丢弃未保存的密钥,但保留端点和次数设置。 数值字段显示生效值,一旦被覆盖就带**已覆盖**标签和**恢复默认**,清空后保存等于重置;填写部署默认值则作为覆盖值保存。暂存了无效编辑或保存失败时提供方下拉框不可用,以免切换后隐藏的字段不再可见。 @@ -74,7 +74,7 @@ kind: "package-reference" -- **自动选择只看部署组合层**——组合层没有为该能力设置提供方时,下拉框才提供自动选择。自动选择生效时,Host 的 `DSH_WEB_SEARCH_PROVIDER` 或 `DSH_WEB_FETCH_PROVIDER` 环境变量会改为由它指定提供方,而页面不会显示这一选择。两者都没有时,如果注册了多个可用提供方,自动选择会让每次操作以 `WEB_PROVIDER_AMBIGUOUS` 失败。 +- **自动选择只看部署组合层**——组合层没有为该能力设置提供方时,下拉框才提供自动选择。自动选择生效时,Host 的 `DSH_WEB_SEARCH_PROVIDER` 或 `DSH_WEB_FETCH_PROVIDER` 环境变量会改为由它指定提供方,而页面不会显示这一选择。两者都没有时,如果注册了多个可用提供方,获取的自动选择会让每次操作以 `WEB_PROVIDER_AMBIGUOUS` 失败;Host 没有注册它为会话模型优先选用的 DeepSeek 提供方时,搜索的自动选择同样如此。搜索自动选择下方的说明是固定文案,描述的是两个 DeepSeek 搜索提供方都已注册的 Host。 - **不显示计费方式是否可用**——所选计费方式没有已登录账号或没有配置密钥时,页面不会提示;读取登录状态需要账号 remote,而本页看不到 DeepSeek API Key 模型提供方实际使用的密钥引用。不可用的计费方式会让模型看不到对应的网页工具。 diff --git a/packages/client/ui-settings-web-search/package.json b/packages/client/ui-settings-web-search/package.json index f9c36218bf..ed54d5cd19 100644 --- a/packages/client/ui-settings-web-search/package.json +++ b/packages/client/ui-settings-web-search/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings-web-search", "description": "Settings page for web search and fetch on the dsh web client's Plugins page: the Search and Fetch provider menus, the DeepSeek Search API result count, DeepSeek Search and Fetch API billing, and legacy Messages search settings", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-settings-web-search/src/client/WebSearchCard.tsx b/packages/client/ui-settings-web-search/src/client/WebSearchCard.tsx index ddb06ab31b..9081f31453 100644 --- a/packages/client/ui-settings-web-search/src/client/WebSearchCard.tsx +++ b/packages/client/ui-settings-web-search/src/client/WebSearchCard.tsx @@ -65,6 +65,8 @@ export function WebSearchCard(props: WebSearchCardProps) { const description = section.options.find(option => option.id === section.selected)?.description return description === undefined ? undefined : props.resolveText(description) || undefined } + // Automatic Search selection names no provider, so the page states which provider the Host runs. + const searchAuto = search.auto && search.selected === AUTO_ID return (
@@ -72,8 +74,8 @@ export function WebSearchCard(props: WebSearchCardProps) { {t('searchGuide')} : search.kind === 'plugin' ? t('pluginProviderHint') : undefined} /> {search.kind === 'deepseek' && ( @@ -267,7 +269,7 @@ function ProviderSelect(props: { disabled: boolean field: keyof WebProviderSelection onSelect: WebSearchCardFace['selectProvider'] - /** The selected provider's registered description, resolved to the active language, if it has one. */ + /** The selected provider's registered description in the active language, or the page's line for automatic selection, if any. */ description: string | undefined /** The page's own line about the selected provider, after its description, if it has one. */ hint: ReactNode diff --git a/packages/client/ui-settings-web-search/src/client/locales.ts b/packages/client/ui-settings-web-search/src/client/locales.ts index 0967272920..44a2997e2f 100644 --- a/packages/client/ui-settings-web-search/src/client/locales.ts +++ b/packages/client/ui-settings-web-search/src/client/locales.ts @@ -5,7 +5,7 @@ import type { SettingsFormLabels } from '@deepseek-ai/dsh-client-ui-primitives' /** Locale keys the page renders. */ export type WebSearchSettingsLocaleKey = | 'title' | 'description' | 'searchSection' | 'fetchSection' - | 'providerDeepSeek' | 'providerLocal' | 'providerDeepSeekFetch' | 'providerMissing' | 'providerAuto' + | 'providerDeepSeek' | 'providerLocal' | 'providerDeepSeekFetch' | 'providerMissing' | 'providerAuto' | 'searchAutoHint' | 'providerLegacy' | 'legacyKeyHint' | 'maxUses' | 'maxUsesHint' | 'invalidMaxUses' | 'providersFailed' | 'retry' | 'pluginProviderHint' | 'searchGuide' | 'searchGuideUrl' @@ -24,7 +24,7 @@ export const en: Record = { searchSection: 'Web search provider', fetchSection: 'Web fetch provider', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (legacy)', + providerLegacy: 'DeepSeek server-side search', legacyKeyHint: 'Uses the signed-in account on account-model requests; otherwise uses this API key ({ref}), shared with Models by default.', maxUses: 'Maximum searches per request', maxUsesHint: 'Maximum server-side searches per Messages request: a positive integer, default 5.', @@ -33,6 +33,7 @@ export const en: Record = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (not loaded)', providerAuto: 'Automatic', + searchAutoHint: "Follows the conversation's model: DeepSeek models use DeepSeek server-side search, which has no per-search charge; other models use DeepSeek Search API.", providersFailed: "Couldn't load the provider list, so this menu may be incomplete.", retry: 'Retry', pluginProviderHint: 'Configure this provider in its own plugin settings.', @@ -71,7 +72,7 @@ export const zh: Record = { searchSection: '网页搜索提供方', fetchSection: '网页获取提供方', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek(旧版)', + providerLegacy: 'DeepSeek 服务端搜索', legacyKeyHint: '账号模型发起的请求使用已登录账号;其他请求使用此 API Key({ref}),默认与「模型」页共用', maxUses: '单次请求最多搜索次数', maxUsesHint: '每次 Messages 请求允许的服务端搜索次数上限,须为正整数,默认 5', @@ -80,6 +81,7 @@ export const zh: Record = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id}(未加载)', providerAuto: '自动选择', + searchAutoHint: '跟随当前会话的模型:DeepSeek 模型使用 DeepSeek 服务端搜索,搜索不按次收费;其他模型使用 DeepSeek Search API。', providersFailed: '无法读取提供方列表,此菜单可能不完整', retry: '重试', pluginProviderHint: '请在该插件自己的设置中配置', @@ -127,7 +129,7 @@ export const ja = { 'searchSection': 'Web 検索プロバイダー', 'fetchSection': 'Web 取得プロバイダー', 'providerDeepSeek': 'DeepSeek Search API', - 'providerLegacy': 'DeepSeek(旧版)', + 'providerLegacy': 'DeepSeek サーバー側検索', 'legacyKeyHint': 'アカウントモデルのリクエストではログイン中のアカウントを使い、それ以外ではこの API キー({ref}、既定ではモデル設定と共有)を使います。', 'maxUses': 'リクエストごとの最大検索回数', 'maxUsesHint': 'Messages リクエストごとのサーバー側検索回数の上限です。正の整数で、既定値は 5 です。', @@ -136,6 +138,7 @@ export const ja = { 'providerDeepSeekFetch': 'DeepSeek Fetch API', 'providerMissing': '{id}(未読み込み)', 'providerAuto': '自動', + 'searchAutoHint': '会話のモデルに従います。DeepSeek モデルでは検索ごとの料金がかからない DeepSeek サーバー側検索を、他のモデルでは DeepSeek Search API を使います。', 'providersFailed': 'プロバイダー一覧を読み込めなかったため、このメニューは不完全な可能性があります。', 'retry': '再試行', 'pluginProviderHint': 'このプロバイダーは、そのプラグイン自身の設定で構成してください。', @@ -174,7 +177,7 @@ export const es = { searchSection: 'Proveedor de búsqueda web', fetchSection: 'Proveedor de obtención web', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (heredado)', + providerLegacy: 'Búsqueda en servidor de DeepSeek', legacyKeyHint: 'Las solicitudes del modelo de cuenta usan la cuenta conectada; las demás usan esta clave API ({ref}), compartida con Modelos de forma predeterminada.', maxUses: 'Búsquedas máximas por solicitud', maxUsesHint: 'Máximo de búsquedas del servidor por solicitud Messages: entero positivo, predeterminado 5.', @@ -183,6 +186,7 @@ export const es = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (no cargado)', providerAuto: 'Automático', + searchAutoHint: 'Sigue el modelo de la conversación: los modelos de DeepSeek usan la búsqueda en servidor de DeepSeek, sin cargo por búsqueda; los demás modelos usan DeepSeek Search API.', providersFailed: 'No se pudo cargar la lista de proveedores, por lo que este menú puede estar incompleto.', retry: 'Reintentar', pluginProviderHint: 'Configure este proveedor en la configuración de su propio complemento.', @@ -221,7 +225,7 @@ export const fr = { searchSection: 'Fournisseur de recherche web', fetchSection: 'Fournisseur de récupération web', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (ancienne version)', + providerLegacy: 'Recherche côté serveur DeepSeek', legacyKeyHint: 'Les requêtes du modèle de compte utilisent le compte connecté ; les autres utilisent cette clé API ({ref}), partagée avec Modèles par défaut.', maxUses: 'Recherches maximales par requête', maxUsesHint: 'Maximum de recherches côté serveur par requête Messages : entier positif, 5 par défaut.', @@ -230,6 +234,7 @@ export const fr = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (non chargé)', providerAuto: 'Automatique', + searchAutoHint: 'Suit le modèle de la conversation : les modèles DeepSeek utilisent la recherche côté serveur DeepSeek, sans frais par recherche ; les autres modèles utilisent DeepSeek Search API.', providersFailed: 'Impossible de charger la liste des fournisseurs ; ce menu peut être incomplet.', retry: 'Réessayer', pluginProviderHint: 'Configurez ce fournisseur dans les paramètres de son propre plugin.', @@ -268,7 +273,7 @@ export const de = { searchSection: 'Anbieter für Websuche', fetchSection: 'Anbieter für Webabruf', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (Legacy)', + providerLegacy: 'DeepSeek-Serversuche', legacyKeyHint: 'Kontomodellanfragen verwenden das angemeldete Konto; andere verwenden diesen API-Schlüssel ({ref}), standardmäßig mit Modelle geteilt.', maxUses: 'Maximale Suchen pro Anfrage', maxUsesHint: 'Maximale serverseitige Suchen pro Messages-Anfrage: positive Ganzzahl, Standard 5.', @@ -277,6 +282,7 @@ export const de = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (nicht geladen)', providerAuto: 'Automatisch', + searchAutoHint: 'Folgt dem Modell der Unterhaltung: DeepSeek-Modelle verwenden die DeepSeek-Serversuche ohne Kosten pro Suche; andere Modelle verwenden DeepSeek Search API.', providersFailed: 'Die Anbieterliste konnte nicht geladen werden, daher ist dieses Menü möglicherweise unvollständig.', retry: 'Erneut versuchen', pluginProviderHint: 'Konfigurieren Sie diesen Anbieter in den Einstellungen seines eigenen Plugins.', @@ -315,7 +321,7 @@ export const ru = { searchSection: 'Поставщик веб-поиска', fetchSection: 'Поставщик загрузки веб-страниц', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (прежняя версия)', + providerLegacy: 'Серверный поиск DeepSeek', legacyKeyHint: 'Запросы модели аккаунта используют активный аккаунт; остальные — этот ключ API ({ref}), по умолчанию общий с настройками моделей.', maxUses: 'Максимум поисков на запрос', maxUsesHint: 'Максимум серверных поисков на запрос Messages: положительное целое, по умолчанию 5.', @@ -324,6 +330,7 @@ export const ru = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (не загружен)', providerAuto: 'Автоматически', + searchAutoHint: 'Следует модели разговора: модели DeepSeek используют серверный поиск DeepSeek без платы за каждый поиск; остальные модели используют DeepSeek Search API.', providersFailed: 'Не удалось загрузить список поставщиков, поэтому это меню может быть неполным.', retry: 'Повторить', pluginProviderHint: 'Настройте этого поставщика в настройках его собственного плагина.', @@ -362,7 +369,7 @@ export const pt = { searchSection: 'Provedor de pesquisa na web', fetchSection: 'Provedor de obtenção na web', providerDeepSeek: 'DeepSeek Search API', - providerLegacy: 'DeepSeek (legado)', + providerLegacy: 'Pesquisa no servidor da DeepSeek', legacyKeyHint: 'Pedidos do modelo de conta usam a conta conectada; os demais usam esta chave API ({ref}), compartilhada com Modelos por padrão.', maxUses: 'Máximo de pesquisas por pedido', maxUsesHint: 'Máximo de pesquisas no servidor por pedido Messages: inteiro positivo, padrão 5.', @@ -371,6 +378,7 @@ export const pt = { providerDeepSeekFetch: 'DeepSeek Fetch API', providerMissing: '{id} (não carregado)', providerAuto: 'Automático', + searchAutoHint: 'Segue o modelo da conversa: os modelos da DeepSeek usam a pesquisa no servidor da DeepSeek, sem cobrança por pesquisa; os outros modelos usam DeepSeek Search API.', providersFailed: 'Não foi possível carregar a lista de provedores, por isso este menu pode estar incompleto.', retry: 'Tentar novamente', pluginProviderHint: 'Configure este provedor nas configurações do próprio plugin.', diff --git a/packages/client/ui-settings-web-search/tests/card.client.spec.tsx b/packages/client/ui-settings-web-search/tests/card.client.spec.tsx index 96c036a0a6..74f69258e5 100644 --- a/packages/client/ui-settings-web-search/tests/card.client.spec.tsx +++ b/packages/client/ui-settings-web-search/tests/card.client.spec.tsx @@ -207,8 +207,8 @@ describe('WebSearchCard billing', () => { describe('WebSearchCard', () => { it('offers legacy search in both locales and renders its own settings', () => { const { actions } = renderPage(legacy()) - expect(searchMenu().textContent).toBe('DeepSeek (legacy)') - expect(zh.providerLegacy).toBe('DeepSeek(旧版)') + expect(searchMenu().textContent).toBe('DeepSeek server-side search') + expect(zh.providerLegacy).toBe('DeepSeek 服务端搜索') expect(screen.queryByLabelText(en.count)).toBeNull() fireEvent.change(screen.getByLabelText(en.credential), { target: { value: 'new-key' } }) fireEvent.change(screen.getByLabelText(en.baseUrl), { target: { value: 'https://messages.test/v1' } }) @@ -395,6 +395,27 @@ describe('WebSearchCard', () => { expect(actions.selectProvider).toHaveBeenCalledTimes(1) }) + it('explains automatic Search selection with the guide link, and shows no provider panel under it', () => { + const base = shipped() + renderPage({ ...base, search: { ...base.search, selected: '', kind: 'none', auto: true } }) + expect(searchMenu().textContent).toBe(en.providerAuto) + expect(screen.getByText(en.searchAutoHint)).toBeTruthy() + expect(screen.getByRole('link', { name: en.searchGuide }).getAttribute('href')).toBe(en.searchGuideUrl) + expect(screen.queryByLabelText(en.count)).toBeNull() + }) + + it('does not explain automatic Search selection while a provider is selected or under automatic Fetch selection', () => { + const base = shipped() + renderPage({ + ...base, + search: { ...base.search, selected: 'deepseek-official', kind: 'none', auto: true }, + fetch: { ...base.fetch, selected: '', kind: 'none', auto: true }, + }) + expect(fetchMenu().textContent).toBe(en.providerAuto) + expect(screen.queryByText(en.searchAutoHint)).toBeNull() + expect(screen.queryByRole('link', { name: en.searchGuide })).toBeNull() + }) + it('reports a failed provider list read in each section and retries it', () => { const { actions } = renderPage({ ...shipped(), providersFailed: true }) for (const name of [en.searchSection, en.fetchSection]) { diff --git a/packages/client/ui-settings/package.json b/packages/client/ui-settings/package.json index 516def03fe..71247d8b2b 100644 --- a/packages/client/ui-settings/package.json +++ b/packages/client/ui-settings/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-settings", "description": "Settings domain base plugin: shared configuration forms and the canonical settings slot-type contract", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-shortcuts/package.json b/packages/client/ui-shortcuts/package.json index 1bab33a446..0a26ae6e9a 100644 --- a/packages/client/ui-shortcuts/package.json +++ b/packages/client/ui-shortcuts/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-shortcuts", "description": "Keyboard shortcut reference, recording, and local preference editing", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-browser/package.json b/packages/client/ui-sidebar-browser/package.json index 9a8afd696f..dfccb8e6d9 100644 --- a/packages/client/ui-sidebar-browser/package.json +++ b/packages/client/ui-sidebar-browser/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-browser", "description": "Sandboxed Web browser tabs for the right Sidebar", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-documentpreview/package.json b/packages/client/ui-sidebar-documentpreview/package.json index 7e7f7f738c..fc024b2033 100644 --- a/packages/client/ui-sidebar-documentpreview/package.json +++ b/packages/client/ui-sidebar-documentpreview/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-documentpreview", "description": "Extensible Sidebar previews for Office documents, spreadsheets, Markdown, code, images, PDF, HTML, and plain text", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-files/README.i18n.yaml b/packages/client/ui-sidebar-files/README.i18n.yaml index 1c386b73cc..468a6603e0 100644 --- a/packages/client/ui-sidebar-files/README.i18n.yaml +++ b/packages/client/ui-sidebar-files/README.i18n.yaml @@ -21,11 +21,11 @@ en: 3424600b15bde2d2 zh: 2cf1c99ffef2ad50 /deepseek-ai-dsh-client-ui-sidebar-files/the-tree: - en: 3d71e50801761213 - zh: e4e9ab19dd22288d + en: 8f85cc7d1f4fec77 + zh: 67f19159054f0888 /deepseek-ai-dsh-client-ui-sidebar-files/search: - en: 275bc2aa20907881 - zh: 4dac902558cb29f5 + en: fe964bf291d46508 + zh: 019e91b2413bca95 /deepseek-ai-dsh-client-ui-sidebar-files/reusable-tree-factory: en: 76e4d93d65d3c50e zh: b611bba888f86b85 @@ -36,8 +36,8 @@ en: 39debadcc6cefd24 zh: cc212c8377851a91 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work: - en: f28a32e47e684f5c - zh: e5e38014048ebe59 + en: 14bd8ccb7c54ed17 + zh: cc2c3181d7859251 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work/dev-note: en: 753149828a165920 zh: a4daff5bb946b14e diff --git a/packages/client/ui-sidebar-files/README.md b/packages/client/ui-sidebar-files/README.md index a9384768f2..3d618398aa 100644 --- a/packages/client/ui-sidebar-files/README.md +++ b/packages/client/ui-sidebar-files/README.md @@ -56,7 +56,7 @@ The tree marks the row of the current file with `aria-current`. While the tree i ## The tree -The root is the session's working directory, read from `useSessions().byId[sessionId].cwd`. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Entries whose name starts with `.` are left out until the reader [shows hidden entries](#search). +The root is the session's working directory, selected with `selectSessionDirectory` from the list snapshot: the projected `workingDirectory`, else the header directory. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Entries whose name starts with `.` are left out until the reader [shows hidden entries](#search). | Entry type | Row | |---|---| @@ -83,7 +83,7 @@ The eye starts closed. Closed, the tree leaves out every entry whose name starts The settings panel floats over the navigator below the search bar and lists the excluded files and directories, newest first: each rule has a checkbox that turns it on or off, its path, and a remove control. A rule without `/` names every file or directory of that name at any depth, and a rule with `/` names one workspace-relative path; an excluded directory takes its contents with it. The field that adds a rule stays above the list, which alone scrolls; Enter adds the typed name or path at the top, or names why it is refused below the field. The default list holds version-control, package-manager, and build output directories (`.git`, `.hg`, `.next`, `.pnpm-store`, `.svn`, `.turbo`, `.yarn`, `build`, `coverage`, `dist`, `node_modules`), then the metadata macOS and Windows write (`.DS_Store`, `.Spotlight-V100`, `.Trashes`, `.fseventsd`, `Thumbs.db`, `desktop.ini`, `$RECYCLE.BIN`, `System Volume Information`). The header ends with the restore control, shown while the list differs from the default list in any way, order included, which replaces the list with the default list, and the close control. Above the list, the "Respect ignore files (.gitignore, etc.)" checkbox, checked by default, leaves out entries that ripgrep's ignore rules ignore: `.gitignore` files inside a git repository, including those above the workspace root, `.ignore` files, and the global Git excludes; outside a git repository `.gitignore` does not apply; like the eye, it is saved as soon as it changes. Rule edits stay in the panel until it closes, by the magnifier, by its close control, by Escape, or by keyboard focus leaving it, as a press outside it does; closing saves them. Exclusion rules narrow only the search, never the tree. -The rules, the eye, and the `.gitignore` choice are kept per workspace root, the Session's working directory with trailing separators removed except the one a filesystem root needs, so every Session and pane rooted there shares them and other roots do not. They live in browser storage under `dsh.sidebar-files.workspace-search.v1`, one entry per root the reader changed, holding only the fields that differ from the defaults, so a later build's default list reaches a root whose rules the reader left alone; a root changed back to the defaults loses its entry, and a missing or malformed field reads as its default. A change while a pane's search text is not blank searches again at once. +The rules, the eye, and the `.gitignore` choice are kept per workspace root, with trailing separators removed except the one a filesystem root needs, so every Session and pane rooted there shares them and other roots do not. They live in browser storage under `dsh.sidebar-files.workspace-search.v1`, one entry per root the reader changed, holding only the fields that differ from the defaults, so a later build's default list reaches a root whose rules the reader left alone; a root changed back to the defaults loses its entry, and a missing or malformed field reads as its default. A change while a pane's search text is not blank searches again at once, and a Session that enters another checkout while its text is not blank searches that checkout with its own preferences. ↓ in the search field moves keyboard focus to the first row, ↑ and ↓ move between rows of the tree or the results, and ↑ on the first row returns to the field while the bar is shown; Enter on a row acts as a click does. Escape closes the settings panel first, then clears the search text even while the bar is collapsed, and only then reaches the overlaying navigator's close; clearing a hidden query keeps focus in the tree. On an existing docked files page or beside a docked preview, `workspace.files` shows the search field and gives it keyboard focus; other targets follow the [command's page-opening behavior](#what-it-registers). @@ -116,7 +116,7 @@ None; directory listings and searches travel over the Remote and assemble no mod - **A query with `/` highlights nothing across names.** Each name is highlighted on its own, so a query that spans a `/` marks no row. - **Names with glob characters cannot be excluded.** A rule may not contain `* ? [ ] { } !`, so a literal path such as Next.js `app/[slug]` cannot be named. - **Preferences do not follow other browser tabs.** Each tab reads browser storage once when the plugin loads and writes the preferences of every root back as one value, so a tab that writes overwrites the changes other tabs made since it loaded to any workspace's preferences, until it reloads. -- **One root.** The tree is rooted at the session's working directory; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. +- **One root.** The tree is rooted at the session's workspace root; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. ### Dev Note diff --git a/packages/client/ui-sidebar-files/README.zh.md b/packages/client/ui-sidebar-files/README.zh.md index 4ee85ac4f3..8cdc21c924 100644 --- a/packages/client/ui-sidebar-files/README.zh.md +++ b/packages/client/ui-sidebar-files/README.zh.md @@ -56,7 +56,7 @@ kind: "package-reference" ## 树 -根是会话的工作目录,读自 `useSessions().byId[sessionId].cwd`。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。名称以 `.` 开头的条目,在读者[显示隐藏条目](#search)之前不显示。 +根是会话的工作目录,用 `selectSessionDirectory` 从列表快照选出:投影的 `workingDirectory`,否则为 header 目录。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。名称以 `.` 开头的条目,在读者[显示隐藏条目](#search)之前不显示。 | 条目类型 | 行 | |---|---| @@ -83,7 +83,7 @@ kind: "package-reference" 设置面板浮在导航栏中搜索栏的下方,列出排除的文件和目录,最新的在最前:每条规则有开关它的复选框、路径和删除按钮。不含 `/` 的规则指任意深度上所有同名的文件或目录,含 `/` 的规则指一个相对于工作区的路径;排除一个目录时其内容也一并排除。添加规则的输入框固定在列表上方,只有列表本身滚动;Enter 把输入的名称或路径添加到最上方,或在输入框下方说明拒绝的原因。默认列表先是版本控制、包管理器和构建输出目录(`.git`、`.hg`、`.next`、`.pnpm-store`、`.svn`、`.turbo`、`.yarn`、`build`、`coverage`、`dist`、`node_modules`),然后是 macOS 和 Windows 写入的元数据(`.DS_Store`、`.Spotlight-V100`、`.Trashes`、`.fseventsd`、`Thumbs.db`、`desktop.ini`、`$RECYCLE.BIN`、`System Volume Information`)。标题行末端是还原按钮和关闭按钮;列表与默认列表有任何不同(包括顺序不同)时显示还原按钮,点击后把列表重置为默认列表。列表上方的「尊重忽略文件(.gitignore 等)」(Respect ignore files (.gitignore, etc.))复选框默认勾选,此时略过 ripgrep 忽略规则忽略的条目:git 仓库内的 `.gitignore`(包括工作区根以上的)、`.ignore` 文件和全局 Git excludes;不在 git 仓库内时 `.gitignore` 不生效;它和眼睛一样,一改变就保存。规则的编辑留在面板内,直到面板通过放大镜、关闭按钮、Escape 或键盘焦点离开它(在面板外按下也是如此)而关闭;关闭即保存。排除规则只缩小搜索范围,从不影响目录树。 -规则、眼睛与 `.gitignore` 选择按工作区根保存,即去掉尾随分隔符的 Session 工作目录(文件系统根需要的那一个除外),因此根在同一目录的每个 Session 与分栏共享它们,其他根互不影响。它们保存在浏览器存储的 `dsh.sidebar-files.workspace-search.v1` 下,读者改过的每个根各占一项,只保存与默认值不同的字段,因此读者没改过规则的根能用上后续版本的默认列表;改回默认值的根删除其条目,缺失或格式不对的字段按默认值读取。分栏的搜索文字非空时发生的变化会立即重新搜索。 +规则、眼睛与 `.gitignore` 选择按工作区根保存,即去掉尾随分隔符的工作区根(文件系统根需要的那一个除外),因此根在同一目录的每个 Session 与分栏共享它们,其他根互不影响。它们保存在浏览器存储的 `dsh.sidebar-files.workspace-search.v1` 下,读者改过的每个根各占一项,只保存与默认值不同的字段,因此读者没改过规则的根能用上后续版本的默认列表;改回默认值的根删除其条目,缺失或格式不对的字段按默认值读取。分栏的搜索文字非空时发生的变化会立即重新搜索;Session 在搜索文字非空时进入另一个检出目录,会用该检出目录自己的偏好在那里重新搜索。 在搜索框中按 ↓ 把键盘焦点移到第一行,↑ 与 ↓ 在目录树或搜索结果的行之间移动,搜索栏显示时在第一行按 ↑ 回到搜索框;在行上按 Enter 与单击效果相同。Escape 先关闭设置面板,再清空搜索文字(搜索栏收起时也一样),之后才交给覆盖式导航栏的关闭行为;清空隐藏的查询时,焦点留在目录树内。在已有停靠文件页或停靠预览旁,`workspace.files` 显示搜索框并把键盘焦点移给它;其他位置遵循[命令的文件页打开行为](#what-it-registers)。 @@ -116,7 +116,7 @@ kind: "package-reference" - **含 `/` 的查询不会跨名称高亮。**每个名称单独高亮,因此跨越 `/` 的查询不会在任何行上标出。 - **含通配符的名称无法排除。**规则不能包含 `* ? [ ] { } !`,因此无法写出 Next.js `app/[slug]` 这类字面路径。 - **偏好不会同步到其他浏览器标签页。**每个标签页只在插件加载时读取一次浏览器存储,并把所有根的偏好作为一个整体写回,因此一个标签页写入时,会覆盖其他标签页在它加载之后对任何工作区偏好所做的修改,直到它重新加载。 -- **只有一个根。**树以会话工作目录为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 +- **只有一个根。**树以会话工作区根为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 ### 开发备注 diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index 912ca2dcef..a4b67c3f53 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-files", "description": "The workspace files page and one workspace directory tree per pane beside docked and floating file previews, listed lazily over the workspaceFiles Remote namespace", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -50,10 +50,13 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-files": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -64,11 +67,9 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@testing-library/react": "^16.3.3", - "react": "^18.2.0", "clsx": "^2.0.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx index dac8bb7f88..151699f78b 100644 --- a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx @@ -7,6 +7,7 @@ * follows `PUSH_FROM`, `FILL_BELOW`, and `FULLSCREEN_QUERY`; the package * README describes its behavior, search included. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { CSSProperties, KeyboardEvent, ReactNode } from 'react' import clsx from 'clsx' @@ -173,9 +174,8 @@ export function FileNavigator({ const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const paneId = panel.id - // A Session's working directory comes from its header and never changes once - // known, so every search result the pane's store holds is rooted at it. - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + // The tree is rooted at the directory the Session works in; the face searches again when it changes. + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const state = useStore(store => store.byPane[paneId]) const rowWidth = useRowWidth(paneId) const canOpen = useCanOpen(check => check) diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx index 7b9269a927..962d3e319e 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx @@ -7,6 +7,7 @@ * it is and opens the file where the right Sidebar places it by default * (`FileNavigator`). */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback, useEffect } from 'react' import type { ReactNode } from 'react' import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' @@ -51,7 +52,7 @@ export function FilesBody(props: FilesBodyProps): ReactNode { () => tab.actions.bindCommands({ refresh: () => { refresh(panel.id) } }), [tab.actions, panel.id, refresh], ) - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) // The setting belongs to a listed tree, so there is nothing to set before one. const autoRefresh = useStore((store) => { const tree = store.byPane[panel.id]?.tree diff --git a/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx index f30da3999d..a897b35074 100644 --- a/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx +++ b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx @@ -5,6 +5,7 @@ * the pane reads, and registers itself with the face, which hands it the * keyboard when Escape closes the navigator. */ +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback } from 'react' import type { ReactNode } from 'react' import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' @@ -42,7 +43,7 @@ export function NavigatorToggle( { useTabInfo, sessionId, useSessions, useStore, actions, toggleDrawn, t }: FactoryComponentPropsOf<'sidebar.files.navigator.toggle'>, ): ReactNode { const { panel } = useTabInfo() - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const cwd = useSessions(sessions => selectSessionDirectory(sessions, sessionId)) const open = useStore(store => store.byPane[panel.id]?.open) === true // Stable, so the control registers once per drawing rather than on every render. const toggleRef = useCallback((button: HTMLElement | null) => { toggleDrawn(panel.id, button) }, [toggleDrawn, panel.id]) diff --git a/packages/client/ui-sidebar-files/src/client/face.ts b/packages/client/ui-sidebar-files/src/client/face.ts index 3bdccb9337..0ca2b20206 100644 --- a/packages/client/ui-sidebar-files/src/client/face.ts +++ b/packages/client/ui-sidebar-files/src/client/face.ts @@ -194,8 +194,8 @@ export interface FilesInjected { * such text, a change to those preferences searches again. Blank text ends * the search, aborting a running one, and the pane draws its tree again. * @param paneId - the pane being drawn. - * @param cwd - the Session's working directory, the search's root; fixed for the Session once known, so a - * result always shares the pane's tree root. + * @param cwd - the Session's working directory, which the search and its result tree are rooted at; a + * `hold` with another directory searches the held text again there. * @param query - the text as typed. */ readonly setQuery: (paneId: PaneId, cwd: string, query: string) => void @@ -629,6 +629,11 @@ export function filesFace( pane.root = node node.open() if (kept !== undefined) batch(() => { relisting(paneId, kept.expanded) }) + // Text held while the Session entered another checkout searches that checkout with its preferences. + if (pane.searchQuery !== '' && pane.following?.cwd !== root) { + follow(paneId, pane, root) + runSearch(paneId, pane, root) + } step(paneId, pane) } // A navigation belongs to its target tab, not the tree that initiated it. diff --git a/packages/client/ui-sidebar-files/tests/mount.client.tsx b/packages/client/ui-sidebar-files/tests/mount.client.tsx index 32a4cc14aa..4f1991bac3 100644 --- a/packages/client/ui-sidebar-files/tests/mount.client.tsx +++ b/packages/client/ui-sidebar-files/tests/mount.client.tsx @@ -140,8 +140,12 @@ function harness(placement: Placement, controller: AbortController, book: Worksp openTab: vi.fn(), close: vi.fn(), } - const sessionsAt = (cwd: string | null): SessionListState => - ({ byId: cwd === null ? {} : { [SESSION]: { cwd } } } as unknown as SessionListState) + const sessionsAt = (cwd: string | null): SessionListState => ({ + ids: cwd === null ? [] : [SESSION], + byId: cwd === null ? {} : { [SESSION]: { id: SESSION, displayTitle: 'files', running: false, retainedBy: {}, blank: false, updatedAt: 0, cwd } }, + phase: 'ready', + projectionsBySession: {}, + }) const useTabInfo = (): SidebarRightTabInfo => ({ sidebar: { expanded: true, fullscreen: false }, panel: { id: PANE, isFloating: placement.isFloating ?? false }, diff --git a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts index 2436eac12e..ca99a0de81 100644 --- a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts @@ -194,6 +194,31 @@ describe('the face\'s search', () => { expect(two.search).toHaveBeenCalledTimes(4) }) + it('searches the checkout a held query\'s pane moves to, with that checkout\'s preferences', async () => { + const book = memoryBook() + const h = session('s-1', book) + h.face.setSearchPreferences('/work/other', { showHidden: true }) + const release = h.face.hold(PANE, ROOT) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + expect(h.search).toHaveBeenCalledOnce() + expect(h.result()).toMatchObject({ tree: { root: ROOT } }) + // The Session enters another checkout: the tree restarts there, and so does the held search. + const moved = h.face.hold(PANE, '/work/other') + release() + expect(h.search).toHaveBeenLastCalledWith('s-1', expect.objectContaining({ query: 'a', includeHidden: true }), expect.any(AbortSignal)) + await searchesSettled() + expect(h.result()).toMatchObject({ tree: { root: '/work/other' }, hiddenLeftOut: false }) + // Holding the same root again searches nothing new; the new root's preferences are followed now. + h.face.hold(PANE, '/work/other')() + expect(h.search).toHaveBeenCalledTimes(2) + h.face.setSearchPreferences(ROOT, { showHidden: true }) + expect(h.search).toHaveBeenCalledTimes(2) + h.face.setSearchPreferences('/work/other', { respectGitignore: false }) + expect(h.search).toHaveBeenCalledTimes(3) + moved() + }) + it('does not search again when the listed levels change under shown results', async () => { const h = session('s-1', memoryBook()) h.instance.actions.start(PANE, ROOT) diff --git a/packages/client/ui-sidebar-files/tsconfig.json b/packages/client/ui-sidebar-files/tsconfig.json index 47b76f17ba..716d7b6823 100644 --- a/packages/client/ui-sidebar-files/tsconfig.json +++ b/packages/client/ui-sidebar-files/tsconfig.json @@ -49,6 +49,9 @@ }, { "path": "../ui-context-menu" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" } ] } diff --git a/packages/client/ui-sidebar-right/package.json b/packages/client/ui-sidebar-right/package.json index 0512e97ce7..4681f4ee4b 100644 --- a/packages/client/ui-sidebar-right/package.json +++ b/packages/client/ui-sidebar-right/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-right", "description": "Right Sidebar: the docking surface's session-bound state, its panel and header expand control, and the navigation service over it", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar-terminal/package.json b/packages/client/ui-sidebar-terminal/package.json index 8e21991f64..059f834c41 100644 --- a/packages/client/ui-sidebar-terminal/package.json +++ b/packages/client/ui-sidebar-terminal/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar-terminal", "description": "Interactive shell tabs for the right Sidebar", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar/README.i18n.yaml b/packages/client/ui-sidebar/README.i18n.yaml index 399cfacf3f..7d7a31ef1a 100644 --- a/packages/client/ui-sidebar/README.i18n.yaml +++ b/packages/client/ui-sidebar/README.i18n.yaml @@ -21,8 +21,8 @@ en: 6bc49e22f0f73f07 zh: 10883997ccb7d145 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/global-panel-entries: - en: 0b5faf7b768c5498 - zh: 98afc24bf1f8a7d6 + en: c0434112ae12b04a + zh: 20da5afa27de5177 /deepseek-ai-dsh-client-ui-sidebar/use-this-package/collapse-behavior: en: 61d563b0f82ff658 zh: f27504350dd14d4c @@ -36,8 +36,8 @@ en: 3e84ffdf6c7c1731 zh: 3f7b19cac6d6674f /deepseek-ai-dsh-client-ui-sidebar/understand-the-implementation: - en: 2b5dd6efe77ee023 - zh: 1dc6610bc9e50406 + en: 4d08c745534fc8f4 + zh: 164418412f91c02a /deepseek-ai-dsh-client-ui-sidebar/understand-the-implementation/slot-discipline: en: 6eefc5c45abe8a8f zh: 20b651e48a0ea903 diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index f2af18a4d2..76cfeb907c 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -41,6 +41,8 @@ The expanded brand row renders `sidebar.brand.mark` and `sidebar.brand.name` as Plugins add an icon component to the root-scoped `sidebar.panellist` list with an `id`, optional `order`, and a string or locale-aware `label`. The same id addresses the component registered in the layout's root-scoped `main` keyed slot; selecting a missing main entry throws without changing the current selection. The label supplies plain visible text, the accessible name, and the collapsed tooltip. Expanded navigation rows are 32px high with a 2px gap; collapsed rail controls remain 36px high with a 12px gap. Expanded navigation keeps an 8px bottom margin before the Workspace header. Each row reads its own selected state through `usePanelInfo`; moving DOM focus to search or a directory picker does not change the displayed panel or its selected row. With no panel registrations, neither the list nor spacing for it is rendered. The shipped composition registers no example panel. +A panel may also register non-interactive inline content in the root-scoped `sidebar.panellist.trailing` list with the same `id`, such as a count. It receives `wide` and `active`. The expanded row lays it out after the title, so a row without content keeps its full title width. Where the pointer hovers, the content rests at the row's end, in the place of the unpin action, and gives way to that action while the row is hovered or holds keyboard focus, as a Session row's time gives way to its actions; on a touch device, where the unpin action always shows, the content stays before it. The collapsed rail shows it over the icon's top trailing corner. It renders inside the row button, so it holds no interactive elements; its text becomes the button's accessible description, so decorative parts must be `aria-hidden`. + While the root-scoped `sidebar.panellist.actions` list has registrations, a **More** button styled as a panel row follows the rows inside the navigation landmark; the collapsed rail shows its label as a tooltip. It opens a menu whose rows are that list's registrations. Each receives `entries` (customizable panels in registration order with `id`, `label`, `pinned`, and `active`; Plugins is never listed), `onOpen(id)`, which selects the panel, `onPinnedChange(id, pinned)`, and `onDismiss()`, which closes the menu. The sidebar keeps one in-memory list of unpinned panel ids shared by every Session; Plugins always shows. While More shows, expanded rows other than Plugins show an unpin action on hover or keyboard focus; devices without hover show it continuously. Its resting color matches the Session pin marker, and its tooltip says “Unpin from left sidebar”. Both sidebar and More entries follow the same registration order rather than pin timing. The default More menu lists only unpinned panels before plugin browsing and creation; opening a panel does not pin it, while its separate pin icon returns the row to the sidebar and dismisses the menu. Choices reset when the plugin reloads and legacy localStorage values are ignored. Unpinning hides only the row, and only while More shows; without `sidebar.panellist.actions` registrations every registered row shows again. The main panel, its registration, and the current selection stay unchanged. Unregistered panel ids remain in the in-memory list until the plugin reloads. ### Collapse behavior @@ -80,7 +82,7 @@ On Desktop, the official navigation controls report `sidebar_menu_click` with `m
Implementation internals — click to expand -The shell is pure composition: `SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared brand, the `sidebar.workspaces` and `sidebar.settings` child slots, and injected navigation callbacks. The sidebar declares the `sidebar.panel.icon` Component Factory, which owns the `sidebar.panellist` list; panel rows and the More menu render a panel's registered icon through that factory. Panel metadata is derived from list registrations and locale changes; selection belongs to the layout store. The injected `trackEntryClick(attributes)` forwards to `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`, and `selectPanel` only selects, so each control supplies its own entry and position. +The shell is pure composition: `SidebarRootComponentProps` composes the layout owner share, the global `useSessions` and `useWorkspaces` hooks, the declared brand, the `sidebar.workspaces` and `sidebar.settings` child slots, and injected navigation callbacks. The sidebar declares the `sidebar.panel.icon` Component Factory, which owns the `sidebar.panellist` list, and the `sidebar.panel.trailing` Component Factory, which owns the `sidebar.panellist.trailing` list; panel rows and the More menu render a panel's registered icon through the first, and panel rows its trailing content through the second. Panel metadata is derived from list registrations and locale changes; selection belongs to the layout store. The injected `trackEntryClick(attributes)` forwards to `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`, and `selectPanel` only selects, so each control supplies its own entry and position. Expanded navigation uses 8px outer gutters, hover and selected fills inset 3px on each side, and a 16px leading cell with a 6px label gap. New Session centers its content; its row keeps 4px side margins and a 6px bottom margin. Navigation adds a further 4px outside the scrollport and an 8px gap inside it that scrolls away. The logo row has no bottom margin; its content starts 16px from the column's left edge, with 5px between mark and name. Only the macOS non-fullscreen top toggle shifts 4px right while expanded, retaining that offset throughout its fade-out. Collapsed geometry stays independent. diff --git a/packages/client/ui-sidebar/README.zh.md b/packages/client/ui-sidebar/README.zh.md index ef04031f95..0d76837aca 100644 --- a/packages/client/ui-sidebar/README.zh.md +++ b/packages/client/ui-sidebar/README.zh.md @@ -41,6 +41,8 @@ dsh Web 客户端的侧边栏让用户识别当前构建、启动新会话、将 插件在 root 作用域的 `sidebar.panellist` list 中注册图标组件,提供 `id`、可选 `order`,以及字符串或 locale-aware 的 `label`。同一个 id 寻址布局中 root 作用域 `main` keyed slot 的组件;选择不存在的主面板条目会抛错,并保留当前选中态。标签提供普通可见文字、无障碍名称和折叠提示。展开态导航行高 32px,间距为 2px;折叠窄栏控件保持 36px 高和 12px 间距。展开态导航区域与工作区标题行之间保留 8px 底部外边距。每一行通过 `usePanelInfo` 读取自己的选中态;DOM 焦点移到搜索框或目录选择器时,显示的面板及其列表项选中态不变。没有面板注册项时,列表及其间距均不渲染。产品随附的组合不注册示例面板。 +面板还可以用相同 `id` 在 root 作用域的 `sidebar.panellist.trailing` list 中注册不可交互的行内内容,例如数量。它接收 `wide` 与 `active`。展开的行把它排在标题之后,没有内容的行保留完整的标题宽度。在支持悬停的设备上,内容停在行尾、取消固定操作所在的位置,行被悬停或获得键盘焦点时让位给该操作,与会话行的时间让位给行内操作的方式相同;在触屏设备上取消固定操作始终显示,内容留在它之前。收起的窄栏在图标右上角显示它。它渲染在行按钮内,因此不能包含可交互元素;它的文字成为按钮的无障碍描述,因此装饰性的部分必须设为 `aria-hidden`。 + root 作用域的 `sidebar.panellist.actions` list 有注册项时,导航区域的面板行之后显示面板行样式的**更多**按钮;收起的窄栏以提示框显示其名称。它打开的菜单以该 list 的注册项为菜单行。每个注册项接收 `entries`(按注册顺序的可自定义面板,含 `id`、`label`、`pinned` 与 `active`;不含插件管理)、选中面板的 `onOpen(id)`、`onPinnedChange(id, pinned)`,以及关闭菜单的 `onDismiss()`。侧边栏在内存中保存所有会话共用的已收起面板 id 列表;插件管理入口始终显示。更多按钮显示时,展开态中除插件管理外的面板行在悬停或键盘聚焦时显示取消固定操作;不支持悬停的设备始终显示该操作。图标默认颜色与会话置顶标记一致,提示为“从左侧栏取消固定”。侧栏和更多菜单入口遵循相同的注册排序,不按固定时间重排。默认更多菜单在插件浏览和创建之前仅列出未固定的面板;打开面板不会将其固定,独立的固定图标则将该行放回侧边栏并关闭菜单。插件重新加载时选择重置,不读取旧 localStorage 值。收起只隐藏导航行,且仅在更多按钮显示时生效;`sidebar.panellist.actions` 没有注册项时,所有已注册的面板行重新显示。主面板、其注册和当前选中态不变。未注册面板的 id 保留在内存列表中,直到插件重新加载。 ### 折叠行为 @@ -80,7 +82,7 @@ root 作用域的 `sidebar.session.action` 是包裹新建会话行内容的 HOC
实现细节——点击展开 -外壳是纯组合:`SidebarRootComponentProps` 组合布局 owner share、全局 `useSessions` 与 `useWorkspaces` 钩子、已声明的品牌、`sidebar.workspaces` 与 `sidebar.settings` 子 slot,以及注入的导航回调。侧边栏声明 `sidebar.panel.icon` Component Factory,由它拥有 `sidebar.panellist` list;面板行和更多菜单都通过该 factory 渲染面板注册的图标。面板元数据由列表注册和 locale 变化派生;选中态属于布局存储。注入的 `trackEntryClick(attributes)` 转发到 `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`;`selectPanel` 只负责选中,因此由各控件自行提供入口与位置。 +外壳是纯组合:`SidebarRootComponentProps` 组合布局 owner share、全局 `useSessions` 与 `useWorkspaces` 钩子、已声明的品牌、`sidebar.workspaces` 与 `sidebar.settings` 子 slot,以及注入的导航回调。侧边栏声明 `sidebar.panel.icon` Component Factory,由它拥有 `sidebar.panellist` list,并声明 `sidebar.panel.trailing` Component Factory,由它拥有 `sidebar.panellist.trailing` list;面板行和更多菜单通过前者渲染面板注册的图标,面板行通过后者渲染行尾内容。面板元数据由列表注册和 locale 变化派生;选中态属于布局存储。注入的 `trackEntryClick(attributes)` 转发到 `ctx.get('productAnalytics')?.track('sidebar_menu_click', attributes)`;`selectPanel` 只负责选中,因此由各控件自行提供入口与位置。 展开态导航的左右外距为 8px,悬停与选中底色在两侧各内缩 3px,前置单元宽 16px,与标签间隔 6px。新会话内容居中,所在行保留 4px 左右外边距及 6px 底部外边距。导航额外保留滚动区外的 4px 与滚动区内、随内容滚走的 8px 间距。logo 行无底部外边距;内容从侧栏左边缘向内 16px 开始,标记与名称间隔 5px。仅 macOS 非全屏、侧栏展开时,顶部开关向右偏移 4px,并在整个淡出期间保持该偏移。折叠态尺寸独立保留。 diff --git a/packages/client/ui-sidebar/package.json b/packages/client/ui-sidebar/package.json index 208fcf4109..fcaba3d1bb 100644 --- a/packages/client/ui-sidebar/package.json +++ b/packages/client/ui-sidebar/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-sidebar", "description": "Sidebar plugin: session multi-level tree, search, grouping, state dots", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-sidebar/src/client/PanelIcon.tsx b/packages/client/ui-sidebar/src/client/PanelIcon.tsx index ba3ed5fc04..85b2fa9262 100644 --- a/packages/client/ui-sidebar/src/client/PanelIcon.tsx +++ b/packages/client/ui-sidebar/src/client/PanelIcon.tsx @@ -10,3 +10,12 @@ import type {} from './contract/slots.ts' export function PanelIcon({ id, size, active, renderSlot }: FactoryComponentPropsOf<'sidebar.panel.icon'>) { return renderSlot('sidebar.panellist', { size, active }, { only: id }) } + +/** + * Render the trailing content registered for one panel in its navigation row. + * @param props - Panel identity, row state, and the authorized child renderer. + * @returns The matching trailing content, or nothing without a registration. + */ +export function PanelTrailing({ id, wide, active, renderSlot }: FactoryComponentPropsOf<'sidebar.panel.trailing'>) { + return renderSlot('sidebar.panellist.trailing', { wide, active }, { only: id }) +} diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css index 07189fffa7..61ffc2b547 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.module.css +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.module.css @@ -693,6 +693,27 @@ outline-offset: -2px; } +/* A panel's trailing content follows the title in the row's flow: a row without content keeps its full title width, + and the title yields room only to content that shows. Where the pointer hovers, the content rests at the row's end + and gives way to the unpin action; elsewhere it stays before the action, which always shows. On the collapsed rail it + sits over the icon's top trailing corner. */ +.panelTrailing { + flex: none; + display: inline-flex; + align-items: center; + margin-left: auto; + color: var(--dsw-alias-label-tertiary); + font-size: 12px; + line-height: 18px; + font-variant-numeric: tabular-nums; +} + +.collapsed .panelTrailing { + position: absolute; + right: 5px; + top: 5px; +} + @media (hover: hover) { .panelUnpin { opacity: 0; } .panelEntry:hover { background-color: var(--dsw-alias-interactive-bg-hover); } @@ -700,6 +721,17 @@ .panelUnpin:hover { color: var(--dsw-alias-label-primary); } .panelEntry:hover .panelUnpin, .panelEntry:has(:focus-visible) .panelUnpin { opacity: 1; } + + /* The unpin action shows only while its row is hovered or holds keyboard focus, so trailing content rests in the + action's place, as a Session row's time rests in the place of its actions: its trailing edge is the unpin glyph's, + 7px from the row's, and its box fills the rest of the 38px the row keeps for the action. */ + .panelEntryWide .panelRow { padding-right: 7px; } + .panelEntryWide .panelTrailing { + justify-content: flex-end; + min-width: 31px; + } + .panelEntry:has(.panelUnpin):hover .panelTrailing, + .panelEntry:has(.panelUnpin):has(:focus-visible) .panelTrailing { opacity: 0; } } .panelList { diff --git a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx index 353eea66de..2be8c62182 100644 --- a/packages/client/ui-sidebar/src/client/SidebarRoot.tsx +++ b/packages/client/ui-sidebar/src/client/SidebarRoot.tsx @@ -18,7 +18,7 @@ * scrollbar indirection away while it is elsewhere, so a list the user is not * pointing at carries no bar. */ -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { PointerEvent as ReactPointerEvent } from 'react' import clsx from 'clsx' import { @@ -67,6 +67,7 @@ function PanelRow({ id, label, wide, unpinLabel, unpinTooltip, canUnpin, usePanelInfo, selectPanel, setPinned, trackEntryClick, renderFactorySlot, }: PanelRowProps) { const active = usePanelInfo(info => info.activePanelId === id) + const trailing = useId() return (
@@ -74,6 +75,7 @@ function PanelRow({ type="button" className={css.panelRow} aria-label={label} + aria-describedby={trailing} aria-current={active ? 'page' : undefined} onClick={() => { const entry = officialEntry(id) @@ -89,6 +91,7 @@ function PanelRow({ {label} )} + {renderFactorySlot('sidebar.panel.trailing', { id, wide, active })} {wide && canUnpin && diff --git a/packages/client/ui-sidebar/src/client/contract/slots.ts b/packages/client/ui-sidebar/src/client/contract/slots.ts index b6c2288656..73c1a7b082 100644 --- a/packages/client/ui-sidebar/src/client/contract/slots.ts +++ b/packages/client/ui-sidebar/src/client/contract/slots.ts @@ -25,6 +25,12 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { props: SidebarPanelIconOwnerProps & { readonly id: string } children: { 'sidebar.panellist': { kind: 'list'; scope: 'root' } } } + /** Render a panel's trailing content in its navigation row. */ + 'sidebar.panel.trailing': { + scope: 'root' + props: SidebarPanelTrailingOwnerProps & { readonly id: string } + children: { 'sidebar.panellist.trailing': { kind: 'list'; scope: 'root'; inline: true } } + } } interface SlotMap { /** Non-interactive notification inside the collapsed sidebar expand button. */ @@ -45,6 +51,14 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { * the sidebar owns the button and resolves its label from list metadata. */ 'sidebar.panellist': { kind: 'list'; scope: 'root'; owner: SidebarPanelIconOwnerProps } + /** + * Non-interactive inline content at the end of a panel's navigation row, registered with the panel's id, such as a + * count. The expanded row lays it out after its title, before the space its unpin action takes, so a row without + * content keeps its full title width; the collapsed rail shows it over the icon's top trailing corner. It renders + * inside the row's button: its text describes that button for assistive technology, so decorative parts are + * `aria-hidden`, and it holds no interactive elements. + */ + 'sidebar.panellist.trailing': { kind: 'list'; scope: 'root'; inline: true; owner: SidebarPanelTrailingOwnerProps } /** Rows of the panel list's More menu; the sidebar shows More only while this list has registrations. */ 'sidebar.panellist.actions': { kind: 'list'; scope: 'root'; owner: SidebarPanelActionsOwnerProps } /** @@ -107,6 +121,14 @@ export interface SidebarPanelIconOwnerProps { active: boolean } +/** Row state supplied to a panel's trailing content. */ +export interface SidebarPanelTrailingOwnerProps { + /** Whether the sidebar is expanded; the collapsed rail leaves room for a mark of a few pixels only. */ + wide: boolean + /** Whether this panel is selected in the main column. */ + active: boolean +} + /** Serializable metadata for one active global panel list registration. */ export interface SidebarPanelMetadata { /** List id and matching main panel key. */ diff --git a/packages/client/ui-sidebar/src/client/index.ts b/packages/client/ui-sidebar/src/client/index.ts index 981ea23d3a..8a31e46308 100644 --- a/packages/client/ui-sidebar/src/client/index.ts +++ b/packages/client/ui-sidebar/src/client/index.ts @@ -14,7 +14,7 @@ import type { SidebarPanelMetadata, SidebarRootInjected, SidebarSectionInjected import { createPanelPins } from './panel-pins.ts' import { HeaderLeadingControls } from './HeaderLeadingControls.tsx' import { SidebarRoot } from './SidebarRoot.tsx' -import { PanelIcon } from './PanelIcon.tsx' +import { PanelIcon, PanelTrailing } from './PanelIcon.tsx' import { en, ja, es, fr, de, ru, pt, zh, type SidebarKey } from './locales.ts' export type { @@ -90,6 +90,10 @@ export function apply(ctx: ClientContext): void { name: 'sidebar.panel.icon', scope: 'root', children: { 'sidebar.panellist': { kind: 'list', scope: 'root' } }, }, PanelIcon) + yield ctx.slots.registerFactory({ + name: 'sidebar.panel.trailing', scope: 'root', + children: { 'sidebar.panellist.trailing': { kind: 'list', scope: 'root', inline: true } }, + }, PanelTrailing) yield ctx.slots.register({ name: 'sidebar', locale: NS, diff --git a/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx b/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx index 554192b591..84b73a5133 100644 --- a/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx +++ b/packages/client/ui-sidebar/tests/panel-list.client.spec.tsx @@ -511,3 +511,68 @@ describe('sidebar entry click analytics', () => { expect(layout.selectPanel).not.toHaveBeenCalled() }) }) + +/** Trailing content that names the row state it receives; its visible count is decorative and its text describes the row. */ +function Count({ wide, active }: PropsRuntime<'sidebar.panellist.trailing'>) { + return ( + + + 6 waiting + + ) +} + +async function mountCount(runtime: SlotTestRuntime, id: MainPanelId) { + return runtime.mount({ + inject: ['slots'], + apply(ctx: Context) { + ctx.slots.inject('sidebar.panellist.trailing', () => ctx.slots.register({ name: 'sidebar.panellist.trailing', id }, Count)) + }, + }) +} + +describe('sidebar panel trailing content', () => { + it('shows a panel registration in its own row only, describing the row button, and follows the selection', async () => { + const { runtime, locale, view } = await bench() + await mountPanels(runtime, locale) + await mountCount(runtime, ALPHA) + + const alpha = await view.findByRole('button', { name: 'Alpha panel' }) + const beta = view.getByRole('button', { name: 'Beta panel' }) + expect(alpha.getAttribute('aria-describedby')).not.toBeNull() + const described = document.getElementById(alpha.getAttribute('aria-describedby') ?? '') + expect(described?.textContent).toBe('66 waiting') + expect(within(described as HTMLElement).getByTestId('count').dataset).toMatchObject({ wide: 'true', active: 'false' }) + expect(document.getElementById(beta.getAttribute('aria-describedby') ?? '')?.textContent).toBe('') + expect(view.getAllByTestId('count')).toHaveLength(1) + // The content sits inside the row button after its title; the slot wrappers are inline spans, so nesting stays valid. + expect(alpha.contains(described)).toBe(true) + expect(described?.previousElementSibling?.textContent).toBe('Alpha panel') + const wrappers = [...(described?.querySelectorAll('[data-slot]') ?? [])] + expect(wrappers.length).toBeGreaterThan(0) + expect(wrappers.every(wrapper => wrapper.tagName === 'SPAN')).toBe(true) + expect(described?.querySelector('div')).toBeNull() + + fireEvent.click(alpha) + await waitFor(() => { expect(view.getByTestId('count').dataset.active).toBe('true') }) + }) + + it('tells the collapsed rail it is not wide', async () => { + const { runtime, locale, view } = await bench(true) + await mountPanels(runtime, locale) + await mountCount(runtime, BETA) + + await waitFor(() => { expect(view.getByTestId('count').dataset.wide).toBe('false') }) + }) + + it('removes the content when its registering fiber is disposed', async () => { + const { runtime, locale, view } = await bench() + await mountPanels(runtime, locale) + const count = await mountCount(runtime, ALPHA) + await view.findByTestId('count') + + await act(async () => { await count.dispose() }) + expect(view.queryByTestId('count')).toBeNull() + expect(view.getByRole('button', { name: 'Alpha panel' })).toBeTruthy() + }) +}) diff --git a/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts b/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts index d6f250313d..51cc466da6 100644 --- a/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts +++ b/packages/client/ui-sidebar/tests/sidebar-styles.client.spec.ts @@ -194,4 +194,37 @@ describe('SidebarRoot.module.css', () => { expect(declarations('.fallbackBrandName')?.get('font-size')).toBe('17px') expect(declarations('.fallbackBrandName')?.get('white-space')).toBe('nowrap') }) + + it('lays panel trailing content out after the title like a Session row, reserving no room without content', () => { + const trailing = declarations('.panelTrailing') + expect(trailing?.get('flex')).toBe('none') + expect(trailing?.get('margin-left')).toBe('auto') + expect(trailing?.has('position')).toBe(false) + expect(declarations('.panelEntryWide .panelRow')?.get('padding-right')).toBe('38px') + expect(css).not.toMatch(/\.panelTrailing:(?:not\()?:?empty/) + expect(css).not.toMatch(/\.panelRow\s*\{[^}]*padding-right:\s*72px/) + }) + + it('rests panel trailing content in the unpin action\'s place where the pointer hovers, and swaps the two on hover or keyboard focus', () => { + const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, ' ') + // The block that also reveals the unpin action on hover. + const hover = /@media \(hover: hover\) \{((?:[^{}]*\{[^{}]*\})*[^{}]*\.panelUnpin \{ opacity: 0; \}(?:[^{}]*\{[^{}]*\})*)\s*\}/.exec(withoutComments)?.[1] ?? '' + const rule = (selector: string): string => new RegExp(`${selector.replace(/[.()[\]:]/g, '\\$&')}\\s*\\{([^{}]*)\\}`).exec(hover)?.[1]?.replace(/\s+/g, ' ').trim() ?? '' + // 7px to the unpin glyph's trailing edge and 31px of content box fill the 38px a row keeps for the action elsewhere. + expect(rule('.panelEntryWide .panelRow')).toBe('padding-right: 7px;') + expect(rule('.panelEntryWide .panelTrailing')).toBe('justify-content: flex-end; min-width: 31px;') + // Only a row that has the action hides its content, on hover and on keyboard focus alike. + expect(hover.replace(/\s+/g, ' ')).toContain( + '.panelEntry:has(.panelUnpin):hover .panelTrailing, .panelEntry:has(.panelUnpin):has(:focus-visible) .panelTrailing { opacity: 0; }', + ) + // Outside that block, where the action always shows, the content stays before the 38px. + expect(withoutComments.replace(hover, '')).not.toMatch(/\.panelTrailing[^{}]*\{[^{}]*(?:opacity|min-width)/) + }) + + it('pins panel trailing content over the collapsed rail icon\'s top trailing corner', () => { + const collapsed = declarations('.collapsed .panelTrailing') + expect(collapsed?.get('position')).toBe('absolute') + expect(collapsed?.get('right')).toBe('5px') + expect(collapsed?.get('top')).toBe('5px') + }) }) diff --git a/packages/client/ui-skill/package.json b/packages/client/ui-skill/package.json index 6edd35eca7..1105c6e87b 100644 --- a/packages/client/ui-skill/package.json +++ b/packages/client/ui-skill/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-skill", "description": "Web skill references and the dedicated skill tool row", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-slots/package.json b/packages/client/ui-slots/package.json index 9a7a058e28..ee27f9fb90 100644 --- a/packages/client/ui-slots/package.json +++ b/packages/client/ui-slots/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-slots", "description": "Slot registry pure core: typed ordinary Slots and reusable Component Factories, derived props, Store seats, and renderer installation", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 855eca71ba..0666bc24d6 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: 77677cfa89b26de8 - zh: 83909430c95f3a6b + en: e912edfd1406cc33 + zh: da0a59a27fb4a65c /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: en: da87d582146106c4 zh: f640b3a3fcc11209 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index e1a6e31218..f64c1a7b2c 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -27,7 +27,7 @@ Browse local subagent conversations and external tasks in the Session panel's Su The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. Each subagent breadcrumb title is a switcher over its parent's direct catalog that marks the title's Session as current; root Sessions have no switcher. The [Session panel](../ui-session-panel/README.md#contribute-a-section) section `subagents` (order 200, titled “Subagents”) lists the current Session's direct catalog, in root and child conversations alike, when the catalog has entries or a read has failed. Showing the section reads nothing; expanding a branch prepares that branch. An absent or empty catalog hides the section and its title unless a footer contribution is available and the Session's enabled `agentTeam` projection has nondeleted shared tasks or a task-record error. Enabling Team mode alone does not show an empty section. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. Either action closes the panel's overlay or the switcher menu that holds the row. -This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. +This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. A Workspace picked in a blank child's Hero opens that Workspace's blank Session as the main Session and moves the draft to it, as the main Conversation does. The section's title control (`conversation.session.panel.section.actions`, key `subagents`) shows direct-member progress: completed, in progress, not running, and external counts in that order, with zero counts omitted and the separator matching the input task list. External tasks never count as running or completed. The section lists running subagents first, the most recently started first, and then the others, the most recently updated first. It shows five rows and then the Session panel's fold control, “Show {count} more”, which shows the rest and then reads “Show less”; the list folds only when that holds back two rows or more, the choice holds for the Session, also after the panel is hidden and shown again, and an expanded branch's own rows all show. The section hides with its title while the Session has no subagents and no failed catalog read. While direct subagents run and the panel does not show, a blue dot on the panel toggle (`conversation.session.panel.indicator`) says so and names their number for assistive technology; external tasks do not count. The Session panel scrolls the section; the tree has no nested scrolling. The breadcrumb switcher menu is 360px wide with 6px outer padding, constrained to fit the layout viewport, and only the menu scrolls. In WebKit-compatible browsers, its native 5px scrollbar sits in the right 6px inset with inset track ends and a stable gutter, preserving content width when scrolling becomes necessary. Other browsers retain their standard native scrollbar. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index eaf55b25f9..4a794b4476 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -27,7 +27,7 @@ kind: "package-reference" 会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。每个 subagent 面包屑标题都是覆盖其父会话直接目录的切换器,并把该标题对应的 Session 标为当前项;根 Session 没有切换器。[会话面板](../ui-session-panel/README.zh.md#contribute-a-section)分栏 `subagents`(order 200,标题为“子智能体”)在根会话和子会话中都列出当前 Session 的直接目录,前提是目录有子项或读取失败。显示分栏不读取任何内容;展开分支时准备该分支。目录缺席或为空时,分栏连同标题一起隐藏,除非存在可用的 footer 扩展,且 Session 已开启的 `agentTeam` 投影含有未删除的共享任务或任务记录错误。仅开启 Team 模式不会显示空分栏。选择任意深度的本地 child,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。两种操作都会关闭面板浮层或该行所在的切换器菜单。 -本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 +本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。在空白 child 的 Hero 中选择工作区时,与主 Conversation 一样,把该工作区的空白 Session 打开为主 Session,并把草稿移过去。 分栏的标题控件(`conversation.session.panel.section.actions`,键为 `subagents`)显示直接成员进度:依次为已完成、进行中、未运行和外部任务数量;省略零值,分隔符与输入区任务列表一致。外部任务不计入运行中或已完成数量。分栏把运行中的子智能体排在最前,最近开始的在前,然后是其余的,最近更新的在前。它只显示五行,然后是会话面板的收起控件「显示其余 {count} 个」,点击后显示其余的行并变为「收起」;只有能收起两行及以上时列表才收起,这个选择在 Session 内保持,隐藏后再次显示面板也不变;展开某个分支后,该分支自己的行全部显示。会话没有子智能体且目录读取未失败时,分栏连同标题一起隐藏。直接子智能体运行中且面板未显示时,面板开关上的蓝点(`conversation.session.panel.indicator`)会提示这一状态,并向辅助技术说明数量;外部任务不计入。会话面板负责分栏滚动,目录树不单独滚动。面包屑切换器菜单宽度为 360px,外层内边距为 6px,并受布局视口可用宽度约束,仅菜单本身滚动。在兼容 WebKit 的浏览器中,其原生 5px 滚动条位于右侧 6px 内边距内,轨道两端内缩,并保留稳定的滚动条空间,使内容在需要滚动时保持原有宽度。其他浏览器保留标准原生滚动条。 diff --git a/packages/client/ui-subagent/package.json b/packages/client/ui-subagent/package.json index ada7723808..1110954edd 100644 --- a/packages/client/ui-subagent/package.json +++ b/packages/client/ui-subagent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-subagent", "description": "Subagent conversation catalog, continuation routing UI, and '@' reference source", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx index 7fa90b5286..a191bb340e 100644 --- a/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx +++ b/packages/client/ui-subagent/src/client/sidebar-chat/index.tsx @@ -4,7 +4,7 @@ import type { ISessions, SessionReference, } from '@deepseek-ai/dsh-api-session-controller/client' import type { ResourceProvider } from '@deepseek-ai/dsh-client-resources/client' -import type { ConversationViewsProps } from '@deepseek-ai/dsh-client-ui-conversation/client' +import type { ConversationViewsProps, WorkspaceSelectedHandler } from '@deepseek-ai/dsh-client-ui-conversation/client' import type { SidebarRightTabDefinition } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { PropsRenderFactories, PropsRenderSlots, PropsRuntime, TranslateNS, @@ -39,7 +39,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' { interface SlotMap { /** Session-scoped Conversation occurrence hosted by one Sidebar chat tab. */ - 'sidebar.chat.conversation': { kind: 'single'; scope: 'session' } + 'sidebar.chat.conversation': { kind: 'single'; scope: 'session'; inject: SidebarChatInjected } } } @@ -117,6 +117,12 @@ function subagentChatResourceProvider(sessions: ISessions): ResourceProvider<'su } } +/** Navigation injected into the child-Session Conversation host. */ +export interface SidebarChatInjected { + /** Open the Workspace's blank Session as the main Session. */ + readonly openWorkspace: WorkspaceSelectedHandler +} + /** Fixed Chat selection used by an embedded Conversation occurrence. */ export function FixedChatConversationView(props: ConversationViewsProps) { return <>{props.renderSlot('conversation.session', { view: 'chat' })} @@ -127,7 +133,7 @@ export type ConversationSlotPanelProps = PropsRuntime<'sidebar.chat.conversation /** Render the shared Conversation content for one explicitly provided child Session. */ export function ConversationSlotPanel({ - sessionId, useSession, useConversation, useSessions, renderFactorySlot, + sessionId, useSession, useConversation, useSessions, renderFactorySlot, openWorkspace, }: ConversationSlotPanelProps) { const session = useSession(value => value) const conversation = useConversation(value => value) @@ -139,7 +145,7 @@ export function ConversationSlotPanel({ const settling = (shellPhase === 'blank' && session.openState === 'loading' && summaryBlank !== true) const hero = shellPhase === 'blank' && (session.openState === 'open' || summaryBlank === true) const phase = settling ? 'settling' : hero ? 'hero' : 'active' - return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero }, { + return renderFactorySlot('conversation.content', { variant: 'embedded', phase, hero, onWorkspaceSelected: openWorkspace }, { slots: { views: FixedChatConversationView }, }) } @@ -188,10 +194,13 @@ export function registerSidebarChat(ctx: Context, t: TranslateNS): vo : ctx.sessions.list.getSnapshot().byId[child]?.projectionValues?.subagent?.label ?? child }, } satisfies SidebarRightTabDefinition), 'ui-subagent: Sidebar chat type') + const chatInjected: SidebarChatInjected = { + openWorkspace: (workspaceId, adopt) => ctx.uiWorkspace.openWorkspace(workspaceId, adopt), + } ctx.effect(() => ctx.slots.inject('sidebar.right.pane.tab', () => ctx.slots.register({ name: 'sidebar.right.pane.tab', key: SUBAGENT_CHAT_ID, - children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session' } }, + children: { 'sidebar.chat.conversation': { kind: 'single', scope: 'session', inject: chatInjected } }, }, SidebarChatTab)), 'ui-subagent: Sidebar chat body') ctx.effect(() => ctx.slots.inject('sidebar.chat.conversation', () => ctx.slots.register({ name: 'sidebar.chat.conversation', diff --git a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx index db15c9cfe7..2ce07e3c8e 100644 --- a/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx +++ b/packages/client/ui-subagent/tests/sidebar-chat.client.spec.tsx @@ -85,6 +85,7 @@ describe('Sidebar chat registration', () => { let provider: ResourceProvider<'subagentchat'> | undefined let definition: SidebarRightTabDefinition | undefined const registrations: { options: Record; component: unknown }[] = [] + const openWorkspace = vi.fn(() => Promise.resolve()) const ctx = { sessions: { retain, refreshProjections, list } as unknown as ISessions, resources: { register: (value: ResourceProvider<'subagentchat'>) => { provider = value; return () => {} } }, @@ -99,7 +100,7 @@ describe('Sidebar chat registration', () => { effect: (install: () => unknown) => { install(); return () => {} }, } as unknown as Context - registerSidebarChat(ctx, (key: string) => key === 'sidebar.chat' ? 'Chat' : key) + registerSidebarChat(Object.assign(ctx, { uiWorkspace: { openWorkspace } }), (key: string) => key === 'sidebar.chat' ? 'Chat' : key) expect(definition?.id).toBe(SUBAGENT_CHAT_ID) expect(definition?.kind).toBe('subagentchat') @@ -112,6 +113,13 @@ describe('Sidebar chat registration', () => { 'sidebar.right.pane.tab', 'sidebar.chat.conversation', ]) + // A Workspace picked in the child's Hero opens as the main Session, as it does in the main Conversation. + const children = registrations[0]?.options.children as { + 'sidebar.chat.conversation': { inject: { openWorkspace: (workspaceId: string, adopt: () => void) => Promise } } + } + const adopt = vi.fn() + await children['sidebar.chat.conversation'].inject.openWorkspace('workspace-1', adopt) + expect(openWorkspace).toHaveBeenCalledWith('workspace-1', adopt) const controller = new AbortController() const stream = provider!.open(subagentChatAddress(ADDRESS), { signal: controller.signal })[Symbol.asyncIterator]() @@ -204,6 +212,7 @@ describe('Sidebar chat components', () => { ])('derives the $name embedded phase and fixes the local view to Chat', ({ session: patch, summaryBlank, expected }) => { const snapshot = { ...sessionSnapshot(CHILD), ...patch } as SessionSnapshot const renderFactorySlot = vi.fn(() => null) + const openWorkspace = vi.fn() render( unknown) => select(snapshot), @@ -212,10 +221,10 @@ describe('Sidebar chat components', () => { ids: [], byId: { [CHILD]: { blank: summaryBlank } }, phase: 'ready', projectionsBySession: {}, jobsBySession: {}, } as unknown as SessionListState), renderFactorySlot, - } as unknown as Parameters[0])} />) + } as unknown as Parameters[0])} openWorkspace={openWorkspace} />) expect(renderFactorySlot).toHaveBeenCalledWith( 'conversation.content', - { variant: 'embedded', ...expected }, + { variant: 'embedded', ...expected, onWorkspaceSelected: openWorkspace }, { slots: { views: FixedChatConversationView } }, ) }) diff --git a/packages/client/ui-theme/package.json b/packages/client/ui-theme/package.json index f8966642c0..9f9cb122ee 100644 --- a/packages/client/ui-theme/package.json +++ b/packages/client/ui-theme/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-theme", "description": "Theme plugin: Host bootstrap for the pre-plugin palette; ThemeRuntime for light/dark/system state and icon replacements; --dsw-* token styles and Appearance settings row", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-tool/package.json b/packages/client/ui-tool/package.json index b4d4f4d714..bf92854934 100644 --- a/packages/client/ui-tool/package.json +++ b/packages/client/ui-tool/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-tool", "description": "Client Tool call-tree renderer and keyed per-tool presentation slot", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-tool/src/client/tool/file-menu.ts b/packages/client/ui-tool/src/client/tool/file-menu.ts index 0b0e5377fd..1010046924 100644 --- a/packages/client/ui-tool/src/client/tool/file-menu.ts +++ b/packages/client/ui-tool/src/client/tool/file-menu.ts @@ -1,7 +1,7 @@ /** Tool-owned path resolution supplied by the existing toolview registration. */ import type { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' /** File paths are resolved when a gesture begins, not when the Slot is mounted. */ @@ -17,10 +17,6 @@ export interface ToolFileInjected { */ export function toolFileInject(ctx: Context): (sessionId: SessionId) => ToolFileInjected { return sessionId => ({ - resolveFilePath: (path) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - return resolveWorkspacePath(current ?? cwd, path) - }, + resolveFilePath: path => resolveWorkspacePath(sessionDirectory(ctx.sessions, sessionId), path), }) } diff --git a/packages/client/ui-trajectory/package.json b/packages/client/ui-trajectory/package.json index 5ecc2ba56f..d6cd8d045e 100644 --- a/packages/client/ui-trajectory/package.json +++ b/packages/client/ui-trajectory/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-trajectory", "description": "Trajectory event ledger and timing overview with live tool-result inspection", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-user-questions/package.json b/packages/client/ui-user-questions/package.json index 252354c08f..2683bda671 100644 --- a/packages/client/ui-user-questions/package.json +++ b/packages/client/ui-user-questions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-user-questions", "description": "Web ask_user_question composer takeover and plan-review presentation UI", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-workflow-run/package.json b/packages/client/ui-workflow-run/package.json index fa43d8f779..6835568b46 100644 --- a/packages/client/ui-workflow-run/package.json +++ b/packages/client/ui-workflow-run/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workflow-run", "description": "Durable workflow-run Conversation Node and nested member disclosure for dsh web", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index 35fd56d63a..1c25042a12 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-ui-workspace", "description": "Workspace picker plugin: one WorkspacePicker registered into the sidebar and empty-state workspace slots", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 262cf9b22b..e432390961 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -6,6 +6,7 @@ import { type SessionListState, type SessionSearchResultItem, type SessionSummary, } from '@deepseek-ai/dsh-api-session-controller/client' +import { selectSessionDirectory } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot, @@ -62,7 +63,7 @@ export interface SessionNode { /** In the registry-global archive set: shown grayed in place and not openable. */ archived: boolean updatedAt: number - /** Session working directory; absent when the Host reports none or an empty path. */ + /** Workspace root the Session works in; absent when the Host reports none or an empty path. */ cwd?: string } @@ -399,6 +400,8 @@ function sessionNode( ): SessionNode { const status = statuses.get(s.id) const pendingInteraction = visiblePendingKind(status?.pendingInteraction?.kind) + // Rows show the checkout the Session works in; grouping stays with the header's original project. + const root = selectSessionDirectory(list, s.id) return { id: s.id, title: sessionTitle(s), @@ -410,7 +413,7 @@ function sessionNode( pinned: !archived.has(s.id) && pinned.has(s.id), archived: archived.has(s.id), updatedAt: s.updatedAt, - ...(s.cwd === undefined || s.cwd === '' ? {} : { cwd: s.cwd }), + ...(root === undefined || root === '' ? {} : { cwd: root }), ...(pendingInteraction === undefined ? {} : { pendingInteraction }), } } diff --git a/packages/client/web/package.json b/packages/client/web/package.json index 22b3aece96..8f51e0c4bd 100644 --- a/packages/client/web/package.json +++ b/packages/client/web/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-client-web", "description": "Web boot kernel: static module table, Cordis loader, framework-free boot page, and UI-renderer handoff", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/command-compact/package.json b/packages/compaction/command-compact/package.json index 9dd11ee681..89eef814e8 100644 --- a/packages/compaction/command-compact/package.json +++ b/packages/compaction/command-compact/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-command-compact", "description": "Human-facing slash command for explicit session compaction", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-basic/package.json b/packages/compaction/compaction-basic/package.json index 88075500ae..4d0fae98c1 100644 --- a/packages/compaction/compaction-basic/package.json +++ b/packages/compaction/compaction-basic/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-basic", "description": "Token-meter-driven compaction policy and LLM summarization backend for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-image-offload/package.json b/packages/compaction/compaction-image-offload/package.json index 8874fc61d5..de8a095a2b 100644 --- a/packages/compaction/compaction-image-offload/package.json +++ b/packages/compaction/compaction-image-offload/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-image-offload", "description": "Durable image offload for image-capable routes: replace over-budget request images with placeholders and retry", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction-tool-result-pruner/package.json b/packages/compaction/compaction-tool-result-pruner/package.json index 1d35fd0330..7db5ac461c 100644 --- a/packages/compaction/compaction-tool-result-pruner/package.json +++ b/packages/compaction/compaction-tool-result-pruner/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction-tool-result-pruner", "description": "Replay-safe model-free head/middle/tail pruning for tool-result surface nodes", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/compaction/compaction/package.json b/packages/compaction/compaction/package.json index 2a0798e0b4..4aee931986 100644 --- a/packages/compaction/compaction/package.json +++ b/packages/compaction/compaction/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-compaction", "description": "Abstract compaction service seam (ctx.compaction) for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/computer-use/computer-use/package.json b/packages/computer-use/computer-use/package.json index ef13439913..288fe0e093 100644 --- a/packages/computer-use/computer-use/package.json +++ b/packages/computer-use/computer-use/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-computer-use", "description": "Exclusive named computer-use provider registration", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/connector/README.i18n.yaml b/packages/connector/README.i18n.yaml index 6d803ef444..4c69b92966 100644 --- a/packages/connector/README.i18n.yaml +++ b/packages/connector/README.i18n.yaml @@ -3,23 +3,23 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/connector/README.md /: - en: 689ac98272d5e23e - zh: c33789dd190f3f43 + en: 7858f8c6b44c6cbd + zh: 7d12cc2c00869507 /connector-application-plugins: en: ef6d2dd74a9b63e0 zh: 2d1b1b1d6de9d5af /connector-application-plugins/summary: - en: ef4e05f7ba8ec163 - zh: 12251f9a81082730 + en: aac8c492c68154ca + zh: f76fa8d4958e4ca0 /connector-application-plugins/table-of-contents: en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /connector-application-plugins/packages: - en: 066c2f08376b0407 - zh: 22190e3850b59561 + en: b0c2e4f71be135a1 + zh: 69d937a6ab40d612 /connector-application-plugins/related-documentation: - en: 392c28cfa4bafb27 - zh: c49329900f6f2fd0 + en: a8c37c85ac7dfaf1 + zh: 9f894caf2f0322c2 /connector-application-plugins/dev-note: en: 5de1d6304e00c58f zh: 3fee785f424f1018 diff --git a/packages/connector/README.md b/packages/connector/README.md index f184c618d4..24b26764a1 100644 --- a/packages/connector/README.md +++ b/packages/connector/README.md @@ -1,5 +1,5 @@ --- -description: "The connector group map: application plugins that connect a third-party service to agents through existing Skill, Shell, and subprocess capabilities, and the CLI account and upstream skills Services they register with." +description: "The connector group map: application plugins that connect a third-party service to agents through existing Skill, MCP, Shell, and subprocess capabilities, and the CLI account and upstream skills Services that CLI app plugins register with." kind: "package-group" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Each application plugin in this group is installed into a profile to use one third-party service in conversations. A plugin composes existing capabilities, such as skills, runtime context, and subprocesses, and keeps application-specific configuration and model guidance in its own package. Plugins whose vendor CLI keeps the user's account register that CLI and account with the CLI account Service, which runs their commands and account operations, and plugins whose upstream skills exist only in the vendor's GitHub repository register their entry skill with the upstream skills Service, which downloads them. +Each application plugin in this group is installed into a profile to use one third-party service in conversations. A plugin composes existing capabilities, such as skills, MCP servers registered with the shared manager, runtime context, and subprocesses, and keeps application-specific configuration and model guidance in its own package. Plugins whose vendor CLI keeps the user's account register that CLI and account with the CLI account Service, which runs their commands and account operations, and plugins whose upstream skills exist only in the vendor's GitHub repository register their entry skill with the upstream skills Service, which downloads them. ## Table of Contents @@ -25,8 +25,14 @@ Each application plugin in this group is installed into a profile to use one thi | Package | Role | ctx key | |---|---|---| | [`cli-account/`](cli-account/README.md) | Holds the vendor CLIs and accounts CLI app plugins register: gives the model each CLI's absolute path in runtime context, runs each plugin's account operations one at a time, and shows the account on the Plugins page | `ctx.cliAccounts` | +| [`feishu/`](feishu/README.md) | The Feishu plugin: installs the official `lark-cli`, gives the model its absolute path, registers its embedded skills, and runs the account operations the Plugins page drives | registers on `ctx.cliAccounts` and `ctx.skills` | +| [`tencent-meeting/`](tencent-meeting/README.md) | The Tencent Meeting plugin: installs the official `tmeet`, gives the model its absolute path, registers its skill, and runs the account operations the Plugins page drives | registers on `ctx.cliAccounts` and `ctx.upstreamSkills` | | [`dingtalk/`](dingtalk/README.md) | The DingTalk plugin: downloads the pinned official `dws` and its skills, gives the model the absolute path of `dws`, registers its skill, and runs the account operations the Plugins page drives | registers on `ctx.cliAccounts` and `ctx.skills` | | [`upstream-skills/`](upstream-skills/README.md) | Holds the entry skills CLI app plugins register: downloads the upstream files each entry indexes from a pinned commit of the vendor's GitHub repository, verifies and caches them, and lists the entry skill over them | `ctx.upstreamSkills` | +| [`linear/`](linear/README.md) | Registers Linear's hosted MCP server with OAuth through the shared MCP manager, adds the Linear plugin naming guidance, and shows its account on the plugin page | registers on `ctx.mcpManager`, `ctx.systemPrompt`, and `ctx.mcpAccounts` | +| [`notion/`](notion/README.md) | Registers Notion's hosted MCP server with OAuth through the shared MCP manager, adds the Notion plugin naming guidance, and shows its account on the plugin page | registers on `ctx.mcpManager`, `ctx.systemPrompt`, and `ctx.mcpAccounts` | +| [`tencent-docs/`](tencent-docs/README.md) | Registers Tencent Docs' hosted MCP server with OAuth through the shared MCP manager, adds the Tencent Docs plugin naming guidance, and shows its account on the plugin page | registers on `ctx.mcpManager`, `ctx.systemPrompt`, and `ctx.mcpAccounts` | +| [`wecom/`](wecom/README.md) | The WeCom plugin: installs the official `wecom-cli`, gives the model its absolute path, registers its skills, and runs the authorization operations the Plugins page drives | registers on `ctx.cliAccounts` and `ctx.upstreamSkills` | ----- @@ -36,6 +42,8 @@ Each application plugin in this group is installed into a profile to use one thi - [Skill subsystem reference](../../docs/subsystems/skills.md) — the registry and provider contract that connector skills use. - [System prompt](../core/system-prompt/README.md) — the registry that orders and renders runtime context. - [Connector account surfaces](../client/ui-connector-account/README.md) — the Plugins page registry where CLI app plugins show their accounts. +- [MCP subsystem reference](../../docs/subsystems/mcp.md) — the MCP packages that connector servers use. +- [MCP manager](../mcp/mcp-manager/README.md) — plugin-registered servers, status, and OAuth authorization. ----- diff --git a/packages/connector/README.zh.md b/packages/connector/README.zh.md index cbd15c33f3..fc4468d168 100644 --- a/packages/connector/README.zh.md +++ b/packages/connector/README.zh.md @@ -1,5 +1,5 @@ --- -description: "connector 分组地图:通过现有 Skill、Shell 与 subprocess 能力把第三方服务接入 agent 的应用插件,以及它们注册到的 CLI 账号 Service 和上游技能 Service。" +description: "connector 分组地图:通过现有 Skill、MCP、Shell 与 subprocess 能力把第三方服务接入 agent 的应用插件,以及 CLI 应用插件注册到的 CLI 账号 Service 和上游技能 Service。" kind: "package-group" --- @@ -9,7 +9,7 @@ kind: "package-group" ## 概述 -本分组中的每个应用插件安装到 profile 后,即可在对话中使用一个第三方服务。插件组合 skill(技能)、运行时上下文和 subprocess 等现有能力,并把应用特有的配置和模型指引保留在自己的包内。由厂商 CLI 保管用户账号的插件,把这个 CLI 和账号注册到 CLI 账号 Service,由它执行插件的命令和账号操作;上游技能只存在于厂商 GitHub 仓库的插件,把入口技能注册到上游技能 Service,由它下载这些技能。 +本分组中的每个应用插件安装到 profile 后,即可在对话中使用一个第三方服务。插件组合 skill(技能)、注册到共用管理器的 MCP 服务器、运行时上下文和 subprocess 等现有能力,并把应用特有的配置和模型指引保留在自己的包内。由厂商 CLI 保管用户账号的插件,把这个 CLI 和账号注册到 CLI 账号 Service,由它执行插件的命令和账号操作;上游技能只存在于厂商 GitHub 仓库的插件,把入口技能注册到上游技能 Service,由它下载这些技能。 ## 目录 @@ -25,8 +25,14 @@ kind: "package-group" | 包 | 职责 | ctx 键 | |---|---|---| | [`cli-account/`](cli-account/README.zh.md) | 保存 CLI 应用插件注册的厂商 CLI 和账号:在运行时上下文中把每个 CLI 的绝对路径告诉模型,让每个插件的账号操作一次只执行一个,并在插件页显示账号 | `ctx.cliAccounts` | +| [`feishu/`](feishu/README.zh.md) | 飞书插件:安装官方 `lark-cli`,把它的绝对路径告诉模型,注册其内嵌 skill,并执行插件页发起的账号操作 | 注册到 `ctx.cliAccounts` 与 `ctx.skills` | +| [`tencent-meeting/`](tencent-meeting/README.zh.md) | 腾讯会议插件:安装官方 `tmeet`,把它的绝对路径告诉模型,注册其 skill,并执行插件页发起的账号操作 | 注册到 `ctx.cliAccounts` 与 `ctx.upstreamSkills` | | [`dingtalk/`](dingtalk/README.zh.md) | 钉钉插件:下载固定版本的官方 `dws` 及其技能,把 `dws` 的绝对路径告诉模型,注册其 skill,并执行插件页发起的账号操作 | 注册到 `ctx.cliAccounts` 与 `ctx.skills` | | [`upstream-skills/`](upstream-skills/README.zh.md) | 保存 CLI 应用插件注册的入口技能:从厂商 GitHub 仓库的固定提交下载每个入口索引的上游文件,校验并缓存,再在这些文件之上列出入口技能 | `ctx.upstreamSkills` | +| [`linear/`](linear/README.zh.md) | 通过共用的 MCP 管理器以 OAuth 注册 Linear 托管的 MCP 服务器,添加 Linear 插件称呼指引,并在插件页面显示账号 | 注册到 `ctx.mcpManager`、`ctx.systemPrompt` 与 `ctx.mcpAccounts` | +| [`notion/`](notion/README.zh.md) | 通过共用的 MCP 管理器以 OAuth 注册 Notion 托管的 MCP 服务器,添加 Notion 插件称呼指引,并在插件页面显示账号 | 注册到 `ctx.mcpManager`、`ctx.systemPrompt` 与 `ctx.mcpAccounts` | +| [`tencent-docs/`](tencent-docs/README.zh.md) | 通过共用的 MCP 管理器以 OAuth 注册腾讯文档托管的 MCP 服务器,添加腾讯文档插件称呼指引,并在插件页面显示账号 | 注册到 `ctx.mcpManager`、`ctx.systemPrompt` 与 `ctx.mcpAccounts` | +| [`wecom/`](wecom/README.zh.md) | 企业微信插件:安装官方 `wecom-cli`,把它的绝对路径告诉模型,注册其 skill,并执行插件页发起的授权操作 | 注册到 `ctx.cliAccounts` 与 `ctx.upstreamSkills` | ----- @@ -36,6 +42,8 @@ kind: "package-group" - [Skill 子系统参考](../../docs/subsystems/skills.zh.md)——connector skill 使用的注册表与提供方契约。 - [System prompt](../core/system-prompt/README.zh.md)——排序并渲染运行时上下文的注册表。 - [连接器账号界面](../client/ui-connector-account/README.zh.md)——CLI 应用插件在插件页显示账号的注册表。 +- [MCP 子系统参考](../../docs/subsystems/mcp.zh.md)——connector 服务器所使用的 MCP 包。 +- [MCP 管理器](../mcp/mcp-manager/README.zh.md)——插件注册的服务器、状态与 OAuth 授权。 ----- diff --git a/packages/connector/cli-account/package.json b/packages/connector/cli-account/package.json index 9068c1b9a6..2acc1a3ab0 100644 --- a/packages/connector/cli-account/package.json +++ b/packages/connector/cli-account/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-cli-account", "description": "Host Service of CLI app plugins: each plugin registers its third-party CLI and account, and the Service gives the model the CLI's absolute path, runs one account operation at a time, and shows the account on the Plugins page", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/connector/feishu/README.i18n.yaml b/packages/connector/feishu/README.i18n.yaml new file mode 100644 index 0000000000..55ff46ab77 --- /dev/null +++ b/packages/connector/feishu/README.i18n.yaml @@ -0,0 +1,91 @@ +# 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/connector/feishu/README.md +/: + en: 2264374cd0367ea0 + zh: 44bbf2e3b393d790 +/deepseek-ai-dsh-feishu: + en: 5b26d6ad2128b454 + zh: 6d3ccfcdb716ef8d +/deepseek-ai-dsh-feishu/summary: + en: a07d30fd633d14b8 + zh: d78e326c5edcde47 +/deepseek-ai-dsh-feishu/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-feishu/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-feishu/use-this-package/install-into-a-profile: + en: 756d8e3c33815f24 + zh: 7f6a3fcfef92c6b8 +/deepseek-ai-dsh-feishu/use-this-package/what-you-get: + en: 55d9fdc4ef0be522 + zh: 8063b8baa6c42776 +/deepseek-ai-dsh-feishu/use-this-package/account-operations: + en: 4b5f07c32cac8141 + zh: 473a23f50efa5947 +/deepseek-ai-dsh-feishu/use-this-package/configure: + en: 7791974428fc09cb + zh: 62bb720d2b4842be +/deepseek-ai-dsh-feishu/understand-the-implementation: + en: f8f0f9cb9eb55960 + zh: 05f09e2198565082 +/deepseek-ai-dsh-feishu/further-exploration: + en: b25e4caa8c5b7116 + zh: 4976eddc4b3e5ec4 +/deepseek-ai-dsh-feishu/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry: + en: a861712b6b65f49a + zh: 3447e587c56a25d6 +/deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/what-the-model-sees: + en: 0a73c38722f334ac + zh: 56d0060443414c9a +/deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/what-the-model-sees/catalog-description: + en: 8ff7f9b51a85c5b5 + zh: 55e58973015e27f7 +/deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/token-effect: + en: 7bd1792c4c56e682 + zh: 94be77d208dddc69 +/deepseek-ai-dsh-feishu/model-experience/skill-catalog-entry/kv-cache-effect: + en: 09346f854e96f385 + zh: c2fa26fbcd1cd6f1 +/deepseek-ai-dsh-feishu/model-experience/loaded-skill-body: + en: 8955ac196848e69f + zh: 54aa7db097eafd3c +/deepseek-ai-dsh-feishu/model-experience/loaded-skill-body/what-the-model-sees: + en: 1f22e390a5ac1f35 + zh: 305341c3bfb1758d +/deepseek-ai-dsh-feishu/model-experience/loaded-skill-body/token-effect: + en: f19372aa372976da + zh: 647eef6b6980db49 +/deepseek-ai-dsh-feishu/model-experience/loaded-skill-body/kv-cache-effect: + en: 1f6b842a95e14ce4 + zh: 0d57cdec5e828828 +/deepseek-ai-dsh-feishu/model-experience/cli-path: + en: b5fed52af6c0d771 + zh: 25b7aa5297583030 +/deepseek-ai-dsh-feishu/model-experience/cli-path/what-the-model-sees: + en: fb721433c0dec520 + zh: 7b17e45979e2fdca +/deepseek-ai-dsh-feishu/model-experience/cli-path/what-the-model-sees/runtime-context-entry: + en: c91314832f78f460 + zh: aac156ea0b5b816a +/deepseek-ai-dsh-feishu/model-experience/cli-path/what-the-model-sees/runtime-context-entry-on-windows: + en: 54f899bbaf7ed198 + zh: 31256473a192427b +/deepseek-ai-dsh-feishu/model-experience/cli-path/token-effect: + en: 2952585b710ffd05 + zh: 6e93e58b6256d534 +/deepseek-ai-dsh-feishu/model-experience/cli-path/kv-cache-effect: + en: 67398dd4e4b02db9 + zh: a873eacd006fa656 +/deepseek-ai-dsh-feishu/known-limitations-and-deferred-work: + en: 95d813f5fe6e7cb2 + zh: c65fcf992ac18b69 +/deepseek-ai-dsh-feishu/known-limitations-and-deferred-work/dev-note: + en: be15f75bf32de641 + zh: 85de42dc5e1d934b diff --git a/packages/connector/feishu/README.md b/packages/connector/feishu/README.md new file mode 100644 index 0000000000..6da72a2d2c --- /dev/null +++ b/packages/connector/feishu/README.md @@ -0,0 +1,179 @@ +--- +description: "Add the Feishu plugin to a profile: the official lark-cli with its embedded skills, and Feishu account connection on the Plugins page." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-feishu + +English | [中文](README.zh.md) + +## Summary + +The Feishu plugin lets conversations use Feishu through the official `lark-cli`. It installs a pinned `@larksuite/cli`, gives the model the absolute path of its `lark-cli` executable in runtime context, and registers one `feishu` skill that indexes the guides embedded in that CLI. It registers the account with the [connector account registry](../../client/ui-connector-account/README.md), whose Plugins page section checks the default account, links an app and signs in through the CLI's browser flows, signs out, and cancels. The CLI keeps credentials in its default configuration, which the user's own terminal shares. Only macOS and Windows x64 are supported. + +## 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 + +### Install into a profile + +Install the plugin from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-feishu +dsh plugin --profile web remove @deepseek-ai/dsh-feishu +``` + +pnpm blocks the `@larksuite/cli` install script, which downloads and verifies the official native binary; approve it through the Plugins page's **Allow these scripts and retry** or the other paths that [Plugin Manager](../../boot/plugin-manager/README.md) documents. Until the executable exists, the `feishu` row fails to load with an error that names the missing path. + +### What you get + +After the plugin loads, one `feishu` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the guide it needs, such as `lark-doc` or `lark-shared`, with `lark-cli skills read`, and runs `lark-cli` by that path through the ordinary Shell tools under the current sandbox and approval policy. When a command reports a missing app configuration or sign-in, the agent asks the user to connect Feishu on the plugin page; it runs the CLI's own setup and sign-in flow only when the user asks to finish it in the conversation. Commands that save sign-in state ask for single-command approval because they write outside the workspace. + +Turning the plugin off in Plugin Manager withdraws the `feishu` skill, the path from runtime context, and the account section. The CLI configuration and sign-in stay in place. + + +### Account operations + +The Plugins page drives these operations through the connector account registry, which the Web app loads; a headless profile loads the plugin without it. The Host runs at most one account operation at a time and owns it, so leaving the page does not cancel it. Linking an app and signing in are separate operations, so the page starts each one from its own click. + +| Operation | Effect | +|---|---| +| `check` | Checks the account again; each browser that opens the Web app starts one when no operation runs | +| `link-app` | Runs `config init --new`, which replaces the CLI's default configuration, including its sign-ins and any other app, with the app the user creates or chooses; it does not sign in. Replacing a linked app asks first | +| `sign-in` | Runs `auth login --json` for the linked app and checks that the same user is signed in | +| `sign-out` | After the user confirms, runs `auth logout --json`, which also signs out the user's own terminal, then checks again | +| Cancel | Cancels the operation during app setup or sign-in and waits for its command to exit; other steps are ignored | + +A check runs `auth status --verify --json`. The account reads `connected` only when the CLI reports an available user that its server verified, `signed-out` when the user is missing, not configured, or needs a refresh, `unconfigured` when no app exists, and `unverified` otherwise, for example when verification cannot reach the server. Every state except `unconfigured` carries the configured `appId`. Each link that `config init` prints and each device-authorization link that `auth login` reports is offered only when it is an HTTPS address on `feishu.cn` or `larksuite.com`. A sign-in that leaves requested permissions ungranted (`auth login` exits with code 3 and lists them as missing) still succeeds; a command that later needs a missing permission reports it. Results report succeeded, cancelled, or failed. Failures show the command and observed exit code on the page and in the Host log; native messages, paths, and authorization data are omitted. A successful Feishu webpage does not confirm that local credentials were saved. The process running DSH needs access to the CLI configuration and system credential storage; `DSH_HOME` does not relocate either. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `binDir` | the installed `@larksuite/cli` package's `bin` | Absolute directory containing an executable `lark-cli`, `lark-cli.exe` on Windows | + +An account check or sign-out gets the `commandTimeoutMs` of the [`cli-account` row](../cli-account/README.md#use-this-package), 30 seconds by default. App setup and sign-in wait up to 10 minutes for the user in the browser, and each command keeps at most 1 MiB of stdout; the CLI account Service fixes both limits. + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-feishu) is the exhaustive source of supported fields. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `feishu` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It checks that `binDir/lark-cli` (`lark-cli.exe` on Windows) is executable, registers that path and the account with `ctx.cliAccounts`, and registers the skill provider. [`src/cli.ts`](src/cli.ts) locates `lark-cli` and parses the JSON output of its account commands. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one account operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the Feishu commands and reads setup and sign-in links from their output lines. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. + +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the 28 guides that `lark-cli` 1.0.97 embeds, and how to open them. [`src/skills.ts`](src/skills.ts) reads the entry once when the plugin loads and lists it as the `feishu` provider's one skill with an opaque resource base, so the catalog lists the entry and a load returns the file without running the CLI. The guides stay in the binary, and the agent reads them with `lark-cli skills read`. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [CLI account Service](../cli-account/README.md) — command execution, the CLI path context, and account operations shared by CLI app plugins. +- [Skills](../../../docs/subsystems/skills.md) — catalog publication, loading, and precedence. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the registry and the Plugins page section that drive the account operations. +- [Plugin Manager](../../boot/plugin-manager/README.md) — installation, build-script approval, and enablement. + +----- + + +## Model Experience + +### Skill catalog entry + +#### What the model sees + +One `feishu` entry appears in the skill catalog with the description below. + +##### Catalog description + +```markdown +Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, sheets, slides, Drive files, messages and group chats, calendar, video meetings and minutes, tasks, approvals, mail, contacts, OKR, attendance, events, and the CLI's app setup and sign-in. Load it before any Feishu or Lark task; it indexes the guides and how to open them. +``` + +#### Token effect + +The entry stays in context while the plugin is loaded, at about 350 characters. + +#### KV Cache effect + +The entry is fixed. Loading or unloading the plugin changes the catalog, which is republished as a new message and leaves earlier context in place. + +### Loaded skill body + +#### What the model sees + +A `skill` tool result for `feishu` contains about 6,700 characters: the DSH guidance, an index that gives each of the 28 guides embedded in `lark-cli` 1.0.97 one line with its routing rules, and how to open a guide. The DSH guidance tells the agent to run `lark-cli` by the absolute path from the current runtime context, to ask the user to connect Feishu on the plugin page before running the CLI's setup and sign-in flow itself, and to set the narrowest `sandbox_permissions` for the commands that save sign-in state. The opening instructions tell the agent that the guides are not skills and that it reads a guide, and the files a guide references, with `lark-cli skills read`. Its resource description reads `Embedded lark-cli guides; open them with the skills read command given in the loaded skill.` + +#### Token effect + +Each load adds the entry body to the retained tool history. Guides and the files they reference arrive as ordinary Shell output when the agent reads them through `lark-cli`. + +#### KV Cache effect + +Loading appends a tool result and does not rewrite earlier context. + +### CLI path + +#### What the model sees + +While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `lark-cli` in `binDir`, which defaults to the installed `@larksuite/cli` package's `bin` directory. + +##### Runtime-context entry + +```markdown +Feishu CLI: run `lark-cli` by its absolute path "/lark-cli"; the bare name may resolve to another installation or to none. +``` + +##### Runtime-context entry on Windows + +```markdown +Feishu CLI: run `lark-cli` by its absolute path with the call operator, & '\lark-cli.exe'; the bare name may resolve to another installation or to none. +``` + +#### Token effect + +One line of about 110 characters plus the path in each runtime-context snapshot. + +#### KV Cache effect + +The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. + +## Known Limitations and Deferred Work + + + +- Only macOS and Windows x64 are supported; other platforms are unverified. +- Commands must run on this Host. When a composition runs them elsewhere, such as over SSH, the plugin still loads, and each command that runs `lark-cli` fails because the path does not exist there. +- The plugin uses the CLI's default configuration. Signing in or out from DSH affects the user's own terminal, and there is no DSH-private account or account picker. The plugin offers no unbind operation; turning it off keeps the configuration and sign-in. +- Sign-in reads the device-authorization link and the completion from `lark-cli auth login --json` events; a CLI version that changes those events fails the connection with a retryable result. +- The entry's guide index follows `lark-cli` 1.0.97; pinning another `@larksuite/cli` version means checking the index against that version's `lark-cli skills list`. +- Under a file sandbox, a token refresh during an ordinary command can be denied and then needs single-command approval. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Repository installs deny the `@larksuite/cli` install script in the root `pnpm-workspace.yaml`, so a checkout has no native binary. To run the plugin from source against the real CLI, run `node packages/connector/feishu/node_modules/@larksuite/cli/scripts/install.js` once. Specs and the `feishu-skills` session snapshot use stand-in executables through `binDir`. + +
diff --git a/packages/connector/feishu/README.zh.md b/packages/connector/feishu/README.zh.md new file mode 100644 index 0000000000..b773af156a --- /dev/null +++ b/packages/connector/feishu/README.zh.md @@ -0,0 +1,179 @@ +--- +description: "把飞书插件加入 profile:带内嵌技能的官方 lark-cli,以及插件页上的飞书账号连接。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-feishu + +[English](README.md) | 中文 + +## 概述 + +飞书插件让对话通过官方 `lark-cli` 使用飞书。它安装固定版本的 `@larksuite/cli`,在运行时上下文中把其 `lark-cli` 可执行文件的绝对路径告诉模型,并注册一个 `feishu` skill,为该 CLI 内嵌的子指南提供索引。它把账号注册到 [连接器账号注册表](../../client/ui-connector-account/README.zh.md),其插件页区块负责检查默认账号、通过 CLI 的浏览器流程关联应用并登录、退出登录以及取消操作。CLI 把凭据保存在默认配置中,用户自己的终端也共用这份配置。仅支持 macOS 和 Windows x64。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +在 Web 侧栏的**插件**页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-feishu +dsh plugin --profile web remove @deepseek-ai/dsh-feishu +``` + +pnpm 会拦截 `@larksuite/cli` 的安装脚本,该脚本负责下载并校验官方原生程序;请通过插件页的**允许这些脚本并重试**,或 [Plugin Manager](../../boot/plugin-manager/README.zh.md) 记录的其他方式批准。可执行文件存在之前,`feishu` 行会加载失败,并给出缺失的路径。 + +### 获得的能力 + +插件加载后,一个 `feishu` skill 进入 skill 目录。agent 用 `skill` 工具加载它,用 `lark-cli skills read` 打开所需的子指南(例如 `lark-doc` 或 `lark-shared`),并在当前沙箱与审批策略下通过普通 Shell 工具按这个路径运行 `lark-cli`。命令报告缺少应用配置或登录时,agent 会请用户到插件页连接飞书;只有用户要求在对话中完成时,才按 CLI 自带的流程配置和登录。保存登录状态的命令会在工作区之外写入,因此会申请单条命令审批。 + +在 Plugin Manager 中关闭插件会撤下 `feishu` skill、运行时上下文中的路径和账号区块,CLI 配置与登录保持不变。 + + +### 账号操作 + +插件页通过 连接器账号注册表发起这些操作,注册表由 Web 应用加载;headless profile 加载插件时没有它。Host 同一时间最多运行一个账号操作并持有它,因此离开页面不会取消操作。关联应用和登录是两个独立操作,页面分别由各自的一次点击发起。 + +| 操作 | 作用 | +|---|---| +| `check` | 重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `link-app` | 运行 `config init --new`,用用户新建或选择的应用替换 CLI 的默认配置,其中的登录和其他应用一并替换;不会登录。更换已关联的应用前会先询问 | +| `sign-in` | 为已关联的应用运行 `auth login --json`,并确认登录的是同一个用户 | +| `sign-out` | 用户确认后运行 `auth logout --json`,同时退出用户自己终端里的登录,然后重新检查 | +| 取消 | 在应用配置或登录期间取消操作并等待其命令退出;其他步骤会被忽略 | + +检查运行 `auth status --verify --json`。只有 CLI 报告用户可用且已被服务端核实时,账号才是 `connected`;用户缺失、未配置或需要刷新时为 `signed-out`;没有应用时为 `unconfigured`;其他情况为 `unverified`,例如核实时无法连到服务端。除 `unconfigured` 外,每种状态都带有已配置的 `appId`。`config init` 打印的链接和 `auth login` 报告的设备授权链接,只有是 `feishu.cn` 或 `larksuite.com` 上的 HTTPS 地址时才会提供。登录后仍有申请的权限未被授予时(`auth login` 以退出码 3 结束并把它们列为缺失),登录仍算成功;之后需要这些权限的命令会报告缺少哪些。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;原生消息、路径和授权数据均不保留。飞书网页显示成功不代表本地凭据已保存。运行 DSH 的进程需要能访问 CLI 配置和系统凭据存储;`DSH_HOME` 不会迁移这两者。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `binDir` | 已安装 `@larksuite/cli` 包的 `bin` | 包含可执行 `lark-cli`(Windows 上为 `lark-cli.exe`)的绝对目录 | + +账号检查和退出登录使用 [`cli-account` 行](../cli-account/README.zh.md#use-this-package)的 `commandTimeoutMs`,默认 30 秒。应用配置和登录最多等待用户在浏览器中操作 10 分钟,每条命令最多保留 1 MiB 的 stdout;这两个上限由 CLI 账号 Service 固定。 + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-feishu)是受支持字段的完整来源。 + +----- + + +## 理解实现 + +
+实现内部机制——点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `feishu` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它检查 `binDir/lark-cli`(Windows 上为 `lark-cli.exe`)是否可执行,把这个路径和账号注册到 `ctx.cliAccounts`,并注册 skill 提供方。[`src/cli.ts`](src/cli.ts) 定位 `lark-cli` 并解析账号命令的 JSON 输出。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个账号操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用飞书的命令完成每个操作,并从命令输出行中读取配置与登录链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令,并在这些进程退出后完成。 + +[`skills/feishu/SKILL.md`](skills/feishu/SKILL.md) 是本包携带的唯一 skill:DSH 指引、`lark-cli` 1.0.97 内嵌的 28 个子指南的索引,以及打开它们的方法。[`src/skills.ts`](src/skills.ts) 在插件加载时读取一次入口,并把它作为 `feishu` 提供方的唯一 skill 列出,资源基址为 opaque 类型,因此目录列出入口、加载返回该文件时都不运行 CLI。子指南留在二进制中,agent 用 `lark-cli skills read` 读取。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md)——这个应用插件所属的分组。 +- [CLI 账号 Service](../cli-account/README.zh.md)——CLI 应用插件共用的命令执行、CLI 路径上下文与账号操作。 +- [Skills](../../../docs/subsystems/skills.zh.md)——目录发布、加载与优先级。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md)——发起账号操作的注册表和插件页区块。 +- [Plugin Manager](../../boot/plugin-manager/README.zh.md)——安装、构建脚本审批与启用。 + +----- + + +## 模型体验 + +### Skill 目录条目 + +#### 模型看到什么 + +skill 目录中出现一个 `feishu` 条目,描述见下方。 + +##### 目录描述 + +```markdown +Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, sheets, slides, Drive files, messages and group chats, calendar, video meetings and minutes, tasks, approvals, mail, contacts, OKR, attendance, events, and the CLI's app setup and sign-in. Load it before any Feishu or Lark task; it indexes the guides and how to open them. +``` + +#### Token 影响 + +插件加载期间该条目一直留在上下文中,约 350 个字符。 + +#### KV Cache 影响 + +该条目固定不变。加载或卸载插件会改变目录,目录作为新消息重新发布,不改动更早的上下文。 + +### 已加载的 skill 正文 + +#### 模型看到什么 + +`feishu` 的 `skill` 工具结果约 6,700 个字符:DSH 指引、为 `lark-cli` 1.0.97 内嵌的 28 个子指南各给一行并附路由规则的索引,以及打开子指南的方法。DSH 指引告诉 agent 按当前运行时上下文给出的绝对路径运行 `lark-cli`,在自己运行 CLI 的配置与登录流程之前先请用户到插件页连接飞书,并为保存登录状态的命令设置最窄的 `sandbox_permissions`。打开说明告诉 agent 子指南不是 skill,子指南及其引用的文件都用 `lark-cli skills read` 读取。其资源描述为 `Embedded lark-cli guides; open them with the skills read command given in the loaded skill.` + +#### Token 影响 + +每次加载把入口正文加入保留的工具历史。agent 通过 `lark-cli` 读取的子指南及其引用文件作为普通 Shell 输出返回。 + +#### KV Cache 影响 + +加载会追加一条工具结果,不改写更早的上下文。 + +### CLI 路径 + +#### 模型看到什么 + +该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `lark-cli` 的路径;`binDir` 默认是已安装的 `@larksuite/cli` 包的 `bin` 目录。 + +##### 运行时上下文条目 + +```markdown +Feishu CLI: run `lark-cli` by its absolute path "/lark-cli"; the bare name may resolve to another installation or to none. +``` + +##### Windows 上的运行时上下文条目 + +```markdown +Feishu CLI: run `lark-cli` by its absolute path with the call operator, & '\lark-cli.exe'; the bare name may resolve to another installation or to none. +``` + +#### Token 影响 + +每份运行时上下文快照中一行,约 110 个字符加上路径。 + +#### KV Cache 影响 + +系统提示词不变;加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 + +## 已知限制与延期工作 + + + +- 仅支持 macOS 和 Windows x64;其他平台未经验证。 +- 命令必须在本 Host 上运行。组合把命令放到别处运行(例如通过 SSH)时,插件仍会加载,但每条运行 `lark-cli` 的命令都会因为那里没有这个路径而失败。 +- 插件使用 CLI 的默认配置。在 DSH 中登录或退出会影响用户自己的终端,没有 DSH 私有账号或账号选择器。插件不提供解绑操作;关闭插件会保留配置与登录。 +- 登录从 `lark-cli auth login --json` 的事件中读取设备授权链接和完成结果;CLI 版本改变这些事件时,连接以可重试的结果失败。 +- 入口的子指南索引对应 `lark-cli` 1.0.97;固定到另一个 `@larksuite/cli` 版本时,需要对照该版本的 `lark-cli skills list` 检查索引。 +- 在文件沙箱下,普通命令中的 token 刷新可能被拒绝,此时需要单条命令审批。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +仓库安装在根目录 `pnpm-workspace.yaml` 中拒绝 `@larksuite/cli` 的安装脚本,因此检出的仓库没有原生二进制。要在源码中用真实 CLI 运行插件,请执行一次 `node packages/connector/feishu/node_modules/@larksuite/cli/scripts/install.js`。单测与 `feishu-skills` 会话快照通过 `binDir` 使用替身可执行文件。 + +
diff --git a/packages/connector/feishu/cordis.patch.yml b/packages/connector/feishu/cordis.patch.yml new file mode 100644 index 0000000000..8edafe5d19 --- /dev/null +++ b/packages/connector/feishu/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: feishu + name: '@deepseek-ai/dsh-feishu' diff --git a/packages/connector/feishu/docs/DETAIL.md b/packages/connector/feishu/docs/DETAIL.md new file mode 100644 index 0000000000..46b5c54b3d --- /dev/null +++ b/packages/connector/feishu/docs/DETAIL.md @@ -0,0 +1 @@ +![The connected Feishu account on the plugin page and a conversation that creates and shares a Feishu doc](preview.svg) diff --git a/packages/connector/feishu/docs/DETAIL.zh.md b/packages/connector/feishu/docs/DETAIL.zh.md new file mode 100644 index 0000000000..7895a5f626 --- /dev/null +++ b/packages/connector/feishu/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已连接的飞书账号,以及在对话中创建飞书文档并发到群里](preview.zh.svg) diff --git a/packages/connector/feishu/docs/preview.svg b/packages/connector/feishu/docs/preview.svg new file mode 100644 index 0000000000..6f37ad368b --- /dev/null +++ b/packages/connector/feishu/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/feishu/docs/preview.zh.svg b/packages/connector/feishu/docs/preview.zh.svg new file mode 100644 index 0000000000..617574d7f6 --- /dev/null +++ b/packages/connector/feishu/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/feishu/icon.svg b/packages/connector/feishu/icon.svg new file mode 100644 index 0000000000..3a760a5c4e --- /dev/null +++ b/packages/connector/feishu/icon.svg @@ -0,0 +1,4 @@ + + + + diff --git a/packages/connector/feishu/locale/de.json b/packages/connector/feishu/locale/de.json new file mode 100644 index 0000000000..a17820abe2 --- /dev/null +++ b/packages/connector/feishu/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Feishu-Plugin", + "description": "Verwenden Sie Dokumente, Nachrichten und weitere autorisierte Funktionen von Feishu in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/en.json b/packages/connector/feishu/locale/en.json new file mode 100644 index 0000000000..fde6ba23a7 --- /dev/null +++ b/packages/connector/feishu/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Feishu plugin", + "description": "Use Feishu documents, messages, and other authorized features in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/es.json b/packages/connector/feishu/locale/es.json new file mode 100644 index 0000000000..244e014462 --- /dev/null +++ b/packages/connector/feishu/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de Feishu", + "description": "Use documentos, mensajes y otras funciones autorizadas de Feishu en las conversaciones.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/fr.json b/packages/connector/feishu/locale/fr.json new file mode 100644 index 0000000000..87d85f04e7 --- /dev/null +++ b/packages/connector/feishu/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin Feishu", + "description": "Utilisez les documents, les messages et les autres fonctionnalités autorisées de Feishu dans les conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/ja.json b/packages/connector/feishu/locale/ja.json new file mode 100644 index 0000000000..5f69bb004b --- /dev/null +++ b/packages/connector/feishu/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Feishu プラグイン", + "description": "会話の中で Feishu のドキュメント、メッセージ、その他の承認済み機能を使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/pt.json b/packages/connector/feishu/locale/pt.json new file mode 100644 index 0000000000..ead1955b8b --- /dev/null +++ b/packages/connector/feishu/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do Feishu", + "description": "Use documentos, mensagens e outros recursos autorizados do Feishu nas conversas.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/ru.json b/packages/connector/feishu/locale/ru.json new file mode 100644 index 0000000000..90b50e8621 --- /dev/null +++ b/packages/connector/feishu/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин Feishu", + "description": "Используйте документы, сообщения и другие разрешённые функции Feishu в беседах.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/feishu/locale/zh.json b/packages/connector/feishu/locale/zh.json new file mode 100644 index 0000000000..87b8512dec --- /dev/null +++ b/packages/connector/feishu/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "飞书插件", + "description": "在对话中使用飞书文档、消息及其他已授权的功能。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/feishu/package.json b/packages/connector/feishu/package.json new file mode 100644 index 0000000000..8d9b750de3 --- /dev/null +++ b/packages/connector/feishu/package.json @@ -0,0 +1,66 @@ +{ + "name": "@deepseek-ai/dsh-feishu", + "description": "Feishu plugin: the official lark-cli with its embedded skills, and account connection from the Plugins page", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/feishu" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "skills", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "dependencies": { + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@larksuite/cli": "1.0.97", + "yaml": "^2.4.2", + "zod": "^4.4.3" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-skill": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-skill": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*" + } +} diff --git a/packages/connector/feishu/skills/feishu/SKILL.md b/packages/connector/feishu/skills/feishu/SKILL.md new file mode 100644 index 0000000000..eeffe0ee13 --- /dev/null +++ b/packages/connector/feishu/skills/feishu/SKILL.md @@ -0,0 +1,51 @@ +--- +name: feishu +description: "Feishu (飞书) and Lark through the bundled lark-cli: documents and wiki, Base, sheets, slides, Drive files, messages and group chats, calendar, video meetings and minutes, tasks, approvals, mail, contacts, OKR, attendance, events, and the CLI's app setup and sign-in. Load it before any Feishu or Lark task; it indexes the guides and how to open them." +--- + +# Feishu in DSH + +Call this integration the Feishu plugin (飞书插件 in Chinese) in user-facing replies. Run `lark-cli` in the Host Shell by the absolute path that the current runtime context gives for it, not by name; DSH installs the version this plugin pins. It uses the default lark-cli configuration and sign-in shared with the user's own terminal, so do not remove, switch, or sign out of apps or profiles unless the user asks. + +When a command reports a missing app configuration or sign-in, first ask the user to connect Feishu on the Feishu plugin page in Plugins. Open the lark-shared guide and run its setup and auth flow yourself only when the user asks to finish it in this conversation. Never ask for or print app secrets or tokens. + +Commands that save sign-in state, such as `auth login --device-code` and `config init`, write outside the workspace and use up their one-time authorization even when the save is denied: on the first attempt, set the Shell tool's `sandbox_permissions` to the narrowest mode that can write outside the workspace, with a `justification`. Run other commands in the existing sandbox and set `sandbox_permissions` only when a credential, lock, log, or cache write is denied. + +Do not install another lark-cli or run `lark-cli update`. + +## Guides + +- `lark-approval`: Feishu Approval: list and handle approval tasks, look up instances, search the definitions you can start, and start native approval instances; to-dos that are not approvals belong to `lark-task`. +- `lark-apps`: Miaoda (Spark) app development and hosting: create apps, develop locally or in the cloud, design mockups and prototypes, deploy and publish, and manage logs, metrics, environment variables, collaborators, roles, and automation triggers; use for apps served from `*.aiforce.cloud`. +- `lark-attendance`: Feishu Attendance: read your own check-in records. +- `lark-base`: Feishu Base (bitable): tables, fields, records, views, statistics, formulas, forms, dashboards, BaseApp pages, workspaces, workflows, roles, and templates; use for `/base/` and `/app/` links. +- `lark-calendar`: Feishu Calendar: view, search, create, and update events, manage attendees, query free/busy and suggested times, and book meeting rooms; past video meetings belong to `lark-meeting` and to-dos to `lark-task`. +- `lark-contact`: Feishu contacts: resolve a name or email to an `open_id`, look a user up by `open_id`, and search the bots and agents you can see; department trees need the native OpenAPI. +- `lark-doc`: Feishu Docs and Wiki documents: read, create, and edit documents, insert or download image attachments, and work with mind notes; route by document URL or token, including `doubao.com` `/docx/` and `/wiki/` links. +- `lark-drive`: Feishu Drive: files and folders, upload and download, copy, move, delete, metadata, permissions, comments, subscriptions, titles, versions, security labels, and importing local Word, Markdown, Excel, CSV, PPTX, or `.base` files as Feishu documents. +- `lark-event`: Feishu real-time events: subscribe to and consume message, approval, task, meeting, minutes, and whiteboard events as NDJSON, with bounded runs for agents that run as subprocesses. +- `lark-im`: Feishu Messenger: send and reply to messages, search chat history, manage group chats and members, transfer images and files, reactions, urgent notices, pinned feeds, interactive cards, and card callbacks. +- `lark-mail`: Feishu Mail: draft, send, reply to, forward, read, and search mail, and manage folders, labels, mail contacts, new-mail listeners, and inbox rules; mail intent only. +- `lark-markdown`: Feishu Markdown files: view, create, upload, edit, and diff native Markdown files in Feishu, including comparing the remote version with a local draft. +- `lark-meeting`: Feishu video meetings: meeting records and artifacts such as minutes and transcripts, Minutes search, upload, download, and editing, bot participation, live meeting content, and in-meeting chat; scheduling, free/busy, and rooms belong to `lark-calendar`. +- `lark-minutes`: alias that defers to `lark-meeting`; open it only when the user or a configuration names it. +- `lark-note`: alias that defers to `lark-meeting`; open it only when the user or a configuration names it. +- `lark-okr`: Feishu OKR: view and edit cycles, objectives, key results, alignments, metrics, and progress records. +- `lark-openapi-explorer`: Feishu native OpenAPI exploration: find and call OpenAPI endpoints the CLI does not wrap when no other guide or registered command fits. +- `lark-shared`: lark-cli setup and auth: login, status, and logout, user versus bot identity, business-domain permissions, missing scopes, revoking authorization, and `_notice` JSON. +- `lark-sheets`: Feishu Sheets: create and edit spreadsheets, sheet and row or column structure, cell values, formulas, styles, charts, pivot tables, conditional formats, filters, and Excel or CSV import and export; Base belongs to `lark-base`, and searching Drive for a sheet to `lark-drive`. +- `lark-skill-maker`: create custom lark-cli skills that wrap Feishu API operations or multi-step flows. +- `lark-slides`: Feishu Slides: create presentations, read slide content, and create, delete, read, or partially replace pages; whiteboards inside documents belong to `lark-whiteboard`. +- `lark-task`: Feishu Tasks: create and update tasks and their status, subtasks, task lists, assignees, attachments, and task agents. +- `lark-vc`: alias that defers to `lark-meeting`; open it only when the user or a configuration names it. +- `lark-vc-agent`: alias that defers to `lark-meeting`; open it only when the user or a configuration names it. +- `lark-whiteboard`: Feishu whiteboards inside documents: export a whiteboard as an image or as raw nodes and update its content in several formats. +- `lark-wiki`: Feishu Wiki: knowledge spaces, their members, the node hierarchy, and organizing documents and shortcuts; use for `/wiki/` links, while document content belongs to `lark-doc`. +- `lark-workflow-meeting-summary`: workflow that collects the meeting minutes of a date range into a structured report. +- `lark-workflow-standup-report`: workflow that combines the calendar agenda and open tasks into a summary for a day or a week. + +## Opening a guide + +These guides belong to lark-cli and are not skills: open one with `lark-cli skills read ` in the Host Shell, not with the skill tool. + +Read a file that a guide references, such as `references/...`, with `lark-cli skills read `. Read a reference to another guide, such as `../lark-foo/...`, with the same command without the leading `../`: `lark-cli skills read lark-foo/...`. diff --git a/packages/connector/feishu/src/account.ts b/packages/connector/feishu/src/account.ts new file mode 100644 index 0000000000..abc6437673 --- /dev/null +++ b/packages/connector/feishu/src/account.ts @@ -0,0 +1,119 @@ +/** Check, connection, and sign-out of the CLI's default Feishu account, as the operations `ctx.cliAccounts` runs. */ + +import { brandString } from '@deepseek-ai/dsh-brand' +import z from 'zod' +import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import { parseJson } from './cli.ts' +import type { FeishuAccountState, FeishuAppId, FeishuCommand, FeishuOperationKind, FeishuPhase } from './types.ts' + +const NotConfigured = z.object({ ok: z.literal(false), error: z.object({ subtype: z.literal('not_configured') }) }) +const User = z.object({ + status: z.string(), + available: z.boolean(), + verified: z.boolean().optional(), + userName: z.string().optional(), + openId: z.string().optional(), +}) +const Status = z.object({ appId: z.string().min(1), identities: z.object({ user: User }) }) +const LoginLink = z.object({ event: z.literal('device_authorization'), verification_uri_complete: z.string() }) +const LoginComplete = z.object({ event: z.literal('authorization_complete'), user_open_id: z.string().min(1), missing: z.array(z.string()) }) +const CONFIG_LINK = /^\s*(https:\/\/\S+)\s*$/u +const SIGNED_OUT = new Set(['missing', 'not_configured', 'needs_refresh']) + +type Control = CliOperationControl + +interface Check { account: FeishuAccountState; openId?: string | undefined } + +/** + * Carry out one account operation with lark-cli and publish the account each check observes. + * @param kind - the requested operation. + * @param control - phase changes, link offers, command runs, and account updates for this operation. + * @param signal - aborts on cancellation and when the plugin unloads. + * @returns after the operation finishes. + * @throws when a command fails, its output is not the expected JSON, or the account it leaves is not the one the + * operation set out to reach. + */ +export async function perform(kind: FeishuOperationKind, control: Control, signal: AbortSignal): Promise { + switch (kind) { + case 'check': + await check(control, signal) + return + case 'link-app': return linkApp(control, signal) + case 'sign-in': return signIn(control, signal) + case 'sign-out': { + control.stage('signing-out') + const result = await control.run('auth-logout', ['auth', 'logout', '--json'], signal) + if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') + await check(control, signal) + return + } + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) + } +} + +/** + * Link an app through the CLI's setup page; sign-in is a separate operation. An existing configuration, + * including its sign-ins and any other app, is replaced by the app the user creates or chooses. + */ +async function linkApp(control: Control, signal: AbortSignal): Promise { + control.stage('configuring') + let offered = false + const setup = await control.run('config-init', ['config', 'init', '--new'], signal, { + awaitsUser: true, + onLine: (stream, line) => { + const link = stream === 'stderr' && !offered ? CONFIG_LINK.exec(line) : null + if (link !== null) offered = control.offer(link[1] as string) + }, + }) + if (setup.exitCode !== 0) throw new Error('feishu: config init failed') + control.stage('checking') + if ((await check(control, signal)).account.state === 'unconfigured') throw new Error('feishu: config init left no app') +} + +/** Sign the configured app's user in, then confirm the CLI's default account is that user. */ +async function signIn(control: Control, signal: AbortSignal): Promise { + control.stage('authorizing') + let complete: z.infer | undefined + const login = await control.run('auth-login', ['auth', 'login', '--json'], signal, { + awaitsUser: true, + onLine: (stream, line) => { + if (stream !== 'stdout' || !line.startsWith('{')) return + const event: unknown = JSON.parse(line) + const link = LoginLink.safeParse(event) + if (link.success) control.offer(link.data.verification_uri_complete) + const done = LoginComplete.safeParse(event) + if (done.success) complete = done.data + }, + }) + // Exit code 3 reports a sign-in that completed without every requested permission. + if (complete === undefined || (login.exitCode !== 0 && !(login.exitCode === 3 && complete.missing.length > 0))) { + throw new Error('feishu: auth login did not complete') + } + control.stage('verifying') + const found = await check(control, signal) + if (found.account.state !== 'connected' || found.openId !== complete.user_open_id) throw new Error('feishu: sign-in did not verify') +} + +/** Read the default account, publish what it shows, and return it with the signed-in user's id. */ +async function check(control: Control, signal: AbortSignal): Promise { + const args = ['auth', 'status', '--verify', '--json'] + const result = await control.run('auth-status', args, signal) + if (result.exitCode !== 0) { + if (!NotConfigured.safeParse(parseJson(args, result.stderr)).success) throw new Error('feishu: auth status failed') + return record(control, { state: 'unconfigured' }) + } + const status = Status.parse(parseJson(args, result.stdout)) + const appId = brandString(status.appId) + const user = status.identities.user + const account: FeishuAccountState = user.available && user.verified === true + ? { state: 'connected', appId, ...user.userName === undefined ? {} : { userName: user.userName } } + : { state: SIGNED_OUT.has(user.status) ? 'signed-out' : 'unverified', appId } + return record(control, account, user.openId) +} + +function record(control: Control, account: FeishuAccountState, openId?: string): Check { + control.publish(account) + return { account, openId } +} diff --git a/packages/connector/feishu/src/cli.ts b/packages/connector/feishu/src/cli.ts new file mode 100644 index 0000000000..8028c8da97 --- /dev/null +++ b/packages/connector/feishu/src/cli.ts @@ -0,0 +1,48 @@ +/** Managed lark-cli location and the JSON output of its commands. */ + +import { accessSync, constants } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** The name lark-cli's guides run it by. */ +export const PROGRAM = 'lark-cli' + +/** + * Name the executable file as `@larksuite/cli` installs it. + * @param platform - the Host platform. + * @returns `lark-cli`, or `lark-cli.exe` on Windows. + */ +export function executableFileName(platform: NodeJS.Platform): string { + return platform === 'win32' ? `${PROGRAM}.exe` : PROGRAM +} + +/** + * Locate the managed executable. + * @param binDir - absolute override; defaults to the installed `@larksuite/cli` package. + * @returns the absolute path of the executable `lark-cli`, `lark-cli.exe` on Windows. + * @throws when the executable is missing. + */ +export function resolveCliExecutable(binDir: string | undefined): string { + const program = join(binDir ?? join(dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))), 'bin'), executableFileName(process.platform)) + try { + accessSync(program, constants.X_OK) + } catch (error) { + throw new Error(`feishu: ${program} is not executable; approve the @larksuite/cli install script or set binDir`, { cause: error }) + } + return program +} + +/** + * Parse one command's JSON output. + * @param args - the command's native arguments, for the error message. + * @param output - the complete stream the command wrote the JSON to. + * @returns unvalidated JSON for the caller to check. + * @throws when the output is not JSON. + */ +export function parseJson(args: readonly string[], output: string): unknown { + try { + return JSON.parse(output) + } catch (error) { + throw new Error(`${[PROGRAM, ...args].join(' ')} returned invalid JSON`, { cause: error }) + } +} diff --git a/packages/connector/feishu/src/index.ts b/packages/connector/feishu/src/index.ts new file mode 100644 index 0000000000..5d2b507a68 --- /dev/null +++ b/packages/connector/feishu/src/index.ts @@ -0,0 +1,62 @@ +/** + * Feishu plugin: registers the managed lark-cli and its account with `ctx.cliAccounts`, which tells the model the CLI's + * absolute path and shows the account on the Plugins page, and lists the packaged `feishu` skill that indexes the + * guides embedded in that CLI. The CLI's default account is shared with the user's own terminal. + * @module @deepseek-ai/dsh-feishu + */ + +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-cli-account' +import type {} from '@deepseek-ai/dsh-skill' +import { perform } from './account.ts' +import { PROGRAM, resolveCliExecutable } from './cli.ts' +import { dictionaries, type FeishuTextKey } from './locales.ts' +import { copy, FEISHU_PACKAGE, operations, presentAccount } from './presentation.ts' +import { FeishuSkillProvider } from './skills.ts' +import type { FeishuAccountState, FeishuCommand, FeishuOperationKind, FeishuPhase } from './types.ts' + +/** Plugin name. */ +export const name = 'feishu' + +/** Services the CLI's account and its skill register with. */ +export const inject = ['cliAccounts', 'skills'] + +/** The packaged entry skill; the guides it indexes stay in the CLI. */ +const ENTRY = fileURLToPath(new URL('../skills/feishu/SKILL.md', import.meta.url)) + +/** Where lark-cli is. */ +export interface Config { + /** Absolute directory holding the `lark-cli` executable; defaults to the installed `@larksuite/cli` package. */ + binDir?: string +} + +/** Validates {@link Config}. */ +export const Config: z = z.object({ + binDir: z.string().min(1), +}) + +/** + * Register the CLI with its account, and the skill. + * @param ctx - Context carrying the CLI account Service and the skill registry. + * @param config - CLI location. + * @throws when `lark-cli` is not executable, or the packaged entry skill has no name or description. + */ +export function apply(ctx: Context, config: Config): void { + ctx.cliAccounts.register({ + name, + packageName: FEISHU_PACKAGE, + cli: { product: 'Feishu', program: PROGRAM, executable: resolveCliExecutable(config.binDir) }, + account: { state: 'unchecked' }, + check: 'check', + cancellable: ['configuring', 'authorizing'], + authorizationHosts: ['feishu.cn', 'larksuite.com'], + perform, + dictionaries, + operations, + copy, + present: presentAccount, + }) + ctx.skills.registerProvider(() => new FeishuSkillProvider(ENTRY)) +} diff --git a/packages/connector/feishu/src/locales.ts b/packages/connector/feishu/src/locales.ts new file mode 100644 index 0000000000..3d8f3fbd0b --- /dev/null +++ b/packages/connector/feishu/src/locales.ts @@ -0,0 +1,367 @@ +/** The Feishu text the Plugins page shows; the browser resolves it in its active language. */ + +/** Chinese dictionary and key source. */ +export const zh = { + 'section.title': '飞书账号', + 'status.checking': '正在检查连接', + 'status.disconnected': '未连接', + 'status.unavailable': '暂时无法确认登录状态', + 'status.connected': '已连接', + 'step.configuring': '第 1 步:关联飞书应用', + 'step.authorizing': '第 2 步:登录飞书账号', + 'step.connecting': '正在连接', + 'step.signing-out': '正在退出登录', + 'detail.no-app': '先关联一个飞书应用(可以新建,也可以选择已有应用),再登录飞书账号。连接后,可以在对话中使用飞书文档、消息及其他你授权的功能。', + 'detail.signed-out': '已关联飞书应用。登录飞书账号后,就可以在对话中使用飞书。', + 'detail.unavailable': '已保留现有配置和登录,可以稍后重试。', + 'detail.connected': '可以在对话中直接请 Agent 使用飞书。', + 'detail.connectedAs': '已登录为 {name}。可以在对话中直接请 Agent 使用飞书。', + 'detail.configuring': '在打开的飞书页面中新建或选择应用,完成后回到这里登录。页面没有打开时,点击“打开飞书页面”。', + 'detail.authorizing': '在打开的飞书页面中确认授权,完成后回到这里查看结果。页面没有打开时,点击“打开飞书页面”。', + hint: '飞书账号与这台电脑终端里的飞书 CLI 共用。', + 'app.linked': '飞书应用:{id}', + failed: '操作未完成,请重试', + 'failed.linkApp': '飞书应用关联未完成。若飞书页面已显示成功,请检查 DSH 对本机配置与系统凭据的访问权限,再次关联时请选择已有应用', + 'action.connect': '连接飞书', + 'action.linkApp': '关联飞书应用', + 'action.signIn': '登录飞书账号', + 'action.open': '打开飞书页面', + 'action.cancel': '取消', + 'action.signOut': '退出登录', + 'action.replaceApp': '更换应用', + 'action.retry': '重试', + 'badge.connected': '已连接', + 'badge.disconnected': '未连接', + 'badge.connecting': '连接中', + 'badge.unavailable': '待确认', + 'signOut.title': '退出飞书登录?', + 'signOut.body': '将退出飞书 CLI 的默认账号,这台电脑终端里的 lark-cli 也会一起退出。已关联的飞书应用会保留。', + 'replaceApp.title': '更换飞书应用?', + 'replaceApp.body': '将打开飞书页面,新建或选择一个应用。这台电脑上飞书 CLI 的配置会替换为这个应用,终端里的 lark-cli 也一样;更换后需要重新登录飞书账号。', + 'activation.title': '连接飞书账号', + 'activation.body': '飞书插件已开启。连接你的飞书账号后,就可以在对话中使用它。', + 'notice.app-linked': '飞书应用已关联,下一步登录飞书账号', + 'notice.connected': '飞书已连接', + 'notice.signed-out': '已退出飞书登录', +} + +/** Every key of the Feishu text. */ +export type FeishuTextKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + 'section.title': 'Feishu account', + 'status.checking': 'Checking connection', + 'status.disconnected': 'Not connected', + 'status.unavailable': 'Cannot confirm sign-in right now', + 'status.connected': 'Connected', + 'step.configuring': 'Step 1: Link a Feishu app', + 'step.authorizing': 'Step 2: Sign in to Feishu', + 'step.connecting': 'Connecting', + 'step.signing-out': 'Signing out', + 'detail.no-app': 'Link a Feishu app first, either a new one or one you already have, then sign in to Feishu. After that, you can use Feishu docs, messages, and other features you authorize in conversations.', + 'detail.signed-out': 'A Feishu app is linked. Sign in to Feishu to use it in conversations.', + 'detail.unavailable': 'The existing setup and sign-in are kept. Try again later.', + 'detail.connected': 'Ask the agent to use Feishu directly in a conversation.', + 'detail.connectedAs': 'Signed in as {name}. Ask the agent to use Feishu directly in a conversation.', + 'detail.configuring': 'Create or choose an app on the Feishu page, then come back here to sign in. If the page did not open, select Open Feishu page.', + 'detail.authorizing': 'Confirm the authorization on the Feishu page, then come back here to see the result. If the page did not open, select Open Feishu page.', + hint: 'The Feishu account is shared with the Feishu CLI in this computer\'s terminal.', + 'app.linked': 'Feishu app: {id}', + failed: 'The action did not finish. Try again.', + 'failed.linkApp': 'Feishu app linking did not finish. If the Feishu page reported success, check DSH access to local configuration and system credentials, then choose the existing app when linking again.', + 'action.connect': 'Connect Feishu', + 'action.linkApp': 'Link Feishu app', + 'action.signIn': 'Sign in to Feishu', + 'action.open': 'Open Feishu page', + 'action.cancel': 'Cancel', + 'action.signOut': 'Sign out', + 'action.replaceApp': 'Change app', + 'action.retry': 'Retry', + 'badge.connected': 'Connected', + 'badge.disconnected': 'Not connected', + 'badge.connecting': 'Connecting', + 'badge.unavailable': 'Unconfirmed', + 'signOut.title': 'Sign out of Feishu?', + 'signOut.body': 'This signs out the Feishu CLI\'s default account, including lark-cli in this computer\'s terminal. The linked Feishu app is kept.', + 'replaceApp.title': 'Change the Feishu app?', + 'replaceApp.body': 'A Feishu page opens where you create or choose an app. The Feishu CLI on this computer, including lark-cli in its terminal, is then configured with that app only, and you sign in to Feishu again.', + 'activation.title': 'Connect your Feishu account', + 'activation.body': 'The Feishu plugin is on. Connect your Feishu account to use it in conversations.', + 'notice.app-linked': 'Feishu app linked. Next, sign in to Feishu.', + 'notice.connected': 'Feishu connected', + 'notice.signed-out': 'Signed out of Feishu', +} + +/** Japanese dictionary. */ +export const ja: Record = { + 'section.title': 'Feishu アカウント', + 'status.checking': '接続を確認中', + 'status.disconnected': '未接続', + 'status.unavailable': '現在サインイン状態を確認できません', + 'status.connected': '接続済み', + 'step.configuring': 'ステップ 1:Feishu アプリを関連付ける', + 'step.authorizing': 'ステップ 2:Feishu にサインイン', + 'step.connecting': '接続中', + 'step.signing-out': 'サインアウト中', + 'detail.no-app': 'まず Feishu アプリを関連付け(新規作成または既存のアプリを選択)、次に Feishu にサインインしてください。その後、会話の中で Feishu のドキュメント、メッセージ、その他の承認した機能を使用できます。', + 'detail.signed-out': 'Feishu アプリは関連付け済みです。Feishu にサインインすると、会話の中で使用できます。', + 'detail.unavailable': '現在の設定とサインイン状態は保持されています。しばらくしてから再試行してください。', + 'detail.connected': '会話の中でエージェントに Feishu の使用を直接依頼できます。', + 'detail.connectedAs': '{name} としてサインインしています。会話の中でエージェントに Feishu の使用を直接依頼できます。', + 'detail.configuring': '開いた Feishu ページでアプリを作成または選択し、完了したらここに戻ってサインインしてください。ページが開かない場合は、「Feishu ページを開く」を選択してください。', + 'detail.authorizing': '開いた Feishu ページで認可を確定し、完了したらここに戻って結果を確認してください。ページが開かない場合は、「Feishu ページを開く」を選択してください。', + hint: 'Feishu アカウントは、このコンピューターのターミナルにある Feishu CLI と共有されます。', + 'app.linked': 'Feishu アプリ:{id}', + failed: '操作が完了しませんでした。もう一度お試しください。', + 'failed.linkApp': 'Feishu アプリの関連付けが完了しませんでした。Feishu ページに成功と表示された場合は、DSH がローカル設定とシステムの認証情報にアクセスできるか確認し、再度関連付けるときは既存のアプリを選択してください。', + 'action.connect': 'Feishu を接続', + 'action.linkApp': 'Feishu アプリを関連付ける', + 'action.signIn': 'Feishu にサインイン', + 'action.open': 'Feishu ページを開く', + 'action.cancel': 'キャンセル', + 'action.signOut': 'サインアウト', + 'action.replaceApp': 'アプリを変更', + 'action.retry': '再試行', + 'badge.connected': '接続済み', + 'badge.disconnected': '未接続', + 'badge.connecting': '接続中', + 'badge.unavailable': '未確認', + 'signOut.title': 'Feishu からサインアウトしますか?', + 'signOut.body': 'Feishu CLI の既定のアカウントからサインアウトします。このコンピューターのターミナルにある lark-cli もサインアウトされます。関連付けた Feishu アプリは保持されます。', + 'replaceApp.title': 'Feishu アプリを変更しますか?', + 'replaceApp.body': 'Feishu ページが開くので、アプリを作成または選択します。このコンピューターの Feishu CLI(ターミナルの lark-cli を含む)の設定はそのアプリに置き換わり、Feishu に再度サインインする必要があります。', + 'activation.title': 'Feishu アカウントを接続', + 'activation.body': 'Feishu プラグインがオンになりました。Feishu アカウントを接続すると、会話の中で使用できます。', + 'notice.app-linked': 'Feishu アプリを関連付けました。次に Feishu にサインインしてください。', + 'notice.connected': 'Feishu を接続しました', + 'notice.signed-out': 'Feishu からサインアウトしました', +} + +/** Spanish dictionary. */ +export const es: Record = { + 'section.title': 'Cuenta de Feishu', + 'status.checking': 'Comprobando la conexión', + 'status.disconnected': 'No conectado', + 'status.unavailable': 'No se puede confirmar el inicio de sesión en este momento', + 'status.connected': 'Conectado', + 'step.configuring': 'Paso 1: vincule una aplicación de Feishu', + 'step.authorizing': 'Paso 2: inicie sesión en Feishu', + 'step.connecting': 'Conectando', + 'step.signing-out': 'Cerrando sesión', + 'detail.no-app': 'Primero vincule una aplicación de Feishu, ya sea nueva o una que ya tenga, y luego inicie sesión en Feishu. Después, podrá usar en las conversaciones los documentos, los mensajes y otras funciones de Feishu que autorice.', + 'detail.signed-out': 'Hay una aplicación de Feishu vinculada. Inicie sesión en Feishu para usarlo en las conversaciones.', + 'detail.unavailable': 'Se conservan la configuración y el inicio de sesión actuales. Inténtelo de nuevo más tarde.', + 'detail.connected': 'Pida al agente que use Feishu directamente en una conversación.', + 'detail.connectedAs': 'Sesión iniciada como {name}. Pida al agente que use Feishu directamente en una conversación.', + 'detail.configuring': 'Cree o elija una aplicación en la página de Feishu y luego vuelva aquí para iniciar sesión. Si la página no se abrió, seleccione “Abrir página de Feishu”.', + 'detail.authorizing': 'Confirme la autorización en la página de Feishu y luego vuelva aquí para ver el resultado. Si la página no se abrió, seleccione “Abrir página de Feishu”.', + hint: 'La cuenta de Feishu se comparte con la CLI de Feishu en la terminal de esta computadora.', + 'app.linked': 'Aplicación de Feishu: {id}', + failed: 'La acción no se completó. Inténtelo de nuevo.', + 'failed.linkApp': 'La vinculación de la aplicación de Feishu no se completó. Si la página de Feishu indicó que se realizó correctamente, compruebe el acceso de DSH a la configuración local y a las credenciales del sistema y, al volver a vincular, elija la aplicación existente.', + 'action.connect': 'Conectar Feishu', + 'action.linkApp': 'Vincular aplicación de Feishu', + 'action.signIn': 'Iniciar sesión en Feishu', + 'action.open': 'Abrir página de Feishu', + 'action.cancel': 'Cancelar', + 'action.signOut': 'Cerrar sesión', + 'action.replaceApp': 'Cambiar aplicación', + 'action.retry': 'Reintentar', + 'badge.connected': 'Conectado', + 'badge.disconnected': 'No conectado', + 'badge.connecting': 'Conectando', + 'badge.unavailable': 'Sin confirmar', + 'signOut.title': '¿Cerrar sesión en Feishu?', + 'signOut.body': 'Se cerrará la sesión de la cuenta predeterminada de la CLI de Feishu, incluido lark-cli en la terminal de esta computadora. La aplicación de Feishu vinculada se conserva.', + 'replaceApp.title': '¿Cambiar la aplicación de Feishu?', + 'replaceApp.body': 'Se abrirá una página de Feishu donde podrá crear o elegir una aplicación. Después, la CLI de Feishu de esta computadora, incluido lark-cli en su terminal, quedará configurada solo con esa aplicación y deberá volver a iniciar sesión en Feishu.', + 'activation.title': 'Conecte su cuenta de Feishu', + 'activation.body': 'El complemento de Feishu está activado. Conecte su cuenta de Feishu para usarlo en las conversaciones.', + 'notice.app-linked': 'Aplicación de Feishu vinculada. Ahora inicie sesión en Feishu.', + 'notice.connected': 'Feishu conectado', + 'notice.signed-out': 'Sesión de Feishu cerrada', +} + +/** French dictionary. */ +export const fr: Record = { + 'section.title': 'Compte Feishu', + 'status.checking': 'Vérification de la connexion', + 'status.disconnected': 'Non connecté', + 'status.unavailable': 'Impossible de confirmer la connexion pour le moment', + 'status.connected': 'Connecté', + 'step.configuring': 'Étape 1 : associez une application Feishu', + 'step.authorizing': 'Étape 2 : connectez-vous à Feishu', + 'step.connecting': 'Connexion en cours', + 'step.signing-out': 'Déconnexion en cours', + 'detail.no-app': 'Associez d’abord une application Feishu, nouvelle ou existante, puis connectez-vous à Feishu. Vous pourrez ensuite utiliser dans les conversations les documents, les messages et les autres fonctionnalités de Feishu que vous autorisez.', + 'detail.signed-out': 'Une application Feishu est associée. Connectez-vous à Feishu pour l’utiliser dans les conversations.', + 'detail.unavailable': 'La configuration et la connexion existantes sont conservées. Réessayez plus tard.', + 'detail.connected': 'Demandez à l’agent d’utiliser Feishu directement dans une conversation.', + 'detail.connectedAs': 'Connecté en tant que {name}. Demandez à l’agent d’utiliser Feishu directement dans une conversation.', + 'detail.configuring': 'Créez ou choisissez une application sur la page Feishu, puis revenez ici pour vous connecter. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page Feishu ».', + 'detail.authorizing': 'Confirmez l’autorisation sur la page Feishu, puis revenez ici pour voir le résultat. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page Feishu ».', + hint: 'Le compte Feishu est partagé avec la CLI Feishu du terminal de cet ordinateur.', + 'app.linked': 'Application Feishu : {id}', + failed: 'L’action n’a pas abouti. Réessayez.', + 'failed.linkApp': 'L’association de l’application Feishu n’a pas abouti. Si la page Feishu a indiqué une réussite, vérifiez l’accès de DSH à la configuration locale et aux identifiants système, puis choisissez l’application existante lors de la nouvelle association.', + 'action.connect': 'Connecter Feishu', + 'action.linkApp': 'Associer une application Feishu', + 'action.signIn': 'Se connecter à Feishu', + 'action.open': 'Ouvrir la page Feishu', + 'action.cancel': 'Annuler', + 'action.signOut': 'Se déconnecter', + 'action.replaceApp': 'Changer d’application', + 'action.retry': 'Réessayer', + 'badge.connected': 'Connecté', + 'badge.disconnected': 'Non connecté', + 'badge.connecting': 'Connexion en cours', + 'badge.unavailable': 'Non confirmé', + 'signOut.title': 'Se déconnecter de Feishu ?', + 'signOut.body': 'Cela déconnecte le compte par défaut de la CLI Feishu, y compris lark-cli dans le terminal de cet ordinateur. L’application Feishu associée est conservée.', + 'replaceApp.title': 'Changer l’application Feishu ?', + 'replaceApp.body': 'Une page Feishu s’ouvre pour créer ou choisir une application. La CLI Feishu de cet ordinateur, y compris lark-cli dans son terminal, est ensuite configurée avec cette seule application, et vous devez vous reconnecter à Feishu.', + 'activation.title': 'Connectez votre compte Feishu', + 'activation.body': 'Le plugin Feishu est activé. Connectez votre compte Feishu pour l’utiliser dans les conversations.', + 'notice.app-linked': 'Application Feishu associée. Connectez-vous maintenant à Feishu.', + 'notice.connected': 'Feishu connecté', + 'notice.signed-out': 'Déconnecté de Feishu', +} + +/** German dictionary. */ +export const de: Record = { + 'section.title': 'Feishu-Konto', + 'status.checking': 'Verbindung wird geprüft', + 'status.disconnected': 'Nicht verbunden', + 'status.unavailable': 'Anmeldung kann gerade nicht bestätigt werden', + 'status.connected': 'Verbunden', + 'step.configuring': 'Schritt 1: Feishu-App verknüpfen', + 'step.authorizing': 'Schritt 2: Bei Feishu anmelden', + 'step.connecting': 'Wird verbunden', + 'step.signing-out': 'Wird abgemeldet', + 'detail.no-app': 'Verknüpfen Sie zuerst eine Feishu-App, entweder eine neue oder eine vorhandene, und melden Sie sich dann bei Feishu an. Danach können Sie Dokumente, Nachrichten und weitere von Ihnen autorisierte Funktionen von Feishu in Unterhaltungen verwenden.', + 'detail.signed-out': 'Eine Feishu-App ist verknüpft. Melden Sie sich bei Feishu an, um es in Unterhaltungen zu verwenden.', + 'detail.unavailable': 'Die bestehende Einrichtung und Anmeldung bleiben erhalten. Versuchen Sie es später erneut.', + 'detail.connected': 'Bitten Sie den Agenten, Feishu direkt in einer Unterhaltung zu verwenden.', + 'detail.connectedAs': 'Angemeldet als {name}. Bitten Sie den Agenten, Feishu direkt in einer Unterhaltung zu verwenden.', + 'detail.configuring': 'Erstellen oder wählen Sie auf der Feishu-Seite eine App und kehren Sie dann hierher zurück, um sich anzumelden. Falls sich die Seite nicht geöffnet hat, wählen Sie „Feishu-Seite öffnen“.', + 'detail.authorizing': 'Bestätigen Sie die Autorisierung auf der Feishu-Seite und kehren Sie dann hierher zurück, um das Ergebnis zu sehen. Falls sich die Seite nicht geöffnet hat, wählen Sie „Feishu-Seite öffnen“.', + hint: 'Das Feishu-Konto wird mit der Feishu-CLI im Terminal dieses Computers geteilt.', + 'app.linked': 'Feishu-App: {id}', + failed: 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', + 'failed.linkApp': 'Die Verknüpfung der Feishu-App wurde nicht abgeschlossen. Wenn die Feishu-Seite einen Erfolg gemeldet hat, prüfen Sie den Zugriff von DSH auf die lokale Konfiguration und die Systemanmeldedaten und wählen Sie beim erneuten Verknüpfen die vorhandene App.', + 'action.connect': 'Feishu verbinden', + 'action.linkApp': 'Feishu-App verknüpfen', + 'action.signIn': 'Bei Feishu anmelden', + 'action.open': 'Feishu-Seite öffnen', + 'action.cancel': 'Abbrechen', + 'action.signOut': 'Abmelden', + 'action.replaceApp': 'App wechseln', + 'action.retry': 'Erneut versuchen', + 'badge.connected': 'Verbunden', + 'badge.disconnected': 'Nicht verbunden', + 'badge.connecting': 'Wird verbunden', + 'badge.unavailable': 'Unbestätigt', + 'signOut.title': 'Von Feishu abmelden?', + 'signOut.body': 'Dadurch wird das Standardkonto der Feishu-CLI abgemeldet, auch für lark-cli im Terminal dieses Computers. Die verknüpfte Feishu-App bleibt erhalten.', + 'replaceApp.title': 'Feishu-App wechseln?', + 'replaceApp.body': 'Es öffnet sich eine Feishu-Seite, auf der Sie eine App erstellen oder wählen. Anschließend ist die Feishu-CLI auf diesem Computer, einschließlich lark-cli im Terminal, nur noch mit dieser App konfiguriert, und Sie melden sich erneut bei Feishu an.', + 'activation.title': 'Feishu-Konto verbinden', + 'activation.body': 'Das Feishu-Plugin ist aktiviert. Verbinden Sie Ihr Feishu-Konto, um es in Unterhaltungen zu verwenden.', + 'notice.app-linked': 'Feishu-App verknüpft. Melden Sie sich als Nächstes bei Feishu an.', + 'notice.connected': 'Feishu verbunden', + 'notice.signed-out': 'Von Feishu abgemeldet', +} + +/** Russian dictionary. */ +export const ru: Record = { + 'section.title': 'Аккаунт Feishu', + 'status.checking': 'Проверка подключения', + 'status.disconnected': 'Не подключено', + 'status.unavailable': 'Сейчас не удаётся подтвердить вход', + 'status.connected': 'Подключено', + 'step.configuring': 'Шаг 1. Привяжите приложение Feishu', + 'step.authorizing': 'Шаг 2. Войдите в Feishu', + 'step.connecting': 'Подключение', + 'step.signing-out': 'Выполняется выход', + 'detail.no-app': 'Сначала привяжите приложение Feishu — новое или уже существующее, — затем войдите в Feishu. После этого в беседах можно будет использовать документы, сообщения и другие разрешённые вами функции Feishu.', + 'detail.signed-out': 'Приложение Feishu привязано. Войдите в Feishu, чтобы использовать его в беседах.', + 'detail.unavailable': 'Текущие настройки и вход сохранены. Повторите попытку позже.', + 'detail.connected': 'Попросите агента использовать Feishu прямо в беседе.', + 'detail.connectedAs': 'Выполнен вход как {name}. Попросите агента использовать Feishu прямо в беседе.', + 'detail.configuring': 'Создайте или выберите приложение на странице Feishu, затем вернитесь сюда, чтобы войти. Если страница не открылась, нажмите «Открыть страницу Feishu».', + 'detail.authorizing': 'Подтвердите авторизацию на странице Feishu, затем вернитесь сюда, чтобы увидеть результат. Если страница не открылась, нажмите «Открыть страницу Feishu».', + hint: 'Аккаунт Feishu общий с Feishu CLI в терминале этого компьютера.', + 'app.linked': 'Приложение Feishu: {id}', + failed: 'Действие не завершено. Повторите попытку.', + 'failed.linkApp': 'Привязка приложения Feishu не завершена. Если страница Feishu сообщила об успехе, проверьте доступ DSH к локальной конфигурации и системным учётным данным, а при повторной привязке выберите уже существующее приложение.', + 'action.connect': 'Подключить Feishu', + 'action.linkApp': 'Привязать приложение Feishu', + 'action.signIn': 'Войти в Feishu', + 'action.open': 'Открыть страницу Feishu', + 'action.cancel': 'Отмена', + 'action.signOut': 'Выйти', + 'action.replaceApp': 'Сменить приложение', + 'action.retry': 'Повторить', + 'badge.connected': 'Подключено', + 'badge.disconnected': 'Не подключено', + 'badge.connecting': 'Подключение', + 'badge.unavailable': 'Не подтверждено', + 'signOut.title': 'Выйти из Feishu?', + 'signOut.body': 'Будет выполнен выход из аккаунта Feishu CLI по умолчанию, в том числе для lark-cli в терминале этого компьютера. Привязанное приложение Feishu сохранится.', + 'replaceApp.title': 'Сменить приложение Feishu?', + 'replaceApp.body': 'Откроется страница Feishu, где можно создать или выбрать приложение. После этого Feishu CLI на этом компьютере, включая lark-cli в терминале, будет настроен только на это приложение, и потребуется снова войти в Feishu.', + 'activation.title': 'Подключите аккаунт Feishu', + 'activation.body': 'Плагин Feishu включён. Подключите аккаунт Feishu, чтобы использовать его в беседах.', + 'notice.app-linked': 'Приложение Feishu привязано. Теперь войдите в Feishu.', + 'notice.connected': 'Feishu подключён', + 'notice.signed-out': 'Выполнен выход из Feishu', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + 'section.title': 'Conta do Feishu', + 'status.checking': 'Verificando a conexão', + 'status.disconnected': 'Não conectado', + 'status.unavailable': 'Não é possível confirmar o login no momento', + 'status.connected': 'Conectado', + 'step.configuring': 'Etapa 1: vincule um app do Feishu', + 'step.authorizing': 'Etapa 2: entre no Feishu', + 'step.connecting': 'Conectando', + 'step.signing-out': 'Saindo', + 'detail.no-app': 'Primeiro vincule um app do Feishu, novo ou já existente, e depois entre no Feishu. Em seguida, você poderá usar nas conversas os documentos, as mensagens e outros recursos do Feishu que autorizar.', + 'detail.signed-out': 'Há um app do Feishu vinculado. Entre no Feishu para usá-lo nas conversas.', + 'detail.unavailable': 'A configuração e o login atuais foram mantidos. Tente novamente mais tarde.', + 'detail.connected': 'Peça ao agente que use o Feishu diretamente em uma conversa.', + 'detail.connectedAs': 'Conectado como {name}. Peça ao agente que use o Feishu diretamente em uma conversa.', + 'detail.configuring': 'Crie ou escolha um app na página do Feishu e depois volte aqui para entrar. Se a página não abriu, selecione “Abrir página do Feishu”.', + 'detail.authorizing': 'Confirme a autorização na página do Feishu e depois volte aqui para ver o resultado. Se a página não abriu, selecione “Abrir página do Feishu”.', + hint: 'A conta do Feishu é compartilhada com a CLI do Feishu no terminal deste computador.', + 'app.linked': 'App do Feishu: {id}', + failed: 'A ação não foi concluída. Tente novamente.', + 'failed.linkApp': 'A vinculação do app do Feishu não foi concluída. Se a página do Feishu informou sucesso, verifique o acesso do DSH à configuração local e às credenciais do sistema e, ao vincular novamente, escolha o app existente.', + 'action.connect': 'Conectar Feishu', + 'action.linkApp': 'Vincular app do Feishu', + 'action.signIn': 'Entrar no Feishu', + 'action.open': 'Abrir página do Feishu', + 'action.cancel': 'Cancelar', + 'action.signOut': 'Sair', + 'action.replaceApp': 'Trocar app', + 'action.retry': 'Tentar novamente', + 'badge.connected': 'Conectado', + 'badge.disconnected': 'Não conectado', + 'badge.connecting': 'Conectando', + 'badge.unavailable': 'Não confirmado', + 'signOut.title': 'Sair do Feishu?', + 'signOut.body': 'Isso encerra a sessão da conta padrão da CLI do Feishu, incluindo o lark-cli no terminal deste computador. O app do Feishu vinculado é mantido.', + 'replaceApp.title': 'Trocar o app do Feishu?', + 'replaceApp.body': 'Uma página do Feishu será aberta para você criar ou escolher um app. Em seguida, a CLI do Feishu neste computador, incluindo o lark-cli no terminal, passa a usar apenas esse app, e você precisa entrar no Feishu novamente.', + 'activation.title': 'Conecte sua conta do Feishu', + 'activation.body': 'O plugin do Feishu está ativado. Conecte sua conta do Feishu para usá-lo nas conversas.', + 'notice.app-linked': 'App do Feishu vinculado. Agora entre no Feishu.', + 'notice.connected': 'Feishu conectado', + 'notice.signed-out': 'Você saiu do Feishu', +} + +/** The dictionary of every shipped language. */ +export const dictionaries = { zh, en, ja, es, fr, de, ru, pt } diff --git a/packages/connector/feishu/src/presentation.ts b/packages/connector/feishu/src/presentation.ts new file mode 100644 index 0000000000..74fad4b129 --- /dev/null +++ b/packages/connector/feishu/src/presentation.ts @@ -0,0 +1,144 @@ +/** The Feishu account section the Plugins page shows for each Host view. */ +import type { CliAccountText } from '@deepseek-ai/dsh-cli-account/types' +import type { + ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountNote, + ConnectorAccountOperation, +} from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { FeishuTextKey } from './locales.ts' +import type { FeishuAppId, FeishuOperationKind, FeishuState } from './types.ts' + +type Text = CliAccountText + +/** The npm package whose bundle page carries the account section. */ +export const FEISHU_PACKAGE = '@deepseek-ai/dsh-feishu' + +/* jscpd:ignore-start -- CLI app plugins declare page operations, copy, and commands alike, each with its own text. */ +/** + * List the operations the section's buttons start; each but a check reports a notice in the browser that started it. + * @param text - writes a key of the Feishu text in every shipped language. + * @returns the operations with their notices. + */ +export function operations(text: Text): readonly ConnectorAccountOperation[] { + return [ + { kind: 'check' }, + { kind: 'link-app', notice: text('notice.app-linked') }, + { kind: 'sign-in', notice: text('notice.connected') }, + { kind: 'sign-out', notice: text('notice.signed-out') }, + ] +} + +/** + * Write the section's title and hint, and the prompt after the bundle is switched on while disconnected. + * @param text - writes a key of the Feishu text in every shipped language. + * @returns the section's fixed text. + */ +export function copy(text: Text): ConnectorAccountCopy { + return { + title: text('section.title'), + hint: text('hint'), + activation: { title: text('activation.title'), body: text('activation.body'), connect: text('action.connect') }, + } +} + +const CHECK = { kind: 'start', operation: 'check' } as const +const LINK_APP = { kind: 'start', operation: 'link-app' } as const +const SIGN_IN = { kind: 'start', operation: 'sign-in' } as const +const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const +/* jscpd:ignore-end */ + +type Operation = NonNullable +type Step = 'step.configuring' | 'step.authorizing' | 'step.connecting' | 'step.signing-out' + +function step(operation: Operation): Step { + if (operation.kind === 'sign-out') return 'step.signing-out' + switch (operation.phase) { + case 'configuring': return 'step.configuring' + case 'authorizing': return 'step.authorizing' + case 'signing-out': return 'step.signing-out' + case 'checking': + case 'verifying': + case 'cancelling': return 'step.connecting' + /* v8 ignore next -- closed operation phase union */ + default: return assertNever(operation.phase) + } +} + +/** The section while an operation runs: its step, the Feishu page and its guidance while waiting there, and cancel. */ +function presentOperation(operation: Operation, text: Text): ConnectorAccountDisplay { + const current = step(operation) + const buttons: ConnectorAccountButton[] = [] + if (operation.authorizationUrl !== undefined) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) + if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + const guidance = operation.authorizationUrl === undefined ? undefined + : current === 'step.configuring' ? text('detail.configuring') + : current === 'step.authorizing' ? text('detail.authorizing') : undefined + return { + phase: 'connecting', status: text(current), badge: text('badge.connecting'), buttons, notes: [], + ...guidance === undefined ? {} : { detail: guidance }, + } +} + +/** The row that names the linked app and replaces it after a confirmation. */ +function appNotes(appId: FeishuAppId, text: Text): ConnectorAccountNote[] { + return [{ + text: text('app.linked', { id: appId }), + button: { + label: text('action.replaceApp'), command: LINK_APP, variant: 'ghost', + confirm: { title: text('replaceApp.title'), body: text('replaceApp.body'), label: text('action.replaceApp') }, + }, + }] +} + +/** The last failed operation's guidance; the Service adds the command and exit code. */ +function failureOf(result: FeishuState['result'], text: Text): { failure?: ConnectorAccountFailure } { + if (result?.outcome !== 'failed') return {} + return { failure: { text: text(result.kind === 'link-app' ? 'failed.linkApp' : 'failed') } } +} + +/** + * The account section for one Host view. + * @param view - the CLI's default account, the operation in progress, and the last result. + * @param text - writes a key of the Feishu text in every shipped language. + * @returns the phase, status, tag, buttons, detail, linked-app row, and failure guidance. + */ +export function presentAccount(view: FeishuState, text: Text): ConnectorAccountDisplay { + const { account, operation } = view + if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + if (operation !== undefined) return presentOperation(operation, text) + const failure = failureOf(view.result, text) + switch (account.state) { + case 'unchecked': return { phase: 'checking', status: text('status.checking'), buttons: [], notes: [] } + case 'unconfigured': + return { + phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), + buttons: [{ label: text('action.linkApp'), command: LINK_APP, variant: 'primary' }], connect: LINK_APP, + detail: text('detail.no-app'), notes: [], ...failure, + } + case 'signed-out': + return { + phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), + buttons: [{ label: text('action.signIn'), command: SIGN_IN, variant: 'primary' }], connect: SIGN_IN, + detail: text('detail.signed-out'), notes: appNotes(account.appId, text), ...failure, + } + case 'unverified': + return { + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes: appNotes(account.appId, text), ...failure, + } + /* jscpd:ignore-start -- CLI app plugins that sign out offer the same confirmed sign-out button. */ + case 'connected': + return { + phase: 'connected', status: text('status.connected'), badge: text('badge.connected'), + buttons: [{ + label: text('action.signOut'), command: SIGN_OUT, + confirm: { title: text('signOut.title'), body: text('signOut.body'), label: text('action.signOut') }, + }], + detail: account.userName === undefined ? text('detail.connected') : text('detail.connectedAs', { name: account.userName }), + notes: appNotes(account.appId, text), ...failure, + } + /* jscpd:ignore-end */ + /* v8 ignore next -- closed account state union */ + default: return assertNever(account) + } +} diff --git a/packages/connector/feishu/src/skills.ts b/packages/connector/feishu/src/skills.ts new file mode 100644 index 0000000000..e708c9e687 --- /dev/null +++ b/packages/connector/feishu/src/skills.ts @@ -0,0 +1,51 @@ +/** The packaged `feishu` entry skill: the DSH guidance, the index of the guides embedded in lark-cli, and how to open them. */ + +import { readFileSync } from 'node:fs' +import z from 'zod' +import { BUNDLED_SKILL_RANK, isSkillName } from '@deepseek-ai/dsh-skill' +import type { SkillCandidate, SkillDefinition, SkillProvider } from '@deepseek-ai/dsh-skill' +import { parse as parseYaml } from 'yaml' + +const Frontmatter = z.object({ name: z.string().refine(isSkillName), description: z.string().min(1) }) +const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u +/** The guides are not files: the loaded entry tells the model to open them through lark-cli. */ +const RESOURCES = 'Embedded lark-cli guides; open them with the skills read command given in the loaded skill.' + +/** Lists the packaged entry without running lark-cli; the entry is read once, when the plugin loads. */ +export class FeishuSkillProvider implements SkillProvider { + readonly name = 'feishu' + private readonly candidate: SkillCandidate + private readonly content: string + + /** + * @param entry - absolute path of the packaged `SKILL.md`, whose frontmatter gives the skill's name and description. + * @throws when the entry has no YAML frontmatter, or its frontmatter has no skill name or no description. + */ + constructor(entry: string) { + const raw = readFileSync(entry, 'utf8') + const match = FRONTMATTER.exec(raw) + const block = match?.[1] + if (match === null || block === undefined) throw new Error(`feishu: ${entry} has no YAML frontmatter`) + const parsed = Frontmatter.safeParse(parseYaml(block)) + if (!parsed.success) throw new Error(`feishu: ${entry} needs a skill name and a description in its frontmatter`, { cause: parsed.error }) + this.content = raw.slice(match[0].length).trim() + this.candidate = { + ...parsed.data, + invocation: { modelInvocable: true, userInvocable: true }, + provider: this.name, + source: 'bundled', + rank: BUNDLED_SKILL_RANK, + locator: entry, + resourceBase: { kind: 'opaque', description: RESOURCES }, + } + } + + list(): Promise { + return Promise.resolve([this.candidate]) + } + + get(): Promise { + const { rank: _rank, locator: _locator, ...summary } = this.candidate + return Promise.resolve({ ...summary, content: this.content }) + } +} diff --git a/packages/connector/feishu/src/types.ts b/packages/connector/feishu/src/types.ts new file mode 100644 index 0000000000..4dde98d734 --- /dev/null +++ b/packages/connector/feishu/src/types.ts @@ -0,0 +1,25 @@ +/** Credential-free Feishu account and operation views the Plugins page presenter reads. */ + +import type { Branded } from '@deepseek-ai/dsh-brand' +import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' + +/** The Feishu app the CLI's default configuration uses, as `auth status` reports it. */ +export type FeishuAppId = Branded<'FeishuAppId'> + +/** The CLI's default account as the latest check observed it. */ +export type FeishuAccountState = + | { readonly state: 'unchecked' | 'unconfigured' } + | { readonly state: 'signed-out' | 'unverified'; readonly appId: FeishuAppId } + | { readonly state: 'connected'; readonly appId: FeishuAppId; readonly userName?: string } + +/** The account operations the Plugins page starts. */ +export type FeishuOperationKind = 'check' | 'link-app' | 'sign-in' | 'sign-out' + +/** Feishu steps of an operation, besides the Service's `checking` and `cancelling`. */ +export type FeishuPhase = 'configuring' | 'authorizing' | 'verifying' | 'signing-out' + +/** The lark-cli commands an operation runs; a failed operation reports its last one with that command's exit code. */ +export type FeishuCommand = 'config-init' | 'auth-status' | 'auth-login' | 'auth-logout' + +/** The complete Feishu view the presenter reads after each change. */ +export type FeishuState = CliAccountView diff --git a/packages/connector/feishu/tests/account.spec.ts b/packages/connector/feishu/tests/account.spec.ts new file mode 100644 index 0000000000..31bcb9e1a3 --- /dev/null +++ b/packages/connector/feishu/tests/account.spec.ts @@ -0,0 +1,224 @@ +/** Account operations over a scripted lark-cli: checks, app linking, sign-in, sign-out, cancellation, and the Plugins page wiring. */ +import { rm } from 'node:fs/promises' +import type { Context } from '@deepseek-ai/cordis' +import type { ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import * as Feishu from '../src/index.ts' +import type { FeishuAppId, FeishuOperationKind, FeishuState } from '../src/types.ts' +import { createHost, type CliReply, type FeishuPage, type ScriptedProcess, type ScriptedSubprocess } from './harness.ts' + +const APP = 'cli_a' as FeishuAppId +const STATUS = 'auth status --verify --json' +const NOT_CONFIGURED: CliReply = { exitCode: 3, stderr: JSON.stringify({ ok: false, error: { type: 'config', subtype: 'not_configured', message: 'not configured' } }) } +const status = (user: Record): CliReply => ({ stdout: JSON.stringify({ appId: APP, identities: { user } }) }) +const CONNECTED = status({ status: 'ready', available: true, verified: true, userName: '张三', openId: 'ou_1' }) +const SIGNED_OUT = status({ status: 'missing', available: false }) +const LOGIN_LINK = JSON.stringify({ event: 'device_authorization', verification_uri_complete: 'https://accounts.feishu.cn/oauth/device?code=1' }) +const login = (missing: string[] = [], openId = 'ou_1') => JSON.stringify({ event: 'authorization_complete', user_open_id: openId, missing }) + +type Script = (process: ScriptedProcess) => void + +let ctx: Context +let subprocess: ScriptedSubprocess +let binDir: string +/** The account the plugin registered, as the Plugins page registry drives it. */ +let account: FeishuPage['source'] +let script: Record + +beforeEach(async () => { + const host = await createHost() + ;({ ctx, subprocess, binDir } = host) + await ctx.plugin(Feishu, { binDir }) + account = host.pages[0]!.source + script = {} + subprocess.respond = (process) => { + const handler = script[process.spec.argv.slice(1).join(' ')] + if (handler === undefined) process.reply({ exitCode: 1, stderr: `unexpected: ${process.spec.argv.join(' ')}` }) + else if (Array.isArray(handler)) process.reply(handler.length > 1 ? handler.shift()! : handler[0]!) + else handler(process) + } +}) + +afterEach(async () => { + await ctx.fiber.dispose() + await rm(binDir, { recursive: true, force: true }) +}) + +/** Start an operation as a page button does; the CLI account Service starts it before returning. */ +const start = (kind: FeishuOperationKind): ConnectorOperationId => { + const id = account.start(kind) + if (typeof id !== 'string') throw new Error('the operation did not start at once') + return id +} +const commands = () => subprocess.processes.map(process => process.spec.argv.slice(1).join(' ')) +const errors = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'error').map((message): unknown => message.args) + +describe('Feishu account operations', () => { + const settled = async (id: ConnectorOperationId): Promise => { + await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) }) + return account.snapshot() + } + + it.each<[string, CliReply, FeishuState['account']]>([ + ['no app', NOT_CONFIGURED, { state: 'unconfigured' }], + ['a verified user', CONNECTED, { state: 'connected', appId: APP, userName: '张三' }], + ['a verified user without a name', status({ status: 'ready', available: true, verified: true }), { state: 'connected', appId: APP }], + ['a missing user', SIGNED_OUT, { state: 'signed-out', appId: APP }], + ['an expired user', status({ status: 'needs_refresh', available: true, verified: false }), { state: 'signed-out', appId: APP }], + ['a failed verification', status({ status: 'verify_failed', available: true, verified: false }), { state: 'unverified', appId: APP }], + ])('checks %s', async (_name, reply, expected) => { + script[STATUS] = [reply] + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking', cancellable: false }) + expect(await settled(id)).toEqual({ account: expected, result: { id, kind: 'check', outcome: 'succeeded' } }) + }) + + it.each<[string, CliReply]>([ + ['an unexpected status failure', { exitCode: 1, stderr: '{"ok":false,"error":{"subtype":"network"}}' }], + ['a status failure without JSON', { exitCode: 1, stderr: 'boom' }], + ])('keeps the previous account and fails on %s', async (_name, reply) => { + script[STATUS] = [reply] + expect(await settled(start('check'))).toMatchObject({ account: { state: 'unchecked' }, result: { outcome: 'failed' } }) + }) + + it('links an app through its setup page, offers only the first trusted link, and stops before sign-in', async () => { + script[STATUS] = [SIGNED_OUT] + const setup = Promise.withResolvers() + script['config init --new'] = (process) => { setup.resolve(process) } + + const id = start('link-app') + const configuring = await setup.promise + expect(account.snapshot().operation).toEqual({ id, kind: 'link-app', phase: 'configuring', cancellable: true }) + configuring.write('stderr', 'Open this link:\n http://open.feishu.cn/page/cli?x=1\n https://evil.example/page\n') + configuring.write('stderr', ' https://open.feishu.cn/page/cli?x=2\n https://open.feishu.cn/page/cli?x=3\n') + await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'configuring', authorizationUrl: 'https://open.feishu.cn/page/cli?x=2' }) }) + configuring.reply({}) + + expect(await settled(id)).toEqual({ account: { state: 'signed-out', appId: APP }, result: { id, kind: 'link-app', outcome: 'succeeded' } }) + expect(commands()).toEqual(['config init --new', STATUS]) + expect(errors()).toEqual([]) + }) + + it('reports safe setup diagnostics to the page and Host without retrying or exposing native output', async () => { + script[STATUS] = [NOT_CONFIGURED] + await settled(start('check')) + const sensitive = 'secret-in-native-output' + script['config init --new'] = [{ exitCode: 5, stdout: sensitive, stderr: `QR\nhttps://open.feishu.cn/?user_code=${sensitive}\nApp created\n${JSON.stringify({ + ok: false, error: { type: 'internal', subtype: 'sdk_error', message: sensitive, hint: sensitive }, + }, null, 2)}\n` }] + + const result = await settled(start('link-app')) + expect(result).toMatchObject({ account: { state: 'unconfigured' }, result: { + outcome: 'failed', failure: { command: 'config-init', exitCode: 5 }, + } }) + expect(errors()).toEqual([['feishu: account operation failed: %o', { + id: result.result?.id, kind: 'link-app', phase: 'configuring', + command: 'config-init', exitCode: 5, + }]]) + expect(JSON.stringify({ result, errors: errors() })).not.toContain(sensitive) + expect(commands()).toEqual([STATUS, 'config init --new']) + }) + + it('attributes a post-setup check failure to auth status', async () => { + script['config init --new'] = [{}] + script[STATUS] = [{ exitCode: 5, stderr: '{"ok":false,"error":{"type":"internal","subtype":"storage"}}' }] + + expect(await settled(start('link-app'))).toMatchObject({ result: { + outcome: 'failed', failure: { command: 'auth-status', exitCode: 5 }, + } }) + }) + + it('retains the observed exit code when the command response is invalid', async () => { + script[STATUS] = [{ stdout: 'invalid-json-secret' }] + const result = await settled(start('check')) + expect(result).toMatchObject({ result: { outcome: 'failed', failure: { command: 'auth-status', exitCode: 0 } } }) + expect(JSON.stringify({ result, errors: errors() })).not.toContain('invalid-json-secret') + }) + + it('signs in through the authorization page and accepts a sign-in that leaves permissions ungranted', async () => { + script[STATUS] = [CONNECTED] + const signIn = Promise.withResolvers() + script['auth login --json'] = (process) => { signIn.resolve(process) } + + const id = start('sign-in') + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing', cancellable: true }) + const authorizing = await signIn.promise + const invalid = JSON.stringify({ event: 'device_authorization', verification_uri_complete: 'not a url' }) + authorizing.write('stdout', `progress\n{"event":"other"}\n${invalid}\n${LOGIN_LINK}\n`) + await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: 'https://accounts.feishu.cn/oauth/device?code=1' }) }) + authorizing.reply({ stdout: login(['im:message']) + '\n', exitCode: 3 }) + + expect(await settled(id)).toEqual({ + account: { state: 'connected', appId: APP, userName: '张三' }, + result: { id, kind: 'sign-in', outcome: 'succeeded' }, + }) + expect(commands()).toEqual(['auth login --json', STATUS]) + }) + + it.each<[string, 'link-app' | 'sign-in', Record]>([ + ['a failed app setup', 'link-app', { 'config init --new': [{ exitCode: 1 }] }], + ['an app setup that left no app', 'link-app', { [STATUS]: [NOT_CONFIGURED], 'config init --new': [{}] }], + ['a sign-in without completion', 'sign-in', { 'auth login --json': [{ stdout: LOGIN_LINK + '\n' }] }], + ['a failed sign-in', 'sign-in', { 'auth login --json': [{ stdout: login() + '\n', exitCode: 1 }] }], + ['a partial sign-in that reports no missing permission', 'sign-in', { 'auth login --json': [{ stdout: login() + '\n', exitCode: 3 }] }], + ['a different signed-in user', 'sign-in', { [STATUS]: [CONNECTED], 'auth login --json': [{ stdout: login([], 'ou_2') + '\n' }] }], + ['an unverified sign-in', 'sign-in', { [STATUS]: [SIGNED_OUT], 'auth login --json': [{ stdout: login() + '\n' }] }], + ])('fails on %s', async (_name, kind, replies) => { + Object.assign(script, replies) + expect((await settled(start(kind))).result).toMatchObject({ kind, outcome: 'failed' }) + }) + + it('signs out without offering cancellation and reports a rejected sign-out', async () => { + script[STATUS] = [SIGNED_OUT] + script['auth logout --json'] = [{ stdout: '{"ok":true}' }, { exitCode: 1 }] + const id = start('sign-out') + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-out', phase: 'signing-out', cancellable: false }) + expect(await settled(id)).toEqual({ account: { state: 'signed-out', appId: APP }, result: { id, kind: 'sign-out', outcome: 'succeeded' } }) + expect((await settled(start('sign-out'))).result).toMatchObject({ + kind: 'sign-out', outcome: 'failed', failure: { command: 'auth-logout', exitCode: 1 }, + }) + }) +}) + +describe('Feishu on the Plugins page', () => { + const finished = async (id: ConnectorOperationId): Promise => { + await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) }) + return account.snapshot().result + } + + it('checks on refresh, then starts checks, app links, sign-ins, and sign-outs one at a time and cancels them', async () => { + script[STATUS] = [SIGNED_OUT] + account.refresh() + const check = account.snapshot().operation + expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked' }, operation: { kind: 'check' } }) + expect(await finished(check!.id)).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + expect(account.snapshot().account).toEqual({ state: 'signed-out', appId: APP }) + + script['auth logout --json'] = [{ stdout: '{"ok":true}' }] + const signingOut = start('sign-out') + expect(() => start('sign-in')).toThrow('another account operation is in progress') + await account.cancel(signingOut) + expect(await finished(signingOut)).toMatchObject({ kind: 'sign-out', outcome: 'succeeded' }) + expect(await finished(start('check'))).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + + script['config init --new'] = () => {} + const linking = start('link-app') + await vi.waitFor(() => { expect(commands().at(-1)).toBe('config init --new') }) + await account.cancel(linking) + expect(await finished(linking)).toMatchObject({ kind: 'link-app', outcome: 'cancelled' }) + script['auth login --json'] = () => {} + const signingIn = start('sign-in') + await vi.waitFor(() => { expect(commands().at(-1)).toBe('auth login --json') }) + await account.cancel(signingIn) + expect(await finished(signingIn)).toMatchObject({ kind: 'sign-in', outcome: 'cancelled' }) + expect(subprocess.processes.at(-1)?.terminated).toBe(true) + }) + + it('stops account work on disposal', async () => { + script[STATUS] = () => {} + account.refresh() + await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) + await ctx.fiber.dispose() + expect(subprocess.processes[0]?.terminated).toBe(true) + }) +}) diff --git a/packages/connector/feishu/tests/cli.spec.ts b/packages/connector/feishu/tests/cli.spec.ts new file mode 100644 index 0000000000..ecf9fe7bbf --- /dev/null +++ b/packages/connector/feishu/tests/cli.spec.ts @@ -0,0 +1,37 @@ +import { constants } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { beforeEach, expect, it, vi } from 'vitest' +import { executableFileName, parseJson, resolveCliExecutable } from '../src/cli.ts' + +const fs = vi.hoisted(() => ({ accessSync: vi.fn() })) +vi.mock('node:fs', async importOriginal => ({ ...await importOriginal(), accessSync: fs.accessSync })) + +const PACKAGE_BIN = join(dirname(fileURLToPath(import.meta.resolve('@larksuite/cli/package.json'))), 'bin') +const FILE = process.platform === 'win32' ? 'lark-cli.exe' : 'lark-cli' + +beforeEach(() => { + fs.accessSync.mockReset() +}) + +it('names the executable file with the .exe extension on Windows only', () => { + expect(executableFileName('win32')).toBe('lark-cli.exe') + expect(executableFileName('darwin')).toBe('lark-cli') +}) + +it('defaults to the executable in the installed @larksuite/cli bin directory', () => { + expect(resolveCliExecutable(undefined)).toBe(join(PACKAGE_BIN, FILE)) + expect(fs.accessSync).toHaveBeenCalledWith(join(PACKAGE_BIN, FILE), constants.X_OK) +}) + +it('accepts a configured directory and names the missing executable with the install remedy', () => { + expect(resolveCliExecutable('/opt/lark/bin')).toBe(join('/opt/lark/bin', FILE)) + fs.accessSync.mockImplementation(() => { throw new Error('EACCES') }) + expect(() => resolveCliExecutable(PACKAGE_BIN)) + .toThrow(`feishu: ${join(PACKAGE_BIN, FILE)} is not executable; approve the @larksuite/cli install script or set binDir`) +}) + +it('parses a command\'s JSON output and names the command whose output is not JSON', () => { + expect(parseJson(['auth', 'status'], '{"ok":false}')).toEqual({ ok: false }) + expect(() => parseJson(['auth', 'status'], '')).toThrow('lark-cli auth status returned invalid JSON') +}) diff --git a/packages/connector/feishu/tests/harness.ts b/packages/connector/feishu/tests/harness.ts new file mode 100644 index 0000000000..0e6989aab9 --- /dev/null +++ b/packages/connector/feishu/tests/harness.ts @@ -0,0 +1,152 @@ +/** A Host for Feishu plugin specs: scripted lark-cli processes, a temporary bin directory, and a recording Plugins page registry. */ + +import { chmod, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { PassThrough } from 'node:stream' +import { Context } from '@deepseek-ai/cordis' +import CliAccounts from '@deepseek-ai/dsh-cli-account' +import type { ConnectorAccountRegistration } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import SkillRegistry from '@deepseek-ai/dsh-skill' +import { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import type { + SubprocessCollectedOutputs, + SubprocessHandle, + SubprocessOutcome, + SubprocessSpawnSpec, + SubprocessTerminalEnvironment, +} from '@deepseek-ai/dsh-subprocess' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import { executableFileName } from '../src/cli.ts' +import type { FeishuState } from '../src/types.ts' + +/** Output and exit facts one scripted command reports. */ +export interface CliReply { + stdout?: string + stderr?: string + exitCode?: number | null + signal?: NodeJS.Signals | null +} + +/** A piped process whose managed range exits on termination. */ +export class ScriptedProcess implements SubprocessHandle { + readonly stdin = undefined + readonly stdout = new PassThrough() + readonly stderr = new PassThrough() + readonly control = undefined + readonly collected: SubprocessCollectedOutputs = {} + readonly done: Promise + terminated = false + private readonly outcome = Promise.withResolvers() + private readonly exit = Promise.withResolvers() + + constructor(readonly spec: SubprocessSpawnSpec) { + this.done = this.outcome.promise + spec.signal?.addEventListener('abort', () => { this.terminate() }, { once: true }) + } + + /** Write output while the command keeps running. */ + write(stream: 'stdout' | 'stderr', text: string): void { + this[stream].write(text) + } + + /** Finish the command with the given output; the managed range stays alive until termination. */ + reply(reply: CliReply): void { + if (reply.stdout !== undefined) this.stdout.write(reply.stdout) + if (reply.stderr !== undefined) this.stderr.write(reply.stderr) + this.close() + this.outcome.resolve({ exitCode: reply.exitCode === undefined ? 0 : reply.exitCode, signal: reply.signal ?? null }) + } + + terminate(): void { + this.terminated = true + this.close() + this.outcome.resolve({ exitCode: null, signal: 'SIGTERM' }) + this.exit.resolve(true) + } + + private close(): void { + if (!this.stdout.writableEnded) this.stdout.end() + if (!this.stderr.writableEnded) this.stderr.end() + } + + waitForExit(): Promise { + return this.exit.promise + } +} + +/** Host subprocess runtime whose lookups and spawns are recorded and answered by `respond`. */ +export class ScriptedSubprocess extends SubprocessRuntime { + readonly lookups: Array<{ command: string; env: Readonly> | undefined }> = [] + readonly processes: ScriptedProcess[] = [] + lookup: (signal?: AbortSignal) => Promise = () => Promise.resolve('/fixture/bin/lark-cli') + respond: (process: ScriptedProcess) => void | Promise = (process) => { process.reply({ stdout: '{}' }) } + + override resolveExecutable(command: string, env?: Readonly>, signal?: AbortSignal): Promise { + this.lookups.push({ command, env }) + return this.lookup(signal) + } + + override terminalEnvironment(): Promise { + return Promise.resolve({ platform: 'posix' }) + } + + override spawn(spec: SubprocessSpawnSpec): ScriptedProcess { + spec.signal?.throwIfAborted() + const process = new ScriptedProcess(spec) + this.processes.push(process) + queueMicrotask(() => { void this.respond(process) }) + return process + } + + override spawnTerminal(): Promise { + throw new Error('lark-cli commands never allocate a terminal') + } +} + +/** + * Create a temporary directory holding an executable `lark-cli` placeholder, `lark-cli.exe` on Windows. + * @returns the absolute bin directory. + */ +export async function createBinDir(): Promise { + const directory = await mkdtemp(join(tmpdir(), 'dsh-feishu-bin-')) + await writeFile(join(directory, executableFileName(process.platform)), '') + await chmod(join(directory, executableFileName(process.platform)), 0o755) + return directory +} + +/** What the Feishu plugin registers for the Plugins page. */ +export type FeishuPage = ConnectorAccountRegistration + +/** The services the Feishu plugin runs on, before the plugin itself loads. */ +export interface FeishuHost { + readonly ctx: Context + readonly subprocess: ScriptedSubprocess + /** The `binDir` to load the plugin with. */ + readonly binDir: string + /** Every account registered for the Plugins page, in order; the registry keeps them after withdrawal. */ + readonly pages: FeishuPage[] + /** How many of those accounts were withdrawn. */ + withdrawn: number +} + +/** + * Start a Host with the skill registry, a scripted subprocess runtime, the system prompt, a Plugins page registry that + * records registrations, and the CLI account Service with a 5-second command deadline. + * @returns the Host; the caller loads the Feishu plugin with `binDir`, disposes `ctx.fiber`, and removes `binDir`. + */ +export async function createHost(): Promise { + const ctx = new Context() + await ctx.plugin(SkillRegistry) + await ctx.plugin(ScriptedSubprocess) + await ctx.plugin(SystemPrompt) + const host: FeishuHost = { ctx, subprocess: ctx.subprocess as ScriptedSubprocess, binDir: await createBinDir(), pages: [], withdrawn: 0 } + ctx.provide('connectorAccounts', { + register: (page: FeishuPage) => { + host.pages.push(page) + return () => { host.withdrawn += 1 } + }, + }) + await ctx.plugin(CliAccounts, { commandTimeoutMs: 5_000 }) + return host +} diff --git a/packages/connector/feishu/tests/plugin.spec.ts b/packages/connector/feishu/tests/plugin.spec.ts new file mode 100644 index 0000000000..8d000cfb68 --- /dev/null +++ b/packages/connector/feishu/tests/plugin.spec.ts @@ -0,0 +1,91 @@ +import { readFile, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Context } from '@deepseek-ai/cordis' +import { renderContextSections } from '@deepseek-ai/dsh-system-prompt' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { cliPathContextText } from '@deepseek-ai/dsh-cli-account/src/context.ts' +import { executableFileName } from '../src/cli.ts' +import * as Feishu from '../src/index.ts' +import { FEISHU_PACKAGE } from '../src/presentation.ts' +import { createHost, type FeishuHost, type ScriptedSubprocess } from './harness.ts' + +const ENTRY = fileURLToPath(new URL('../skills/feishu/SKILL.md', import.meta.url)) + +describe('Config', () => { + it('takes the CLI directory, which is optional and never empty', () => { + expect(Feishu.Config({})).toEqual({}) + expect(Feishu.Config({ binDir: '/opt/lark/bin' })).toEqual({ binDir: '/opt/lark/bin' }) + expect(() => Feishu.Config({ binDir: '' })).toThrow() + }) +}) + +describe('Feishu plugin', () => { + let host: FeishuHost + let ctx: Context + let subprocess: ScriptedSubprocess + let binDir: string + let warnings: string[] + + beforeEach(async () => { + host = await createHost() + ;({ ctx, subprocess, binDir } = host) + warnings = [] + ctx.logger.warn = ((message: unknown) => { warnings.push(String(message)) }) as typeof ctx.logger.warn + }) + + afterEach(async () => { + await ctx.fiber.dispose() + await rm(binDir, { recursive: true, force: true }) + }) + + const runtimeContext = async () => renderContextSections(await ctx.systemPrompt.assemble()) + + it('lists the packaged feishu skill and loads its entry without running lark-cli', async () => { + await ctx.plugin(Feishu, { binDir }) + + expect(await ctx.skills.list()).toEqual([{ + name: 'feishu', + description: expect.stringContaining('Load it before any Feishu or Lark task') as string, + invocation: { modelInvocable: true, userInvocable: true }, + provider: 'feishu', + source: 'bundled', + resourceBase: { kind: 'opaque', description: 'Embedded lark-cli guides; open them with the skills read command given in the loaded skill.' }, + }]) + + const loaded = await ctx.skills.get('feishu') + const file = await readFile(ENTRY, 'utf8') + expect(loaded?.content.trim()).toBe(file.slice(file.indexOf('\n---\n', 4) + '\n---\n'.length).trim()) + expect(loaded?.content).toContain('# Feishu in DSH') + expect(loaded?.content).toContain('open one with `lark-cli skills read ` in the Host Shell, not with the skill tool') + expect(subprocess.lookups).toEqual([]) + expect(subprocess.processes).toEqual([]) + expect(warnings).toEqual([]) + }) + + it('withdraws the runtime context and the skill on disposal', async () => { + const fiber = await ctx.plugin(Feishu, { binDir }) + expect(await runtimeContext()).toEqual([{ + name: 'feishu:cli', + text: cliPathContextText({ product: 'Feishu', program: 'lark-cli', executable: join(binDir, executableFileName(process.platform)) }, process.platform), + }]) + expect((await ctx.skills.list()).map(skill => skill.name)).toEqual(['feishu']) + + await fiber.dispose() + + expect(await runtimeContext()).toEqual([]) + expect(await ctx.skills.list()).toEqual([]) + expect(warnings).toEqual([]) + }) + + it('shows the account on the Plugins page while the registry runs, and withdraws it with the plugin', async () => { + const fiber = await ctx.plugin(Feishu, { binDir }) + expect(host.pages).toHaveLength(1) + expect(host.pages[0]).toMatchObject({ key: FEISHU_PACKAGE, packageName: FEISHU_PACKAGE }) + expect(host.pages[0]!.source.snapshot().account.state).toBe('unchecked') + + await fiber.dispose() + + expect(host.withdrawn).toBe(1) + }) +}) diff --git a/packages/connector/feishu/tests/presentation.spec.ts b/packages/connector/feishu/tests/presentation.spec.ts new file mode 100644 index 0000000000..61fd722166 --- /dev/null +++ b/packages/connector/feishu/tests/presentation.spec.ts @@ -0,0 +1,149 @@ +/** The Feishu section offers each state's next step, the linked app, confirmations, and failure guidance, in every shipped language. */ +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountDisplay, ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { rm } from 'node:fs/promises' +import { afterAll, beforeAll, expect, it } from 'vitest' +import * as Feishu from '../src/index.ts' +import { en, zh, type FeishuTextKey } from '../src/locales.ts' +import type { FeishuAppId, FeishuState } from '../src/types.ts' +import { createHost, type FeishuHost, type FeishuPage } from './harness.ts' + +const OP = 'op' as ConnectorOperationId +const APP = 'cli_a' as FeishuAppId +const LINK = 'https://x.feishu.cn' +const CHECK = { kind: 'start', operation: 'check' } as const +const LINK_APP = { kind: 'start', operation: 'link-app' } as const +const SIGN_IN = { kind: 'start', operation: 'sign-in' } as const +const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const + +/** The key's text as the Chinese and English browsers resolve it. */ +const say = (key: FeishuTextKey): Partial> => ({ zh: zh[key], en: en[key] }) +const zhOf = (text: LocalizedText | undefined): string | undefined => typeof text === 'object' ? text.zh : text +const labels = (display: ConnectorAccountDisplay): (string | undefined)[] => display.buttons.map(button => zhOf(button.label)) + +let host: FeishuHost +/** What the plugin registered for the Plugins page, with the failure details the CLI account Service adds. */ +let page: FeishuPage + +beforeAll(async () => { + host = await createHost() + await host.ctx.plugin(Feishu, { binDir: host.binDir }) + page = host.pages[0]! +}) + +afterAll(async () => { + await host.ctx.fiber.dispose() + await rm(host.binDir, { recursive: true, force: true }) +}) + +const presentAccount = (view: FeishuState): ConnectorAccountDisplay => page.present(view) + +const UNCONFIGURED: FeishuState = { account: { state: 'unconfigured' } } +const SIGNED_OUT: FeishuState = { account: { state: 'signed-out', appId: APP } } + +it('links an app first, then signs in, with each step\'s page, guidance, and cancel', () => { + let shown = presentAccount(UNCONFIGURED) + expect(shown).toMatchObject({ + phase: 'disconnected', status: say('status.disconnected'), badge: say('badge.disconnected'), + detail: say('detail.no-app'), connect: LINK_APP, notes: [], + }) + expect(shown.buttons).toMatchObject([{ label: say('action.linkApp'), command: LINK_APP, variant: 'primary' }]) + + shown = presentAccount({ ...UNCONFIGURED, operation: { id: OP, kind: 'link-app', phase: 'configuring', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'connecting', status: say('step.configuring'), badge: say('badge.connecting') }) + expect(labels(shown)).toEqual([zh['action.cancel']]) + expect(shown.detail).toBeUndefined() + shown = presentAccount({ ...UNCONFIGURED, operation: { id: OP, kind: 'link-app', phase: 'configuring', cancellable: true, authorizationUrl: LINK } }) + expect(shown.detail).toMatchObject(say('detail.configuring')) + + shown = presentAccount(SIGNED_OUT) + expect(shown).toMatchObject({ phase: 'disconnected', detail: say('detail.signed-out'), connect: SIGN_IN }) + expect(shown.buttons).toMatchObject([{ label: say('action.signIn'), command: SIGN_IN, variant: 'primary' }]) + + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true, authorizationUrl: LINK } }) + expect(shown).toMatchObject({ status: say('step.authorizing'), detail: say('detail.authorizing') }) + expect(shown.buttons.map(button => button.command)).toEqual([{ kind: 'open' }, { kind: 'cancel' }]) + + for (const [phase, status] of [['verifying', 'step.connecting'], ['checking', 'step.connecting'], ['cancelling', 'step.connecting']] as const) { + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase, cancellable: false } }) + expect(shown).toMatchObject({ status: say(status), buttons: [] }) + } + + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-out', phase: 'signing-out', cancellable: false, authorizationUrl: LINK } }) + expect(shown).toMatchObject({ status: say('step.signing-out') }) + expect(shown.detail).toBeUndefined() + expect(labels(shown)).toEqual([zh['action.open']]) + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'link-app', phase: 'signing-out', cancellable: false } }) + expect(shown).toMatchObject({ status: say('step.signing-out') }) + + for (const view of [ + { ...SIGNED_OUT, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, + { account: { state: 'unchecked' } }, + ] as const satisfies readonly FeishuState[]) { + shown = presentAccount(view) + expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [], notes: [] }) + expect(shown.badge).toBeUndefined() + } +}) + +it('retries an unconfirmed sign-in by checking again', () => { + const shown = presentAccount({ account: { state: 'unverified', appId: APP } }) + expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable') }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) +}) + +it('reports app-link recovery with the command and exit code', () => { + let shown = presentAccount({ + ...UNCONFIGURED, + result: { id: OP, kind: 'link-app', outcome: 'failed', failure: { command: 'config-init', exitCode: 1 } }, + }) + expect(labels(shown)).toEqual([zh['action.linkApp']]) + expect(shown.failure).toMatchObject({ text: say('failed.linkApp'), details: ['config-init', 'exit 1'] }) + + shown = presentAccount({ ...SIGNED_OUT, result: { id: OP, kind: 'link-app', outcome: 'failed', failure: { command: 'auth-status', exitCode: null } } }) + expect(labels(shown)).toEqual([zh['action.signIn']]) + expect(shown.failure).toMatchObject({ text: say('failed.linkApp'), details: ['auth-status'] }) + + expect(presentAccount({ ...UNCONFIGURED, result: { id: OP, kind: 'link-app', outcome: 'cancelled' } }).failure).toBeUndefined() +}) + +it.each(['sign-in', 'sign-out', 'check'] as const)('keeps the generic guidance for a failed %s', (kind) => { + const failure = presentAccount({ ...SIGNED_OUT, result: { id: OP, kind, outcome: 'failed' } }).failure + expect(failure).toMatchObject({ text: say('failed') }) + expect(failure).not.toHaveProperty('details') +}) + +it('shows who is signed in and asks before signing out', () => { + expect(zhOf(presentAccount({ account: { state: 'connected', appId: APP, userName: '张三' } }).detail)).toBe(zh['detail.connectedAs'].replace('{name}', '张三')) + const shown = presentAccount({ account: { state: 'connected', appId: APP } }) + expect(shown).toMatchObject({ phase: 'connected', status: say('status.connected'), badge: say('badge.connected'), detail: say('detail.connected') }) + expect(shown.buttons).toMatchObject([{ + label: say('action.signOut'), command: SIGN_OUT, + confirm: { title: say('signOut.title'), body: say('signOut.body'), label: say('action.signOut') }, + }]) +}) + +it('shows the linked app and asks before changing it', () => { + for (const view of [SIGNED_OUT, { account: { state: 'unverified', appId: APP } }, { account: { state: 'connected', appId: APP } }] as const satisfies readonly FeishuState[]) { + const [note] = presentAccount(view).notes + expect(zhOf(note?.text)).toBe(zh['app.linked'].replace('{id}', 'cli_a')) + expect(note?.button).toMatchObject({ + label: say('action.replaceApp'), command: LINK_APP, variant: 'ghost', + confirm: { title: say('replaceApp.title'), body: say('replaceApp.body'), label: say('action.replaceApp') }, + }) + } +}) + +it('names the section, its activation prompt, and the notice of each page operation', () => { + expect(page.copy).toMatchObject({ + title: say('section.title'), hint: say('hint'), + activation: { title: say('activation.title'), body: say('activation.body'), connect: say('action.connect') }, + }) + expect(page.operations).toMatchObject([ + { kind: 'check' }, + { kind: 'link-app', notice: say('notice.app-linked') }, + { kind: 'sign-in', notice: say('notice.connected') }, + { kind: 'sign-out', notice: say('notice.signed-out') }, + ]) + expect(page.operations[0]).not.toHaveProperty('notice') +}) diff --git a/packages/connector/feishu/tests/skills.spec.ts b/packages/connector/feishu/tests/skills.spec.ts new file mode 100644 index 0000000000..8e9cbd38ad --- /dev/null +++ b/packages/connector/feishu/tests/skills.spec.ts @@ -0,0 +1,70 @@ +/** The packaged entry skill: its index names exactly the guides lark-cli 1.0.97 embeds, and it stays below the pruner threshold. */ +import { readdirSync, readFileSync } from 'node:fs' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { renderSkillContent } from '@deepseek-ai/dsh-skill' +import { expect, it } from 'vitest' +import { FeishuSkillProvider } from '../src/skills.ts' + +const skills = fileURLToPath(new URL('../skills/', import.meta.url)) +const entry = join(skills, 'feishu') + +/** The guides `lark-cli skills list` reports in the pinned `@larksuite/cli` 1.0.97. */ +const GUIDES = [ + 'lark-approval', 'lark-apps', 'lark-attendance', 'lark-base', 'lark-calendar', 'lark-contact', 'lark-doc', 'lark-drive', + 'lark-event', 'lark-im', 'lark-mail', 'lark-markdown', 'lark-meeting', 'lark-minutes', 'lark-note', 'lark-okr', + 'lark-openapi-explorer', 'lark-shared', 'lark-sheets', 'lark-skill-maker', 'lark-slides', 'lark-task', 'lark-vc', + 'lark-vc-agent', 'lark-whiteboard', 'lark-wiki', 'lark-workflow-meeting-summary', 'lark-workflow-standup-report', +] + +/** + * `packages/bundle/web-app/presets/standard.patch.yml` prunes a tool result only above `thresholdChars: 8192` + * code points; a skill result below it reaches the model intact. + */ +const PRUNER_THRESHOLD_CHARS = 8192 + +/** The body the `skill` tool returns: the file without its YAML frontmatter. */ +function body(): string { + const text = readFileSync(join(entry, 'SKILL.md'), 'utf8') + const end = text.indexOf('\n---\n', 4) + return text.slice(end + '\n---\n'.length) +} + +it('ships only the feishu entry; its guides stay in lark-cli', () => { + expect(readdirSync(skills, { recursive: true }).toSorted()).toEqual(['feishu', join('feishu', 'SKILL.md')]) +}) + +it('renders the entry below the pruner threshold', () => { + const rendered = renderSkillContent({ name: 'feishu', provider: 'feishu', resourceBase: { kind: 'directory', path: entry }, content: body() }) + expect(Array.from(rendered).length).toBeLessThan(PRUNER_THRESHOLD_CHARS) +}) + +it('indexes every guide of the pinned lark-cli exactly once', () => { + const indexed = [...body().matchAll(/^- `([a-z-]+)`:/gmu)].map(match => match[1] ?? '') + expect(indexed.toSorted()).toEqual(GUIDES) +}) + +it('lists the entry with an opaque resource base and returns its body without the catalog-only fields', async () => { + const file = join(entry, 'SKILL.md') + const provider = new FeishuSkillProvider(file) + expect(await provider.list()).toMatchObject([{ name: 'feishu', provider: 'feishu', source: 'bundled', locator: file, resourceBase: { kind: 'opaque' } }]) + const definition = await provider.get() + expect(definition).not.toHaveProperty('rank') + expect(definition).not.toHaveProperty('locator') + expect(definition.content).toBe(body().trim()) +}) + +it('refuses an entry without YAML frontmatter or without a skill name and description', async () => { + const dir = await mkdtemp(join(tmpdir(), 'dsh-feishu-entry-')) + try { + const file = join(dir, 'SKILL.md') + await writeFile(file, '# No frontmatter\n') + expect(() => new FeishuSkillProvider(file)).toThrow('has no YAML frontmatter') + await writeFile(file, '---\nname: Not A Skill\n---\n\nbody\n') + expect(() => new FeishuSkillProvider(file)).toThrow('needs a skill name and a description') + } finally { + await rm(dir, { recursive: true, force: true }) + } +}) diff --git a/packages/connector/feishu/tsconfig.json b/packages/connector/feishu/tsconfig.json new file mode 100644 index 0000000000..e907e5373d --- /dev/null +++ b/packages/connector/feishu/tsconfig.json @@ -0,0 +1,33 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../util/brand" + }, + { + "path": "../../util/values" + }, + { + "path": "../../skill/skill" + }, + { + "path": "../cli-account" + }, + { + "path": "../../client/ui-connector-account/tsconfig.host.json" + } + ] +} diff --git a/packages/connector/linear/README.i18n.yaml b/packages/connector/linear/README.i18n.yaml new file mode 100644 index 0000000000..65d30edd13 --- /dev/null +++ b/packages/connector/linear/README.i18n.yaml @@ -0,0 +1,73 @@ +# 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/connector/linear/README.md +/: + en: 939da448d3c75854 + zh: 18d990b86d0a14fe +/deepseek-ai-dsh-linear: + en: 4030a35e9e9eba0c + zh: e38262e0e0943994 +/deepseek-ai-dsh-linear/summary: + en: f25efa86e65d612e + zh: 34d941e6108776fc +/deepseek-ai-dsh-linear/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-linear/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-linear/use-this-package/install-into-a-profile: + en: 94724890eb42aed2 + zh: 49aef9822a7149c5 +/deepseek-ai-dsh-linear/use-this-package/authorize-and-sign-out: + en: 28da3a802b35be1d + zh: b925860d660b8e97 +/deepseek-ai-dsh-linear/use-this-package/turn-off-and-uninstall: + en: 408e2b369ddb5254 + zh: 2efc008fa32d09a9 +/deepseek-ai-dsh-linear/use-this-package/configure: + en: db9b1515054d7b0d + zh: 27bd7ddb4fd0ff24 +/deepseek-ai-dsh-linear/understand-the-implementation: + en: 9f8f1f804db227ad + zh: 495a69874f52bc81 +/deepseek-ai-dsh-linear/further-exploration: + en: ed7d1edadf2feef5 + zh: 6746823e51e4f4f3 +/deepseek-ai-dsh-linear/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-linear/model-experience/naming-and-connection-guidance: + en: 01b6ec6d681e457b + zh: 7fe0d1c9d1037bd4 +/deepseek-ai-dsh-linear/model-experience/naming-and-connection-guidance/what-the-model-sees: + en: 49e8c3a79ec569f7 + zh: 9db165a86fa1ade2 +/deepseek-ai-dsh-linear/model-experience/naming-and-connection-guidance/what-the-model-sees/guidance-text: + en: 8f57292f6821da96 + zh: b2d3bc7e5c9cbc05 +/deepseek-ai-dsh-linear/model-experience/naming-and-connection-guidance/token-effect: + en: 871fd5b39ce9299a + zh: f73294aa75132999 +/deepseek-ai-dsh-linear/model-experience/naming-and-connection-guidance/kv-cache-effect: + en: 9c7a599f4647412c + zh: 673c0dff65e62cd8 +/deepseek-ai-dsh-linear/model-experience/linear-server-tools-and-instructions: + en: b7d3a70c835efa15 + zh: cfea216bf67f9d43 +/deepseek-ai-dsh-linear/model-experience/linear-server-tools-and-instructions/what-the-model-sees: + en: 6258c3e0a743b59e + zh: 1aa9fabe7040246c +/deepseek-ai-dsh-linear/model-experience/linear-server-tools-and-instructions/token-effect: + en: 738480c7888daeaa + zh: c06ff095165990f6 +/deepseek-ai-dsh-linear/model-experience/linear-server-tools-and-instructions/kv-cache-effect: + en: e7ac075c511418ef + zh: 50ff737d29e63782 +/deepseek-ai-dsh-linear/known-limitations-and-deferred-work: + en: a743c3bd328a39cc + zh: d897eb426678f207 +/deepseek-ai-dsh-linear/known-limitations-and-deferred-work/dev-note: + en: 34edaa192d4de759 + zh: 276357d32049ebcf diff --git a/packages/connector/linear/README.md b/packages/connector/linear/README.md new file mode 100644 index 0000000000..cfdbcb916d --- /dev/null +++ b/packages/connector/linear/README.md @@ -0,0 +1,156 @@ +--- +description: "Connect Linear's hosted MCP server through the shared MCP manager, authorize it with OAuth, and use its tools in conversations." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-linear + +English | [中文](README.zh.md) + +## Summary + +The Linear plugin registers Linear's hosted MCP server, `https://mcp.linear.app/mcp`, with the Host's shared [MCP manager](../../mcp/mcp-manager/README.md) for as long as the plugin is loaded. The user connects a Linear account from the plugin's page on the Web sidebar's **Plugins** page; afterwards every conversation on that Host can use the server's tools, and the model is told to call the integration the Linear plugin. The manager owns the connection, OAuth authorization, the saved grant, and sign-out, which the shared [MCP account service](../../mcp/mcp-account/README.md) shows on the Plugins page. It runs in the Web and Desktop compositions. + +## 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 + +### Install into a profile + +Install the package as a bundle, for example from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-linear +``` + +The bundle patch inserts the `linear` row after the profile's other layers. The plugin requires the `mcpManager` and `systemPrompt` services: the [base bundle](../../bundle/base/README.md) provides `systemPrompt`, and the Web and Desktop compositions add the MCP manager through [`dsh-web-app`](../../bundle/web-app/README.md). In a profile without the MCP manager, such as `headless`, the plugin does not activate, and startup prints a warning that names the missing `mcpManager` service. + +### Authorize and sign out + +The plugin registers the server `linear` with the fixed OAuth credential key `mcp-client/linear`. Without a saved grant the server waits for authorization and exposes no Linear tools. With a saved grant the manager connects at startup and refreshes tokens as needed. Linear's tools load [on demand](../../mcp/mcp-client/README.md#on-demand-tool-loading) by default: the system prompt lists them, and each agent loads the ones it needs with `mcp__linear__load_tools`. + +While the plugin is on, its page on the **Plugins** page shows a **Linear account** section, and a tag beside the title reads Not connected, Connecting, Connected, Reconnect, or Unavailable. Switching the plugin on from the list while no account is connected offers **Connect Linear**, which opens the plugin's page and starts authorization. + +| Section state | Action | +|---|---| +| Not connected, or the grant expired, no longer matches the settings, was rejected, or lacks permissions | **Connect Linear** or **Connect again** starts an authorization attempt | +| Waiting for you to confirm in the browser | The browser that started the attempt opens Linear's authorization page once; **Open authorization page** opens it again, and **Cancel** ends the attempt | +| Connected | **Sign out** asks for confirmation, then deletes the local grant | +| Cannot connect right now | **Retry** restarts the server and keeps the existing grant | + +Authorization must be completed in a browser on the Host machine. After the user approves access in Linear, the callback page says DSH received the authorization; the section then shows the result. Leaving the page does not cancel an attempt, which the Host owns. A failed attempt shows **Authorization was not completed. Try again.**; a failed page action shows a toast. Sign-out keeps the client registration and does not revoke the connection on Linear's side. + +The page follows the account through the [`connectorAccounts` Remote](../../client/ui-connector-account/README.md) under the key `mcp:linear`, and its buttons start `connect`, `sign-out`, or `retry` or cancel the attempt there. On the Host, [`dsh-mcp-account`](../../mcp/mcp-account/README.md) runs them through the manager's [OAuth operations](../../mcp/mcp-manager/README.md#oauth-authorization): `startAuthorization('linear')` returns an attempt whose `authorizationUrl` the stream reports, `cancelAuthorization('linear', id)` cancels it, `signOut('linear')` deletes the grant, and `restart('linear')` retries. Other Remote clients can use the same operations. + +### Turn off and uninstall + +Turning the row off in Plugin Manager, or uninstalling the package, ends the registration: the Linear tools leave the model's tool set, and the saved grant stays in the credentials store, so reinstalling reuses it. To remove the grant, sign out while the plugin is loaded, or delete the `mcp-client/linear` record from `$DSH_HOME/.credentials.yaml` as the [local credentials provider](../../credentials/credentials-local/README.md) documents. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `url` | `https://mcp.linear.app/mcp` | Streamable HTTP MCP endpoint of the Linear server | +| `toolLoading` | `on-demand` | `on-demand` keeps Linear's tools hidden from each agent until it loads them; `eager` sends every tool definition with every request | + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-linear) is the exhaustive source of supported fields. Connection and authorization budgets use the manager and mcp-client defaults. The saved grant is bound to `url`; changing it requires connecting the account again. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts one row with id `linear` naming this package, so the package is both the bundle and its only row; `config` overrides target that id. The Host half, [`src/index.ts`](src/index.ts), makes two registrations, both effects of the plugin's fiber: `ctx.mcpManager.register('linear', …)` adds a Streamable HTTP entry with the configured `url` and OAuth credential key, and `ctx.systemPrompt.section()` adds the naming guidance at the `MCP_SERVERS` order. The server name fixes the `mcp__linear__` tool namespace, and the credential key fixes the grant address, so a reloaded or reinstalled plugin reaches the same tools and grant. The manager validates the entry when it is registered; a configured or registered server that already uses the name or key makes the plugin fail to load before the guidance is added. + +While the account registry runs, the plugin also calls `ctx.mcpAccounts.register({ server: 'linear', packageName: '@deepseek-ai/dsh-linear', copy })`, where [`src/locales.ts`](src/locales.ts) holds the text that names Linear in every shipped language; [`dsh-mcp-account`](../../mcp/mcp-account/README.md) then registers the account with the connector account registry, which renders the section, guidance, tag, and toast described above. A composition without the registry, such as a headless profile, loads the plugin without the account section. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [MCP manager](../../mcp/mcp-manager/README.md) — registration lifetime, status, OAuth authorization, and sign-out. +- [MCP client](../../mcp/mcp-client/README.md) — connection, tool naming, OAuth grant refresh, and redaction. +- [MCP subsystem](../../../docs/subsystems/mcp.md) — how the MCP packages fit together. +- [Plugin Manager](../../boot/plugin-manager/README.md) — installation and enablement. +- [MCP account service](../../mcp/mcp-account/README.md) — how the manager's status and authorization map to the account section. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the section, tag, guidance, and notices the account registration shows. +- [Plugins page](../../client/ui-plugin-manager/README.md#use-this-package) — the bundle page those surfaces occupy. + +----- + + +## Model Experience + +### Naming and connection guidance + +#### What the model sees + +While the plugin is loaded, the system prompt contains the text below before the MCP server sections, whether or not Linear is authorized. + +##### Guidance text + +```markdown +Tools named `mcp__linear__*` come from the Linear plugin. In user-facing replies, call it the Linear plugin (Linear 插件 in Chinese), not MCP. If no `mcp__linear__*` tool appears in your tool list, Linear is not connected yet; ask the user to connect it on the Linear plugin page in Plugins. +``` + +#### Token effect + +The three fixed sentences add about 70 tokens to every request while the plugin is loaded. + +#### KV Cache effect + +The guidance is prefix-stable: it changes only when the plugin loads or unloads, not when authorization or the connection changes. + +### Linear server tools and instructions + +#### What the model sees + +After authorization, the model sees Linear's server instructions under `### MCP server: linear` and, with the default `toolLoading: on-demand`, the loader `mcp__linear__load_tools` and a [catalog of Linear's tools](../../mcp/mcp-client/README.md#model-experience) in the system prompt; each tool it loads then appears as `mcp__linear__` with Linear's description and input schema. With `eager`, every tool appears from the start, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. With `on-demand`, the loader and the catalog appear only once Linear is connected. While the plugin is loaded, including before authorization, the [shared resource tools](../../mcp/mcp-resources/README.md#model-experience) and their server-name prompt list `linear`. + +#### Token effect + +Linear's server defines the tool set and instructions, and their size can change without a DSH update. With `on-demand`, a connected Linear costs its instructions, the loader, and a catalog of about 9,600 characters for its 70 tools, plus the definitions an agent has loaded; with `eager`, all definitions, about 97,900 characters, repeat on every request. + +#### KV Cache effect + +Linear's instructions (or, with `eager`, its tools) appear when the connection succeeds and disappear when authorization is withdrawn or the plugin unloads; each change can invalidate reuse from the first changed token. With `on-demand`, the catalog changes only when Linear's tool list does, and each load changes the agent's next tool list, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. The shared resource tools stay unchanged across connection changes. + +## Known Limitations and Deferred Work + + + +- The Linear account section exists only while the plugin is on. To sign out after turning the plugin off, turn it on again or delete the grant record. +- Only the Web and Desktop compositions mount the MCP manager; other profiles leave the plugin inactive. +- The authorization callback is `http://127.0.0.1:` on the Host, so the browser that completes authorization must run on the Host machine. A Web Host reached from another machine cannot finish authorization. +- Desktop listens on an OS-assigned port for each launch. Authorizing again after a restart registers a new OAuth client and keeps the earlier registration record; saved grants refresh normally across restarts. +- Before the account is connected, the shared resource prompt still lists `linear` as a server name, and resource calls to it fail until the user connects. +- One Linear authorization covers one Linear workspace and serves the whole Host; there is no account or workspace picker. +- A paid Linear workspace can require admin approval for third-party applications ([Linear documentation](https://linear.app/docs/third-party-application-approvals)). There, Linear asks the user to request approval instead of granting access, and the user connects again after an admin approves. +- Turning the plugin off or uninstalling it keeps the local grant. Signing out deletes the local grant but leaves the connection authorized on Linear's side until the user removes it there. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs run the plugin against the MCP manager and the mcp-client loopback OAuth server fixture; another checks that the account registry serves the Linear account with its text and withdraws it with the plugin. The `linear-plugin` session snapshot replays the Linear row without a saved grant, so it pins the naming guidance and verifies that no request reaches the server. + +
diff --git a/packages/connector/linear/README.zh.md b/packages/connector/linear/README.zh.md new file mode 100644 index 0000000000..612ec55726 --- /dev/null +++ b/packages/connector/linear/README.zh.md @@ -0,0 +1,156 @@ +--- +description: "通过共用的 MCP 管理器接入 Linear 托管的 MCP 服务器,经 OAuth 授权后在对话中使用其工具。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-linear + +[English](README.md) | 中文 + +## 概述 + +Linear 插件在加载期间把 Linear 托管的 MCP 服务器 `https://mcp.linear.app/mcp` 注册到 Host 共用的 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)。用户在 Web 侧栏**插件**页面的插件详情页中连接 Linear 账号,之后该 Host 上的所有对话都能使用这个服务器的工具,模型也会被告知把这项集成称为 Linear 插件。连接、OAuth 授权、已保存的 grant 和退出登录都由管理器负责,并由共用的 [MCP 账号服务](../../mcp/mcp-account/README.zh.md)显示在插件页面上。插件运行在 Web 与 Desktop 组合中。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +将本包作为 bundle 安装,例如在 Web 侧栏的**插件**页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-linear +``` + +bundle patch 在 profile 其他层之后插入 `linear` 行。插件需要 `mcpManager` 与 `systemPrompt` 服务:[base bundle](../../bundle/base/README.zh.md) 提供 `systemPrompt`,Web 与 Desktop 组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 补上 MCP 管理器。在没有 MCP 管理器的 profile(例如 `headless`)中,插件不会激活,启动时会打印一条警告,指出缺少 `mcpManager` 服务。 + +### 授权与退出登录 + +插件以固定的 OAuth 凭据 key `mcp-client/linear` 注册服务器 `linear`。没有已保存的 grant 时,服务器等待授权,不提供 Linear 工具。有已保存的 grant 时,管理器在启动时连接,并按需刷新 token。Linear 的工具默认[按需加载](../../mcp/mcp-client/README.zh.md#on-demand-tool-loading):系统提示词列出这些工具,每个 agent 用 `mcp__linear__load_tools` 加载需要的工具。 + +插件开启期间,它在**插件**页面的详情页显示 **Linear 账号**区块,标题旁的标签显示未连接、连接中、已连接、需要重新连接或暂时无法连接。在列表中开启插件而尚未连接账号时,页面提示**连接 Linear**,点击后打开插件详情页并发起授权。 + +| 区块状态 | 操作 | +|---|---| +| 未连接,或授权已过期、与当前设置不再匹配、被拒绝、缺少权限 | **连接 Linear** 或**重新连接**发起一次授权尝试 | +| 等待你在浏览器中确认 | 发起尝试的浏览器打开一次 Linear 授权页面;**打开授权页面**再次打开,**取消**结束这次尝试 | +| 已连接 | **退出登录**确认后删除本地 grant | +| 暂时无法连接 | **重试**重启服务器并保留现有授权 | + +授权必须在 Host 所在机器的浏览器中完成。用户在 Linear 中同意授权后,回调页面说明 DSH 已收到授权,区块随后显示结果。离开页面不会取消授权尝试,尝试由 Host 持有。授权失败时显示**授权未完成,请重试**;页面操作失败时显示 toast。退出登录保留客户端注册,不会在 Linear 一侧撤销连接。 + +页面通过 [`connectorAccounts` Remote](../../client/ui-connector-account/README.zh.md) 以 key `mcp:linear` 跟随账号,其按钮在该 Remote 上发起 `connect`、`sign-out` 或 `retry`,或取消授权尝试。在 Host 上,[`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 通过管理器的 [OAuth 操作](../../mcp/mcp-manager/README.zh.md#oauth-authorization)执行它们:`startAuthorization('linear')` 返回一次授权尝试,其 `authorizationUrl` 由流报告,`cancelAuthorization('linear', id)` 取消它,`signOut('linear')` 删除 grant,`restart('linear')` 重试。其他 Remote 客户端可以使用同样的操作。 + +### 停用与卸载 + +在 Plugin Manager 中关闭该行或卸载本包都会结束注册:Linear 工具从模型的工具集中撤下,已保存的 grant 留在凭据存储中,因此重新安装会复用它。要删除 grant,请在插件加载期间退出登录,或按[本地凭据提供方](../../credentials/credentials-local/README.zh.md)的说明,从 `$DSH_HOME/.credentials.yaml` 中删除 `mcp-client/linear` 记录。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `url` | `https://mcp.linear.app/mcp` | Linear 服务器的 Streamable HTTP MCP 端点 | +| `toolLoading` | `on-demand` | `on-demand` 让 Linear 的工具在 agent 加载前对其隐藏;`eager` 在每次请求中发送全部工具定义 | + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-linear)是受支持字段的完整来源。连接与授权的预算使用管理器和 mcp-client 的默认值。已保存的 grant 与 `url` 绑定,修改后需要重新连接账号。 + +----- + + +## 理解实现 + +
+实现内部机制——点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 插入一行 id 为 `linear` 的条目,指向本包,因此本包既是 bundle,也是其唯一的一行;`config` 覆盖以该 id 为目标。Host 侧的 [`src/index.ts`](src/index.ts) 进行两项注册,二者都是插件 fiber 的 effect:`ctx.mcpManager.register('linear', …)` 以配置的 `url` 和 OAuth 凭据 key 添加一个 Streamable HTTP 条目,`ctx.systemPrompt.section()` 在 `MCP_SERVERS` 排序位置添加称呼指引。服务器名固定了 `mcp__linear__` 工具命名空间,凭据 key 固定了 grant 地址,因此重新加载或重新安装的插件会得到同样的工具和 grant。管理器在注册时校验条目;如果已配置或已注册的服务器占用了该名称或 key,插件会在添加指引之前加载失败。 + +账号注册表运行时,插件还调用 `ctx.mcpAccounts.register({ server: 'linear', packageName: '@deepseek-ai/dsh-linear', copy })`,其中 [`src/locales.ts`](src/locales.ts) 以每种已发布语言保存指明 Linear 的文案;随后由 [`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 把账号登记到连接器账号注册表,由注册表渲染上文所述的区块、引导、标签与 toast。没有注册表的组合(如 headless profile)加载插件时不带账号区块。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md)——这个应用插件所属的分组。 +- [MCP 管理器](../../mcp/mcp-manager/README.zh.md)——注册生命周期、状态、OAuth 授权与退出登录。 +- [MCP 客户端](../../mcp/mcp-client/README.zh.md)——连接、工具命名、OAuth grant 刷新与脱敏。 +- [MCP 子系统](../../../docs/subsystems/mcp.zh.md)——各 MCP 包如何协同。 +- [Plugin Manager](../../boot/plugin-manager/README.zh.md)——安装与启用。 +- [MCP 账号服务](../../mcp/mcp-account/README.zh.md)——管理器的状态与授权如何映射到账号区块。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md)——账号注册后显示的区块、标签、引导与提示。 +- [插件页面](../../client/ui-plugin-manager/README.zh.md#use-this-package)——这些界面所在的 bundle 详情页。 + +----- + + +## 模型体验 + +### 称呼与连接指引 + +#### 模型看到什么 + +插件加载期间,无论 Linear 是否已授权,系统提示词都会在 MCP 服务器各节之前包含下面这段文字。 + +##### 指引文本 + +```markdown +Tools named `mcp__linear__*` come from the Linear plugin. In user-facing replies, call it the Linear plugin (Linear 插件 in Chinese), not MCP. If no `mcp__linear__*` tool appears in your tool list, Linear is not connected yet; ask the user to connect it on the Linear plugin page in Plugins. +``` + +#### Token 影响 + +插件加载期间,这三句固定文字为每次请求增加约 70 个 token。 + +#### KV Cache 影响 + +这段指引保持前缀稳定:只在插件加载或卸载时变化,授权或连接状态变化不会改变它。 + +### Linear 服务器工具与说明 + +#### 模型看到什么 + +授权之后,模型会在 `### MCP server: linear` 之下看到 Linear 的服务器说明;在默认的 `toolLoading: on-demand` 下,还会看到加载器 `mcp__linear__load_tools`,以及系统提示词中的 [Linear 工具目录](../../mcp/mcp-client/README.zh.md#model-experience),加载的每个工具随后以 `mcp__linear__` 命名,带有 Linear 提供的描述和输入 schema。设为 `eager` 时,所有工具从一开始就出现,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。设为 `on-demand` 时,加载器和目录只在 Linear 连接后出现。插件加载期间(包括授权之前),[共用的资源工具](../../mcp/mcp-resources/README.zh.md#model-experience)及其服务器名提示词都会列出 `linear`。 + +#### Token 影响 + +工具集与服务器说明由 Linear 服务器定义,其大小可能在 DSH 不更新的情况下变化。设为 `on-demand` 时,已连接的 Linear 的开销是服务器说明、加载工具、70 个工具约 9,600 字符的目录,以及 agent 已加载的定义;设为 `eager` 时,全部定义(约 97,900 字符)在每次请求中重复出现。 + +#### KV Cache 影响 + +Linear 的服务器说明(设为 `eager` 时则是其工具)在连接成功时出现,在授权被撤回或插件卸载时消失;每次变化都可能使从第一个变化 token 起的复用失效。设为 `on-demand` 时,目录只在 Linear 的工具列表变化时变化,每次加载都会改变该 agent 下一次请求的工具列表,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。共用的资源工具在连接变化前后保持不变。 + +## 已知限制与延期工作 + + + +- Linear 账号区块只在插件开启时存在。关闭插件后如需退出登录,请先重新开启插件,或删除 grant 记录。 +- 只有 Web 与 Desktop 组合挂载 MCP 管理器;在其他 profile 中插件保持未激活。 +- 授权回调地址是 Host 上的 `http://127.0.0.1:`,因此完成授权的浏览器必须运行在 Host 所在机器上。从另一台机器访问的 Web Host 无法完成授权。 +- Desktop 每次启动都监听操作系统分配的端口。重启后再次授权会注册一个新的 OAuth 客户端,并保留之前的注册记录;已保存的 grant 在重启前后正常刷新。 +- 账号连接之前,共享资源的提示词仍把 `linear` 列为服务器名,对它的资源调用会失败,直到用户完成连接。 +- 一次 Linear 授权对应一个 Linear 工作区,供整个 Host 使用;没有账号或工作区选择器。 +- 付费 Linear 工作区可以要求管理员审批第三方应用([Linear 文档](https://linear.app/docs/third-party-application-approvals))。这时 Linear 让用户提交审批申请而不是直接授权,管理员批准后用户需要重新连接。 +- 停用或卸载插件会保留本地 grant。退出登录会删除本地 grant,但在用户于 Linear 一侧移除之前,该连接在 Linear 中仍处于已授权状态。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 侧单测让插件运行在 MCP 管理器和 mcp-client 的回环 OAuth 服务器夹具之上;另一项单测检查账号注册表提供带文案的 Linear 账号,并随插件一起撤下。`linear-plugin` 会话快照在没有已保存 grant 的情况下回放 Linear 行,因此它固定称呼指引,并验证没有请求到达服务器。 + +
diff --git a/packages/connector/linear/cordis.patch.yml b/packages/connector/linear/cordis.patch.yml new file mode 100644 index 0000000000..534a24adb8 --- /dev/null +++ b/packages/connector/linear/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: linear + name: '@deepseek-ai/dsh-linear' diff --git a/packages/connector/linear/docs/DETAIL.md b/packages/connector/linear/docs/DETAIL.md new file mode 100644 index 0000000000..c56055002b --- /dev/null +++ b/packages/connector/linear/docs/DETAIL.md @@ -0,0 +1 @@ +![The connected Linear account on the plugin page and a conversation that lists Linear issues](preview.svg) diff --git a/packages/connector/linear/docs/DETAIL.zh.md b/packages/connector/linear/docs/DETAIL.zh.md new file mode 100644 index 0000000000..fac6392e7e --- /dev/null +++ b/packages/connector/linear/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已连接的 Linear 账号,以及在对话中列出 Linear 议题](preview.zh.svg) diff --git a/packages/connector/linear/docs/preview.svg b/packages/connector/linear/docs/preview.svg new file mode 100644 index 0000000000..48cc57f7de --- /dev/null +++ b/packages/connector/linear/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/linear/docs/preview.zh.svg b/packages/connector/linear/docs/preview.zh.svg new file mode 100644 index 0000000000..a9a7d69a40 --- /dev/null +++ b/packages/connector/linear/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/linear/icon.svg b/packages/connector/linear/icon.svg new file mode 100644 index 0000000000..f8b0428eee --- /dev/null +++ b/packages/connector/linear/icon.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/linear/locale/de.json b/packages/connector/linear/locale/de.json new file mode 100644 index 0000000000..46eebf8d8c --- /dev/null +++ b/packages/connector/linear/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Linear-Plugin", + "description": "Verwenden Sie Issues, Projekte und Kommentare von Linear in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/en.json b/packages/connector/linear/locale/en.json new file mode 100644 index 0000000000..26f7ab9de2 --- /dev/null +++ b/packages/connector/linear/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Linear plugin", + "description": "Use Linear issues, projects, and comments in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/es.json b/packages/connector/linear/locale/es.json new file mode 100644 index 0000000000..d6203314c1 --- /dev/null +++ b/packages/connector/linear/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de Linear", + "description": "Use incidencias, proyectos y comentarios de Linear en las conversaciones.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/fr.json b/packages/connector/linear/locale/fr.json new file mode 100644 index 0000000000..356e77f777 --- /dev/null +++ b/packages/connector/linear/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin Linear", + "description": "Utilisez les tickets, les projets et les commentaires de Linear dans les conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/ja.json b/packages/connector/linear/locale/ja.json new file mode 100644 index 0000000000..29a82b983c --- /dev/null +++ b/packages/connector/linear/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Linear プラグイン", + "description": "会話の中で Linear の Issue、プロジェクト、コメントを使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/pt.json b/packages/connector/linear/locale/pt.json new file mode 100644 index 0000000000..0b4575da3f --- /dev/null +++ b/packages/connector/linear/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do Linear", + "description": "Use issues, projetos e comentários do Linear nas conversas.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/ru.json b/packages/connector/linear/locale/ru.json new file mode 100644 index 0000000000..e1d0c7b367 --- /dev/null +++ b/packages/connector/linear/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин Linear", + "description": "Используйте задачи, проекты и комментарии Linear в беседах.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/linear/locale/zh.json b/packages/connector/linear/locale/zh.json new file mode 100644 index 0000000000..dd01d628c7 --- /dev/null +++ b/packages/connector/linear/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Linear 插件", + "description": "在对话中使用 Linear 的议题、项目与评论。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/linear/package.json b/packages/connector/linear/package.json new file mode 100644 index 0000000000..3c38a3ceb8 --- /dev/null +++ b/packages/connector/linear/package.json @@ -0,0 +1,67 @@ +{ + "name": "@deepseek-ai/dsh-linear", + "description": "Linear plugin: Linear's hosted MCP server, authorized through the shared MCP manager", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/linear" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-mcp-account": "workspace:*", + "@deepseek-ai/dsh-mcp-manager": "workspace:*", + "@deepseek-ai/dsh-mcp-resources": "workspace:*", + "@deepseek-ai/dsh-scope": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*" + } +} diff --git a/packages/connector/linear/src/index.ts b/packages/connector/linear/src/index.ts new file mode 100644 index 0000000000..20d580033d --- /dev/null +++ b/packages/connector/linear/src/index.ts @@ -0,0 +1,67 @@ +/** + * Linear plugin: registers Linear's hosted MCP server with the shared MCP + * manager for this plugin's lifetime, tells the model to call it the Linear + * plugin, and shows the account on the Plugins page while the account registry + * runs. The manager owns connection, OAuth authorization, saved grants, and + * sign-out; once a grant exists, the server's `mcp__linear__*` tools are + * listed in the system prompt and each agent loads the ones it needs. + * @module @deepseek-ai/dsh-linear + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-mcp-account' +import type {} from '@deepseek-ai/dsh-mcp-manager' +import type {} from '@deepseek-ai/dsh-system-prompt' +import { COPY } from './locales.ts' + +export const name = 'linear' +export const inject = ['mcpManager', 'systemPrompt'] + +// One shared account per Host: a fixed server name keeps tool names stable and +// a fixed credential key lets a reinstalled plugin reuse its saved grant. +const SERVER_NAME = 'linear' +const CREDENTIAL_KEY = 'mcp-client/linear' +const GUIDANCE = 'Tools named `mcp__linear__*` come from the Linear plugin. In user-facing replies, call it the Linear plugin (Linear 插件 in Chinese), not MCP.' + + ' If no `mcp__linear__*` tool appears in your tool list, Linear is not connected yet; ask the user to connect it on the Linear plugin page in Plugins.' + +/** Linear MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Linear's hosted server. */ + url: string + /** `on-demand` (default) keeps Linear's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} + +/* jscpd:ignore-start -- deliberate twin of dsh-notion and dsh-tencent-docs: the same MCP server and guidance registrations. */ +/** Runtime configuration schema for the Linear plugin. */ +export const Config: z, Config> = z.object({ + url: z.string().default('https://mcp.linear.app/mcp'), + toolLoading: z.union(['eager', 'on-demand']).default('on-demand'), +}) + +/** + * Register the Linear server, its naming guidance, and, while the account registry runs, its Plugins page account; all + * are withdrawn when the plugin unloads. + * @param ctx - Context carrying the MCP manager and system prompt. + * @param config - Linear endpoint and tool loading. + * @throws when another configured or registered server already uses the `linear` name or credential key. + */ +export function apply(ctx: Context, config: Config): void { + ctx.mcpManager.register(SERVER_NAME, { + transport: 'streamable-http', + url: config.url, + oauth: { credentialKey: CREDENTIAL_KEY }, + toolLoading: config.toolLoading, + }) + // Sections at one order sort by name, so `linear` precedes every `mcp…` server section. + ctx.systemPrompt.section({ + name: SERVER_NAME, + order: ctx.systemPrompt.getSectionOrder('MCP_SERVERS'), + text: GUIDANCE, + }) + ctx.inject(['mcpAccounts'], (scope) => { + scope.effect(() => scope.mcpAccounts.register({ server: SERVER_NAME, packageName: '@deepseek-ai/dsh-linear', copy: COPY }), 'linear: Plugins page account') + }) +} +/* jscpd:ignore-end */ diff --git a/packages/connector/linear/src/locales.ts b/packages/connector/linear/src/locales.ts new file mode 100644 index 0000000000..bfbc29c35a --- /dev/null +++ b/packages/connector/linear/src/locales.ts @@ -0,0 +1,167 @@ +/** The Plugins page text that names Linear; the shared account copy comes from the account surfaces' dictionary. */ +import type { McpAccountCopy } from '@deepseek-ai/dsh-mcp-account' + +/** Every language the Web app ships. */ +type ShippedText = Readonly> + +/** Linear's account text in every shipped language. */ +export const COPY: McpAccountCopy = { + title: { + zh: 'Linear 账号', + en: 'Linear account', + ja: 'Linear アカウント', + es: 'Cuenta de Linear', + fr: 'Compte Linear', + de: 'Linear-Konto', + ru: 'Аккаунт Linear', + pt: 'Conta do Linear', + }, + connect: { + zh: '连接 Linear', + en: 'Connect Linear', + ja: 'Linear を接続', + es: 'Conectar Linear', + fr: 'Connecter Linear', + de: 'Linear verbinden', + ru: 'Подключить Linear', + pt: 'Conectar Linear', + }, + activation: { + title: { + zh: '连接 Linear 账号', + en: 'Connect your Linear account', + ja: 'Linear アカウントを接続', + es: 'Conecte su cuenta de Linear', + fr: 'Connectez votre compte Linear', + de: 'Linear-Konto verbinden', + ru: 'Подключите аккаунт Linear', + pt: 'Conecte sua conta do Linear', + }, + body: { + zh: 'Linear 插件已开启。连接你的 Linear 账号后,就可以在对话中使用它。', + en: 'The Linear plugin is on. Connect your Linear account to use it in conversations.', + ja: 'Linear プラグインがオンになりました。Linear アカウントを接続すると、会話の中で使用できます。', + es: 'El complemento de Linear está activado. Conecte su cuenta de Linear para usarlo en las conversaciones.', + fr: 'Le plugin Linear est activé. Connectez votre compte Linear pour l’utiliser dans les conversations.', + de: 'Das Linear-Plugin ist aktiviert. Verbinden Sie Ihr Linear-Konto, um es in Unterhaltungen zu verwenden.', + ru: 'Плагин Linear включён. Подключите аккаунт Linear, чтобы использовать его в беседах.', + pt: 'O plugin do Linear está ativado. Conecte sua conta do Linear para usá-lo nas conversas.', + }, + }, + detail: { + disconnected: { + zh: '连接 Linear 账号后,可以在对话中查找、创建和更新议题、项目与评论。', + en: 'Connect your Linear account to find, create, and update issues, projects, and comments right from a conversation.', + ja: 'Linear アカウントを接続すると、会話の中から直接 Issue、プロジェクト、コメントを検索、作成、更新できます。', + es: 'Conecte su cuenta de Linear para buscar, crear y actualizar incidencias, proyectos y comentarios directamente desde una conversación.', + fr: 'Connectez votre compte Linear pour rechercher, créer et mettre à jour des tickets, des projets et des commentaires, directement depuis une conversation.', + de: 'Verbinden Sie Ihr Linear-Konto, um Issues, Projekte und Kommentare direkt aus einer Unterhaltung heraus zu suchen, zu erstellen und zu aktualisieren.', + ru: 'Подключите аккаунт Linear, чтобы искать, создавать и обновлять задачи, проекты и комментарии прямо из беседы.', + pt: 'Conecte sua conta do Linear para pesquisar, criar e atualizar issues, projetos e comentários, direto de uma conversa.', + }, + waitingBrowser: { + zh: '已打开 Linear 授权页面。在 Linear 中确认后,回到这里查看结果。', + en: 'The Linear authorization page is open. Confirm in Linear, then come back here to see the result.', + ja: 'Linear の認可ページを開きました。Linear で確定したら、ここに戻って結果を確認してください。', + es: 'La página de autorización de Linear está abierta. Confirme en Linear y luego vuelva aquí para ver el resultado.', + fr: 'La page d’autorisation Linear est ouverte. Confirmez dans Linear, puis revenez ici pour voir le résultat.', + de: 'Die Linear-Autorisierungsseite ist geöffnet. Bestätigen Sie in Linear und kehren Sie dann hierher zurück, um das Ergebnis zu sehen.', + ru: 'Страница авторизации Linear открыта. Подтвердите в Linear, затем вернитесь сюда, чтобы увидеть результат.', + pt: 'A página de autorização do Linear está aberta. Confirme no Linear e depois volte aqui para ver o resultado.', + }, + authorizing: { + zh: '正在与 Linear 完成授权。', + en: 'Finishing authorization with Linear.', + ja: 'Linear での認可を完了しています。', + es: 'Completando la autorización con Linear.', + fr: 'Finalisation de l’autorisation avec Linear.', + de: 'Die Autorisierung mit Linear wird abgeschlossen.', + ru: 'Завершение авторизации в Linear.', + pt: 'Concluindo a autorização com o Linear.', + }, + connecting: { + zh: '正在连接 Linear。', + en: 'Connecting to Linear.', + ja: 'Linear に接続しています。', + es: 'Conectando con Linear.', + fr: 'Connexion à Linear en cours.', + de: 'Verbindung mit Linear wird hergestellt.', + ru: 'Подключение к Linear.', + pt: 'Conectando ao Linear.', + }, + connected: { + zh: '可以在对话中直接请 Agent 使用 Linear。', + en: 'Ask the agent to use Linear directly in a conversation.', + ja: '会話の中でエージェントに Linear の使用を直接依頼できます。', + es: 'Pida al agente que use Linear directamente en una conversación.', + fr: 'Demandez à l’agent d’utiliser Linear directement dans une conversation.', + de: 'Bitten Sie den Agenten, Linear direkt in einer Unterhaltung zu verwenden.', + ru: 'Попросите агента использовать Linear прямо в беседе.', + pt: 'Peça ao agente que use o Linear diretamente em uma conversa.', + }, + rejected: { + zh: 'Linear 不再接受当前授权,请重新连接。', + en: 'Linear no longer accepts the current authorization. Connect again.', + ja: 'Linear は現在の認可を受け付けなくなりました。再度接続してください。', + es: 'Linear ya no acepta la autorización actual. Vuelva a conectar.', + fr: 'Linear n’accepte plus l’autorisation actuelle. Reconnectez-vous.', + de: 'Linear akzeptiert die aktuelle Autorisierung nicht mehr. Verbinden Sie erneut.', + ru: 'Linear больше не принимает текущую авторизацию. Подключитесь снова.', + pt: 'O Linear não aceita mais a autorização atual. Conecte novamente.', + }, + scope: { + zh: '当前授权缺少所需权限。重新连接时,请在 Linear 中确认权限。', + en: 'The current authorization lacks required permissions. Confirm them in Linear when you connect again.', + ja: '現在の認可には必要な権限が不足しています。再度接続するときに、Linear で権限を確認してください。', + es: 'A la autorización actual le faltan permisos necesarios. Confírmelos en Linear cuando vuelva a conectar.', + fr: 'L’autorisation actuelle ne dispose pas des permissions requises. Confirmez-les dans Linear lors de la reconnexion.', + de: 'Der aktuellen Autorisierung fehlen erforderliche Berechtigungen. Bestätigen Sie diese in Linear, wenn Sie erneut verbinden.', + ru: 'Текущей авторизации не хватает нужных разрешений. Подтвердите их в Linear при повторном подключении.', + pt: 'A autorização atual não tem as permissões necessárias. Confirme-as no Linear ao conectar novamente.', + }, + }, + signOut: { + title: { + zh: '退出 Linear 登录?', + en: 'Sign out of Linear?', + ja: 'Linear からサインアウトしますか?', + es: '¿Cerrar sesión en Linear?', + fr: 'Se déconnecter de Linear ?', + de: 'Von Linear abmelden?', + ru: 'Выйти из Linear?', + pt: 'Sair do Linear?', + }, + body: { + zh: '将删除 DSH 保存的 Linear 授权,之后对话中无法使用 Linear。如需在 Linear 一侧撤销连接,请到 Linear 的设置中处理。', + en: 'This deletes the Linear authorization DSH saved, so conversations can no longer use Linear. To revoke the connection on Linear\'s side, use Linear\'s settings.', + ja: 'DSH が保存した Linear の認可を削除します。以後、会話の中で Linear は使用できなくなります。Linear 側で接続を取り消すには、Linear の設定から行ってください。', + es: 'Se eliminará la autorización de Linear que guardó DSH, por lo que las conversaciones ya no podrán usar Linear. Para revocar la conexión del lado de Linear, use la configuración de Linear.', + fr: 'Cela supprime l’autorisation Linear enregistrée par DSH : les conversations ne pourront plus utiliser Linear. Pour révoquer la connexion côté Linear, utilisez les paramètres de Linear.', + de: 'Dadurch wird die von DSH gespeicherte Linear-Autorisierung gelöscht, sodass Unterhaltungen Linear nicht mehr verwenden können. Um die Verbindung auf Linear-Seite zu widerrufen, verwenden Sie die Einstellungen von Linear.', + ru: 'Сохранённая DSH авторизация Linear будет удалена, и беседы больше не смогут использовать Linear. Чтобы отозвать подключение на стороне Linear, воспользуйтесь настройками Linear.', + pt: 'Isso exclui a autorização do Linear salva pelo DSH, e as conversas não poderão mais usar o Linear. Para revogar a conexão no lado do Linear, use as configurações do Linear.', + }, + }, + notice: { + connected: { + zh: 'Linear 已连接', + en: 'Linear connected', + ja: 'Linear を接続しました', + es: 'Linear conectado', + fr: 'Linear connecté', + de: 'Linear verbunden', + ru: 'Linear подключён', + pt: 'Linear conectado', + }, + signedOut: { + zh: '已退出 Linear 登录', + en: 'Signed out of Linear', + ja: 'Linear からサインアウトしました', + es: 'Sesión de Linear cerrada', + fr: 'Déconnecté de Linear', + de: 'Von Linear abgemeldet', + ru: 'Выполнен выход из Linear', + pt: 'Você saiu do Linear', + }, + }, +} diff --git a/packages/connector/linear/tests/plugin.spec.ts b/packages/connector/linear/tests/plugin.spec.ts new file mode 100644 index 0000000000..ba0a3063b5 --- /dev/null +++ b/packages/connector/linear/tests/plugin.spec.ts @@ -0,0 +1,145 @@ +/** Linear plugin over a real MCP manager profile and a loopback OAuth MCP server. */ + +import { expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import ConnectorAccounts from '@deepseek-ai/dsh-client-ui-connector-account' +import type { ConnectorAccountsView } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import McpAccounts from '@deepseek-ai/dsh-mcp-account' +import { parseCredentialKey } from '@deepseek-ai/dsh-credentials' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import type { McpManagedServerStatus } from '@deepseek-ai/dsh-mcp-manager' +import McpResources from '@deepseek-ai/dsh-mcp-resources' +import { createScope } from '@deepseek-ai/dsh-scope' +import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import { callback, oauthWorld, phase } from '../../../mcp/mcp-client/tests/oauth-fixture.ts' +import { managerProfile } from '../../../mcp/mcp-manager/tests/profile-fixture.ts' +import { COPY } from '../src/locales.ts' +import * as Linear from '../src/index.ts' + +// Verbatim pin of the model-visible guidance in src/index.ts. +const GUIDANCE = 'Tools named `mcp__linear__*` come from the Linear plugin. In user-facing replies, call it the Linear plugin (Linear 插件 in Chinese), not MCP.' + + ' If no `mcp__linear__*` tool appears in your tool list, Linear is not connected yet; ask the user to connect it on the Linear plugin page in Plugins.' + +async function fixture(servers: Record = {}) { + const world = await oauthWorld() + await world.ctx.plugin(McpResources) + await managerProfile(world.ctx, { base: { servers } }) + const view = () => world.ctx.mcpManager.list().find(entry => entry.name === 'linear') + const state = async (expected: McpManagedServerStatus['state']) => { + await vi.waitFor(() => { expect(view()?.status.state).toBe(expected) }, { timeout: 5000 }) + } + const mount = (config: Partial = {}) => world.ctx.plugin(Linear, { url: world.origin + '/mcp', ...config }) + const prompt = async () => renderPrompt(await world.ctx.systemPrompt.assemble()) + const ping = () => executeToolFixture(world.ctx, { + callId: ToolCallId('linear-ping'), name: 'mcp__linear__ping', arguments: {}, signal: new AbortController().signal, + }) + const grant = async () => (await world.ctx.credentials.describeRecord(parseCredentialKey('mcp-client/linear'))).configured + const agent = async (): Promise => { + const holder: { ctx?: Context } = {} + const created = holder as Agent + await world.ctx.plugin({ inject: ['tools'], apply(inner: Context) { holder.ctx = createScope(inner, created).ctx } }) + await world.ctx.serial('agent/created', { agent: created, source: 'startup' }) + return created + } + const authorize = async () => { + await world.ctx.mcpManager.startAuthorization('linear') + expect(await callback(await phase(() => view()?.authorization, 'waiting-browser'))).toBe(200) + await state('connected') + } + return { ...world, view, state, mount, prompt, ping, grant, agent, authorize } +} + +it('defaults to the hosted Linear endpoint', () => { + expect(Linear.Config({})).toEqual({ url: 'https://mcp.linear.app/mcp', toolLoading: 'on-demand' }) +}) + +it('registers Linear for the plugin lifetime and reuses the saved grant after reloading', async () => { + const b = await fixture() + // Eager tools register for the Host, so the test calls them without an agent. + const first = b.mount({ toolLoading: 'eager' }) + await first.await() + await b.state('waiting-authorization') + expect(b.view()?.status).toMatchObject({ reason: 'missing' }) + expect(await b.prompt()).toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + + await b.authorize() + expect(await b.ping()).toMatchObject({ isError: false }) + + await first.dispose() + expect(b.view()).toBeUndefined() + expect(await b.prompt()).not.toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + expect(await b.grant()).toBe(true) + + const tokens = b.tokens() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(await b.ping()).toMatchObject({ isError: false }) + expect(b.view()?.authorization).toBeUndefined() + expect(b.tokens()).toBe(tokens) + expect(b.registrations()).toBe(1) +}) + +it('keeps Linear tools hidden from an agent until it loads them, unless loading is eager', async () => { + const b = await fixture() + const agent = await b.agent() + const onDemand = b.mount() + await onDemand.await() + await b.authorize() + expect(b.ctx.tools.get('mcp__linear__ping', agent)).toBeUndefined() + expect(b.ctx.tools.get('mcp__linear__load_tools', agent)).toBeDefined() + expect(await executeToolFixture(b.ctx, { + callId: ToolCallId('linear-load'), name: 'mcp__linear__load_tools', arguments: { tools: ['ping'] }, + signal: new AbortController().signal, agent, + })).toMatchObject({ isError: false, value: 'Loaded: mcp__linear__ping.' }) + expect(b.ctx.tools.get('mcp__linear__ping', agent)).toBeDefined() + + await onDemand.dispose() + const other = await b.agent() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(b.ctx.tools.get('mcp__linear__ping', other)).toBeDefined() +}) + +/** Read the account stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('account stream ended') + if (predicate(next.value)) return next.value + } +} + +it('shows the Linear account on the Plugins page while the account registry runs, and withdraws it with the plugin', async () => { + const b = await fixture() + await b.ctx.plugin(ConnectorAccounts) + await b.ctx.plugin(McpAccounts) + const stream = b.ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const plugin = b.mount() + await plugin.await() + const shown = await until(stream, view => view.accounts[0]?.display.phase === 'disconnected') + expect(shown.accounts).toHaveLength(1) + expect(shown.accounts[0]).toMatchObject({ + key: 'mcp:linear', packageName: '@deepseek-ai/dsh-linear', + copy: { title: COPY.title, activation: { connect: COPY.connect } }, display: { phase: 'disconnected' }, + }) + await plugin.dispose() + await until(stream, view => view.accounts.length === 0) +}) + +it('refuses to load when a configured server already uses the Linear name', async () => { + const b = await fixture({ linear: { transport: 'streamable-http', url: 'https://linear.example/mcp', enabled: false } }) + await expect(b.mount().await()).rejects.toThrow('server "linear" is already configured or registered') + expect(await b.prompt()).not.toContain(GUIDANCE) +}) + +it('refuses to load when a configured server already uses the Linear credential key', async () => { + const b = await fixture({ tracker: { transport: 'streamable-http', url: 'https://tracker.example/mcp', oauth: { credentialKey: 'mcp-client/linear' }, enabled: false } }) + await expect(b.mount().await()).rejects.toThrow('OAuth credentialKey is already assigned to another server') + expect(await b.prompt()).not.toContain(GUIDANCE) +}) diff --git a/packages/connector/linear/tsconfig.json b/packages/connector/linear/tsconfig.json new file mode 100644 index 0000000000..64cc75ae5b --- /dev/null +++ b/packages/connector/linear/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../mcp/mcp-manager" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../mcp/mcp-account" + } + ] +} diff --git a/packages/connector/notion/README.i18n.yaml b/packages/connector/notion/README.i18n.yaml new file mode 100644 index 0000000000..e87f0f6156 --- /dev/null +++ b/packages/connector/notion/README.i18n.yaml @@ -0,0 +1,73 @@ +# 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/connector/notion/README.md +/: + en: 0aa30500a6748dff + zh: ecfb242e80df586f +/deepseek-ai-dsh-notion: + en: ebcdb43f309b330c + zh: 364385eb8bbf6171 +/deepseek-ai-dsh-notion/summary: + en: 05703b12e01e8b04 + zh: 9dff7eb9cfbeae68 +/deepseek-ai-dsh-notion/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-notion/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-notion/use-this-package/install-into-a-profile: + en: 917f72b8c57fa68a + zh: d2e5a6d4337c6048 +/deepseek-ai-dsh-notion/use-this-package/authorize-and-sign-out: + en: 2b77a82c90e41194 + zh: ab7d72148ead15d3 +/deepseek-ai-dsh-notion/use-this-package/turn-off-and-uninstall: + en: 8fb8e3a36288a635 + zh: 3ba01fe30e802d1f +/deepseek-ai-dsh-notion/use-this-package/configure: + en: 74b045a61a3fec72 + zh: 69d64b33e8d1812e +/deepseek-ai-dsh-notion/understand-the-implementation: + en: 5a12bb3e000c4cc9 + zh: 6431dcb502c1d7af +/deepseek-ai-dsh-notion/further-exploration: + en: ed7d1edadf2feef5 + zh: 6746823e51e4f4f3 +/deepseek-ai-dsh-notion/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance: + en: 01b6ec6d681e457b + zh: 7fe0d1c9d1037bd4 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/what-the-model-sees: + en: a62a8dbe1f7b7944 + zh: 32a94fa68d8b30c2 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/what-the-model-sees/guidance-text: + en: 8f57292f6821da96 + zh: b2d3bc7e5c9cbc05 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/token-effect: + en: 263969c79903e387 + zh: d45f9e49d9a252c3 +/deepseek-ai-dsh-notion/model-experience/naming-and-connection-guidance/kv-cache-effect: + en: e9668826c9355444 + zh: 66f609e3779fd510 +/deepseek-ai-dsh-notion/model-experience/notion-server-tools-and-instructions: + en: ae0fe892d237cd8d + zh: bfd6c55b83ff9f8c +/deepseek-ai-dsh-notion/model-experience/notion-server-tools-and-instructions/what-the-model-sees: + en: 1acff8ce3a0dbdc4 + zh: f392c0dfc07c8b2c +/deepseek-ai-dsh-notion/model-experience/notion-server-tools-and-instructions/token-effect: + en: ea047c321d077856 + zh: d50bd0a0579c0a6c +/deepseek-ai-dsh-notion/model-experience/notion-server-tools-and-instructions/kv-cache-effect: + en: 5bed63237f352122 + zh: a82a734d98bf1ba7 +/deepseek-ai-dsh-notion/known-limitations-and-deferred-work: + en: 9f145e50fb31de42 + zh: fdc6da981ae79456 +/deepseek-ai-dsh-notion/known-limitations-and-deferred-work/dev-note: + en: be76e387a7ea3a71 + zh: d53904834ac3525c diff --git a/packages/connector/notion/README.md b/packages/connector/notion/README.md new file mode 100644 index 0000000000..589feba39a --- /dev/null +++ b/packages/connector/notion/README.md @@ -0,0 +1,155 @@ +--- +description: "Connect Notion's hosted MCP server through the shared MCP manager, authorize it with OAuth, and use its tools in conversations." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-notion + +English | [中文](README.zh.md) + +## Summary + +The Notion plugin registers Notion's hosted MCP server, `https://mcp.notion.com/mcp`, with the Host's shared [MCP manager](../../mcp/mcp-manager/README.md) for as long as the plugin is loaded. The user connects a Notion account from the plugin's page on the Web sidebar's **Plugins** page; afterwards every conversation on that Host can use the server's tools, and the model is told to call the integration the Notion plugin. The manager owns the connection, OAuth authorization, the saved grant, and sign-out, which the shared [MCP account service](../../mcp/mcp-account/README.md) shows on the Plugins page. It runs in the Web and Desktop compositions. + +## 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 + +### Install into a profile + +Install the package as a bundle, for example from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-notion +``` + +The bundle patch inserts the `notion` row after the profile's other layers. The plugin requires the `mcpManager` and `systemPrompt` services, which the Web and Desktop compositions provide through [`dsh-web-app`](../../bundle/web-app/README.md). In a profile without the MCP manager, such as `headless`, the plugin does not activate, and startup prints a warning that names the missing `mcpManager` service. + +### Authorize and sign out + +The plugin registers the server `notion` with the fixed OAuth credential key `mcp-client/notion`. Without a saved grant the server waits for authorization and exposes no Notion tools. With a saved grant the manager connects at startup and refreshes tokens as needed. Notion's tools load [on demand](../../mcp/mcp-client/README.md#on-demand-tool-loading) by default: the system prompt lists them, and each agent loads the ones it needs with `mcp__notion__load_tools`. + +While the plugin is on, its page on the **Plugins** page shows a **Notion account** section, and a tag beside the title reads Not connected, Connecting, Connected, Reconnect, or Unavailable. Switching the plugin on from the list while no account is connected offers **Connect Notion**, which opens the plugin's page and starts authorization. + +| Section state | Action | +|---|---| +| Not connected, or the grant expired, no longer matches the settings, was rejected, or lacks permissions | **Connect Notion** or **Connect again** starts an authorization attempt | +| Waiting for you to confirm in the browser | The browser that started the attempt opens Notion's authorization page once; **Open authorization page** opens it again, and **Cancel** ends the attempt | +| Connected | **Sign out** asks for confirmation, then deletes the local grant | +| Cannot connect right now | **Retry** restarts the server and keeps the existing grant | + +Authorization must be completed in a browser on the Host machine. After the user approves access in Notion, the callback page says DSH received the authorization; the section then shows the result. Leaving the page does not cancel an attempt, which the Host owns. A failed attempt shows **Authorization was not completed. Try again.**; a failed page action shows a toast. Sign-out keeps the client registration and does not revoke the connection on Notion's side. + +The page follows the account through the [`connectorAccounts` Remote](../../client/ui-connector-account/README.md) under the key `mcp:notion`, and its buttons start `connect`, `sign-out`, or `retry` or cancel the attempt there. On the Host, [`dsh-mcp-account`](../../mcp/mcp-account/README.md) runs them through the manager's [OAuth operations](../../mcp/mcp-manager/README.md#oauth-authorization): `startAuthorization('notion')` returns an attempt whose `authorizationUrl` the stream reports, `cancelAuthorization('notion', id)` cancels it, `signOut('notion')` deletes the grant, and `restart('notion')` retries. Other Remote clients can use the same operations. + +### Turn off and uninstall + +Turning the row off in Plugin Manager, or uninstalling the package, ends the registration: the Notion tools leave the model's tool set, and the saved grant stays in the credentials store, so reinstalling reuses it. To remove the grant, sign out while the plugin is loaded, or delete the `mcp-client/notion` record from `$DSH_HOME/.credentials.yaml` as the [local credentials provider](../../credentials/credentials-local/README.md) documents. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `url` | `https://mcp.notion.com/mcp` | Streamable HTTP MCP endpoint of the Notion server | +| `toolLoading` | `on-demand` | `on-demand` keeps Notion's tools hidden from each agent until it loads them; `eager` sends every tool definition with every request | + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-notion) is the exhaustive source of supported fields. Connection and authorization budgets use the manager and mcp-client defaults. The saved grant is bound to `url`; changing it requires connecting the account again. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts one row with id `notion` naming this package, so the package is both the bundle and its only row; `config` overrides target that id. The Host half, [`src/index.ts`](src/index.ts), makes two registrations, both effects of the plugin's fiber: `ctx.mcpManager.register('notion', …)` adds a Streamable HTTP entry with the configured `url` and OAuth credential key, and `ctx.systemPrompt.section()` adds the naming guidance at the `MCP_SERVERS` order. The server name fixes the `mcp__notion__` tool namespace, and the credential key fixes the grant address, so a reloaded or reinstalled plugin reaches the same tools and grant. The manager validates the entry when it is registered; a configured or registered server that already uses the name or key makes the plugin fail to load before the guidance is added. + +While the account registry runs, the plugin also calls `ctx.mcpAccounts.register({ server: 'notion', packageName: '@deepseek-ai/dsh-notion', copy })`, where [`src/locales.ts`](src/locales.ts) holds the text that names Notion in every shipped language; [`dsh-mcp-account`](../../mcp/mcp-account/README.md) then registers the account with the connector account registry, which renders the section, guidance, tag, and toast described above. A composition without the registry, such as a headless profile, loads the plugin without the account section. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [MCP manager](../../mcp/mcp-manager/README.md) — registration lifetime, status, OAuth authorization, and sign-out. +- [MCP client](../../mcp/mcp-client/README.md) — connection, tool naming, OAuth grant refresh, and redaction. +- [MCP subsystem](../../../docs/subsystems/mcp.md) — how the MCP packages fit together. +- [Plugin Manager](../../boot/plugin-manager/README.md) — installation and enablement. +- [MCP account service](../../mcp/mcp-account/README.md) — how the manager's status and authorization map to the account section. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the section, tag, guidance, and notices the account registration shows. +- [Plugins page](../../client/ui-plugin-manager/README.md#use-this-package) — the bundle page those surfaces occupy. + +----- + + +## Model Experience + +### Naming and connection guidance + +#### What the model sees + +While the plugin is loaded, the system prompt contains the text below after the MCP server sections, whether or not Notion is authorized. + +##### Guidance text + +```markdown +Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins. +``` + +#### Token effect + +The two fixed sentences add about 70 tokens to every request while the plugin is loaded. + +#### KV Cache effect + +The sentence is prefix-stable: it changes only when the plugin loads or unloads, not when authorization or the connection changes. + +### Notion server tools and instructions + +#### What the model sees + +After authorization, the model sees Notion's server instructions under `### MCP server: notion` and, with the default `toolLoading: on-demand`, the loader `mcp__notion__load_tools` and a [catalog of Notion's tools](../../mcp/mcp-client/README.md#model-experience) in the system prompt; each tool it loads then appears as `mcp__notion__` with Notion's description and input schema. With `eager`, every tool appears from the start, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. With `on-demand`, the loader and the catalog appear only once Notion is connected. While the plugin is loaded, including before authorization, the [shared resource tools](../../mcp/mcp-resources/README.md#model-experience) and their server-name prompt list `notion`. + +#### Token effect + +Notion's server defines the tool set and instructions, and their size can change without a DSH update. With `on-demand`, a connected Notion costs its instructions, the loader, and a catalog of about 6,400 characters for its 46 tools, plus the definitions an agent has loaded; with `eager`, all definitions, about 214,500 characters, repeat on every request. + +#### KV Cache effect + +Notion's instructions (or, with `eager`, its tools) appear when the connection succeeds and disappear when authorization is withdrawn or the plugin unloads; each change can invalidate reuse from the first changed token. With `on-demand`, the catalog changes only when Notion's tool list does, and each load changes the agent's next tool list, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. The shared resource tools stay unchanged across connection changes. + +## Known Limitations and Deferred Work + + + +- The Notion account section exists only while the plugin is on. To sign out after turning the plugin off, turn it on again or delete the grant record. +- Only the Web and Desktop compositions mount the MCP manager; other profiles leave the plugin inactive. +- The authorization callback is `http://127.0.0.1:` on the Host, so the browser that completes authorization must run on the Host machine. A Web Host reached from another machine cannot finish authorization. +- Desktop listens on an OS-assigned port for each launch. Authorizing again after a restart registers a new OAuth client and keeps the earlier registration record; saved grants refresh normally across restarts. +- Before the account is connected, the shared resource prompt still lists `notion` as a server name, and resource calls to it fail until the user connects. +- One Notion authorization serves the whole Host; there is no account or workspace picker. +- Turning the plugin off or uninstalling it keeps the local grant. Signing out deletes the local grant but leaves the connection authorized on Notion's side until the user removes it there. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs run the plugin against the MCP manager and the mcp-client loopback OAuth server fixture; another checks that the account registry serves the Notion account with its text and withdraws it with the plugin. The `notion-plugin` session snapshot replays the Notion row without a saved grant, so it pins the naming guidance and verifies that no request reaches the server. + +
diff --git a/packages/connector/notion/README.zh.md b/packages/connector/notion/README.zh.md new file mode 100644 index 0000000000..3dca05834d --- /dev/null +++ b/packages/connector/notion/README.zh.md @@ -0,0 +1,155 @@ +--- +description: "通过共用的 MCP 管理器接入 Notion 托管的 MCP 服务器,经 OAuth 授权后在对话中使用其工具。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-notion + +[English](README.md) | 中文 + +## 概述 + +Notion 插件在加载期间把 Notion 托管的 MCP 服务器 `https://mcp.notion.com/mcp` 注册到 Host 共用的 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)。用户在 Web 侧栏**插件**页面的插件详情页中连接 Notion 账号,之后该 Host 上的所有对话都能使用这个服务器的工具,模型也会被告知把这项集成称为 Notion 插件。连接、OAuth 授权、已保存的 grant 和退出登录都由管理器负责,并由共用的 [MCP 账号服务](../../mcp/mcp-account/README.zh.md)显示在插件页面上。插件运行在 Web 与 Desktop 组合中。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +将本包作为 bundle 安装,例如在 Web 侧栏的**插件**页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-notion +``` + +bundle patch 在 profile 其他层之后插入 `notion` 行。插件需要 `mcpManager` 与 `systemPrompt` 服务,Web 与 Desktop 组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 提供它们。在没有 MCP 管理器的 profile(例如 `headless`)中,插件不会激活,启动时会打印一条警告,指出缺少 `mcpManager` 服务。 + +### 授权与退出登录 + +插件以固定的 OAuth 凭据 key `mcp-client/notion` 注册服务器 `notion`。没有已保存的 grant 时,服务器等待授权,不提供 Notion 工具。有已保存的 grant 时,管理器在启动时连接,并按需刷新 token。Notion 的工具默认[按需加载](../../mcp/mcp-client/README.zh.md#on-demand-tool-loading):系统提示词列出这些工具,每个 agent 用 `mcp__notion__load_tools` 加载需要的工具。 + +插件开启期间,它在**插件**页面的详情页显示 **Notion 账号**区块,标题旁的标签显示未连接、连接中、已连接、需要重新连接或暂时无法连接。在列表中开启插件而尚未连接账号时,页面提示**连接 Notion**,点击后打开插件详情页并发起授权。 + +| 区块状态 | 操作 | +|---|---| +| 未连接,或授权已过期、与当前设置不再匹配、被拒绝、缺少权限 | **连接 Notion** 或**重新连接**发起一次授权尝试 | +| 等待你在浏览器中确认 | 发起尝试的浏览器打开一次 Notion 授权页面;**打开授权页面**再次打开,**取消**结束这次尝试 | +| 已连接 | **退出登录**确认后删除本地 grant | +| 暂时无法连接 | **重试**重启服务器并保留现有授权 | + +授权必须在 Host 所在机器的浏览器中完成。用户在 Notion 中同意授权后,回调页面说明 DSH 已收到授权,区块随后显示结果。离开页面不会取消授权尝试,尝试由 Host 持有。授权失败时显示**授权未完成,请重试**;页面操作失败时显示 toast。退出登录保留客户端注册,不会在 Notion 一侧撤销连接。 + +页面通过 [`connectorAccounts` Remote](../../client/ui-connector-account/README.zh.md) 以 key `mcp:notion` 跟随账号,其按钮在该 Remote 上发起 `connect`、`sign-out` 或 `retry`,或取消授权尝试。在 Host 上,[`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 通过管理器的 [OAuth 操作](../../mcp/mcp-manager/README.zh.md#oauth-authorization)执行它们:`startAuthorization('notion')` 返回一次授权尝试,其 `authorizationUrl` 由流报告,`cancelAuthorization('notion', id)` 取消它,`signOut('notion')` 删除 grant,`restart('notion')` 重试。其他 Remote 客户端可以使用同样的操作。 + +### 停用与卸载 + +在 Plugin Manager 中关闭该行或卸载本包都会结束注册:Notion 工具从模型的工具集中撤下,已保存的 grant 留在凭据存储中,因此重新安装会复用它。要删除 grant,请在插件加载期间退出登录,或按[本地凭据提供方](../../credentials/credentials-local/README.zh.md)的说明,从 `$DSH_HOME/.credentials.yaml` 中删除 `mcp-client/notion` 记录。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `url` | `https://mcp.notion.com/mcp` | Notion 服务器的 Streamable HTTP MCP 端点 | +| `toolLoading` | `on-demand` | `on-demand` 让 Notion 的工具在 agent 加载前对其隐藏;`eager` 在每次请求中发送全部工具定义 | + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-notion)是受支持字段的完整来源。连接与授权的预算使用管理器和 mcp-client 的默认值。已保存的 grant 与 `url` 绑定,修改后需要重新连接账号。 + +----- + + +## 理解实现 + +
+实现内部机制——点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 插入一行 id 为 `notion` 的条目,指向本包,因此本包既是 bundle,也是其唯一的一行;`config` 覆盖以该 id 为目标。Host 侧的 [`src/index.ts`](src/index.ts) 进行两项注册,二者都是插件 fiber 的 effect:`ctx.mcpManager.register('notion', …)` 以配置的 `url` 和 OAuth 凭据 key 添加一个 Streamable HTTP 条目,`ctx.systemPrompt.section()` 在 `MCP_SERVERS` 排序位置添加称呼指引。服务器名固定了 `mcp__notion__` 工具命名空间,凭据 key 固定了 grant 地址,因此重新加载或重新安装的插件会得到同样的工具和 grant。管理器在注册时校验条目;如果已配置或已注册的服务器占用了该名称或 key,插件会在添加指引之前加载失败。 + +账号注册表运行时,插件还调用 `ctx.mcpAccounts.register({ server: 'notion', packageName: '@deepseek-ai/dsh-notion', copy })`,其中 [`src/locales.ts`](src/locales.ts) 以每种已发布语言保存指明 Notion 的文案;随后由 [`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 把账号登记到连接器账号注册表,由注册表渲染上文所述的区块、引导、标签与 toast。没有注册表的组合(如 headless profile)加载插件时不带账号区块。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md)——这个应用插件所属的分组。 +- [MCP 管理器](../../mcp/mcp-manager/README.zh.md)——注册生命周期、状态、OAuth 授权与退出登录。 +- [MCP 客户端](../../mcp/mcp-client/README.zh.md)——连接、工具命名、OAuth grant 刷新与脱敏。 +- [MCP 子系统](../../../docs/subsystems/mcp.zh.md)——各 MCP 包如何协同。 +- [Plugin Manager](../../boot/plugin-manager/README.zh.md)——安装与启用。 +- [MCP 账号服务](../../mcp/mcp-account/README.zh.md)——管理器的状态与授权如何映射到账号区块。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md)——账号注册后显示的区块、标签、引导与提示。 +- [插件页面](../../client/ui-plugin-manager/README.zh.md#use-this-package)——这些界面所在的 bundle 详情页。 + +----- + + +## 模型体验 + +### 称呼与连接指引 + +#### 模型看到什么 + +插件加载期间,无论 Notion 是否已授权,系统提示词都会在 MCP 服务器各节之后包含下面这段文字。 + +##### 指引文本 + +```markdown +Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP. If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins. +``` + +#### Token 影响 + +插件加载期间,这两句固定文字为每次请求增加约 70 个 token。 + +#### KV Cache 影响 + +这句话保持前缀稳定:只在插件加载或卸载时变化,授权或连接状态变化不会改变它。 + +### Notion 服务器工具与说明 + +#### 模型看到什么 + +授权之后,模型会在 `### MCP server: notion` 之下看到 Notion 的服务器说明;在默认的 `toolLoading: on-demand` 下,还会看到加载器 `mcp__notion__load_tools`,以及系统提示词中的 [Notion 工具目录](../../mcp/mcp-client/README.zh.md#model-experience),加载的每个工具随后以 `mcp__notion__` 命名,带有 Notion 提供的描述和输入 schema。设为 `eager` 时,所有工具从一开始就出现,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。设为 `on-demand` 时,加载器和目录只在 Notion 连接后出现。插件加载期间(包括授权之前),[共用的资源工具](../../mcp/mcp-resources/README.zh.md#model-experience)及其服务器名提示词都会列出 `notion`。 + +#### Token 影响 + +工具集与服务器说明由 Notion 服务器定义,其大小可能在 DSH 不更新的情况下变化。设为 `on-demand` 时,已连接的 Notion 的开销是服务器说明、加载工具、46 个工具约 6,400 字符的目录,以及 agent 已加载的定义;设为 `eager` 时,全部定义(约 214,500 字符)在每次请求中重复出现。 + +#### KV Cache 影响 + +Notion 的服务器说明(设为 `eager` 时则是其工具)在连接成功时出现,在授权被撤回或插件卸载时消失;每次变化都可能使从第一个变化 token 起的复用失效。设为 `on-demand` 时,目录只在 Notion 的工具列表变化时变化,每次加载都会改变该 agent 下一次请求的工具列表,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。共用的资源工具在连接变化前后保持不变。 + +## 已知限制与延期工作 + + + +- Notion 账号区块只在插件开启时存在。关闭插件后如需退出登录,请先重新开启插件,或删除 grant 记录。 +- 只有 Web 与 Desktop 组合挂载 MCP 管理器;在其他 profile 中插件保持未激活。 +- 授权回调地址是 Host 上的 `http://127.0.0.1:`,因此完成授权的浏览器必须运行在 Host 所在机器上。从另一台机器访问的 Web Host 无法完成授权。 +- Desktop 每次启动都监听操作系统分配的端口。重启后再次授权会注册一个新的 OAuth 客户端,并保留之前的注册记录;已保存的 grant 在重启前后正常刷新。 +- 账号连接之前,共享资源的提示词仍把 `notion` 列为服务器名,对它的资源调用会失败,直到用户完成连接。 +- 一次 Notion 授权供整个 Host 使用;没有账号或工作区选择器。 +- 停用或卸载插件会保留本地 grant。退出登录会删除本地 grant,但在用户于 Notion 一侧移除之前,该连接在 Notion 中仍处于已授权状态。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 侧单测让插件运行在 MCP 管理器和 mcp-client 的回环 OAuth 服务器夹具之上;另一项单测检查账号注册表提供带文案的 Notion 账号,并随插件一起撤下。`notion-plugin` 会话快照在没有已保存 grant 的情况下回放 Notion 行,因此它固定称呼指引,并验证没有请求到达服务器。 + +
diff --git a/packages/connector/notion/cordis.patch.yml b/packages/connector/notion/cordis.patch.yml new file mode 100644 index 0000000000..e7326ee1c9 --- /dev/null +++ b/packages/connector/notion/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: notion + name: '@deepseek-ai/dsh-notion' diff --git a/packages/connector/notion/docs/DETAIL.md b/packages/connector/notion/docs/DETAIL.md new file mode 100644 index 0000000000..e923469cf2 --- /dev/null +++ b/packages/connector/notion/docs/DETAIL.md @@ -0,0 +1 @@ +![The connected Notion account on the plugin page and a conversation that searches Notion pages](preview.svg) diff --git a/packages/connector/notion/docs/DETAIL.zh.md b/packages/connector/notion/docs/DETAIL.zh.md new file mode 100644 index 0000000000..3c714ad17a --- /dev/null +++ b/packages/connector/notion/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已连接的 Notion 账号,以及在对话中搜索 Notion 页面](preview.zh.svg) diff --git a/packages/connector/notion/docs/preview.svg b/packages/connector/notion/docs/preview.svg new file mode 100644 index 0000000000..ddaafc4f93 --- /dev/null +++ b/packages/connector/notion/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/notion/docs/preview.zh.svg b/packages/connector/notion/docs/preview.zh.svg new file mode 100644 index 0000000000..570c3b00da --- /dev/null +++ b/packages/connector/notion/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/notion/icon.svg b/packages/connector/notion/icon.svg new file mode 100644 index 0000000000..75cb870951 --- /dev/null +++ b/packages/connector/notion/icon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages/connector/notion/locale/de.json b/packages/connector/notion/locale/de.json new file mode 100644 index 0000000000..b2f6a77c2e --- /dev/null +++ b/packages/connector/notion/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Notion-Plugin", + "description": "Verwenden Sie Seiten, Datenbanken und weitere autorisierte Inhalte von Notion in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/en.json b/packages/connector/notion/locale/en.json new file mode 100644 index 0000000000..ff0621b4e4 --- /dev/null +++ b/packages/connector/notion/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Notion plugin", + "description": "Use Notion pages, databases, and other authorized content in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/es.json b/packages/connector/notion/locale/es.json new file mode 100644 index 0000000000..cfee867fe6 --- /dev/null +++ b/packages/connector/notion/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de Notion", + "description": "Use páginas, bases de datos y otro contenido autorizado de Notion en las conversaciones.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/fr.json b/packages/connector/notion/locale/fr.json new file mode 100644 index 0000000000..0965c90bb2 --- /dev/null +++ b/packages/connector/notion/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin Notion", + "description": "Utilisez les pages, les bases de données et les autres contenus autorisés de Notion dans les conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/ja.json b/packages/connector/notion/locale/ja.json new file mode 100644 index 0000000000..d49362eb68 --- /dev/null +++ b/packages/connector/notion/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Notion プラグイン", + "description": "会話の中で Notion のページ、データベース、その他の承認済みコンテンツを使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/pt.json b/packages/connector/notion/locale/pt.json new file mode 100644 index 0000000000..bbc7e4acca --- /dev/null +++ b/packages/connector/notion/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do Notion", + "description": "Use páginas, bancos de dados e outros conteúdos autorizados do Notion nas conversas.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/ru.json b/packages/connector/notion/locale/ru.json new file mode 100644 index 0000000000..f65a358ddf --- /dev/null +++ b/packages/connector/notion/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин Notion", + "description": "Используйте страницы, базы данных и другой разрешённый контент Notion в беседах.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/notion/locale/zh.json b/packages/connector/notion/locale/zh.json new file mode 100644 index 0000000000..5498971acc --- /dev/null +++ b/packages/connector/notion/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Notion 插件", + "description": "在对话中使用 Notion 页面、数据库及其他已授权的内容。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/notion/package.json b/packages/connector/notion/package.json new file mode 100644 index 0000000000..40af295521 --- /dev/null +++ b/packages/connector/notion/package.json @@ -0,0 +1,67 @@ +{ + "name": "@deepseek-ai/dsh-notion", + "description": "Notion plugin: Notion's hosted MCP server, authorized through the shared MCP manager", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/notion" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-mcp-account": "workspace:*", + "@deepseek-ai/dsh-mcp-manager": "workspace:*", + "@deepseek-ai/dsh-mcp-resources": "workspace:*", + "@deepseek-ai/dsh-scope": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*" + } +} diff --git a/packages/connector/notion/src/index.ts b/packages/connector/notion/src/index.ts new file mode 100644 index 0000000000..bb042c97d0 --- /dev/null +++ b/packages/connector/notion/src/index.ts @@ -0,0 +1,65 @@ +/** + * Notion plugin: registers Notion's hosted MCP server with the shared MCP + * manager for this plugin's lifetime, tells the model to call it the Notion + * plugin, and shows the account on the Plugins page while the account registry + * runs. The manager owns connection, OAuth authorization, saved grants, and + * sign-out; once a grant exists, the server's `mcp__notion__*` tools are + * listed in the system prompt and each agent loads the ones it needs. + * @module @deepseek-ai/dsh-notion + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-mcp-account' +import type {} from '@deepseek-ai/dsh-mcp-manager' +import type {} from '@deepseek-ai/dsh-system-prompt' +import { COPY } from './locales.ts' + +export const name = 'notion' +export const inject = ['mcpManager', 'systemPrompt'] + +// One shared account per Host: a fixed server name keeps tool names stable and +// a fixed credential key lets a reinstalled plugin reuse its saved grant. +const SERVER_NAME = 'notion' +const CREDENTIAL_KEY = 'mcp-client/notion' +const GUIDANCE = 'Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP.' + + ' If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins.' + +/** Notion MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Notion's hosted server. */ + url: string + /** `on-demand` (default) keeps Notion's tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} + +/** Runtime configuration schema for the Notion plugin. */ +export const Config: z, Config> = z.object({ + url: z.string().default('https://mcp.notion.com/mcp'), + toolLoading: z.union(['eager', 'on-demand']).default('on-demand'), +}) + +/** + * Register the Notion server, its naming guidance, and, while the account registry runs, its Plugins page account; all + * are withdrawn when the plugin unloads. + * @param ctx - Context carrying the MCP manager and system prompt. + * @param config - Notion endpoint and tool loading. + * @throws when another configured or registered server already uses the `notion` name or credential key. + */ +export function apply(ctx: Context, config: Config): void { + ctx.mcpManager.register(SERVER_NAME, { + transport: 'streamable-http', + url: config.url, + oauth: { credentialKey: CREDENTIAL_KEY }, + toolLoading: config.toolLoading, + }) + // Sections at one order sort by name, so `notion` follows every `mcp…` server section. + ctx.systemPrompt.section({ + name: SERVER_NAME, + order: ctx.systemPrompt.getSectionOrder('MCP_SERVERS'), + text: GUIDANCE, + }) + ctx.inject(['mcpAccounts'], (scope) => { + scope.effect(() => scope.mcpAccounts.register({ server: SERVER_NAME, packageName: '@deepseek-ai/dsh-notion', copy: COPY }), 'notion: Plugins page account') + }) +} diff --git a/packages/connector/notion/src/locales.ts b/packages/connector/notion/src/locales.ts new file mode 100644 index 0000000000..9ecde9af32 --- /dev/null +++ b/packages/connector/notion/src/locales.ts @@ -0,0 +1,167 @@ +/** The Plugins page text that names Notion; the shared account copy comes from the account surfaces' dictionary. */ +import type { McpAccountCopy } from '@deepseek-ai/dsh-mcp-account' + +/** Every language the Web app ships. */ +type ShippedText = Readonly> + +/** Notion's account text in every shipped language. */ +export const COPY: McpAccountCopy = { + title: { + zh: 'Notion 账号', + en: 'Notion account', + ja: 'Notion アカウント', + es: 'Cuenta de Notion', + fr: 'Compte Notion', + de: 'Notion-Konto', + ru: 'Аккаунт Notion', + pt: 'Conta do Notion', + }, + connect: { + zh: '连接 Notion', + en: 'Connect Notion', + ja: 'Notion を接続', + es: 'Conectar Notion', + fr: 'Connecter Notion', + de: 'Notion verbinden', + ru: 'Подключить Notion', + pt: 'Conectar Notion', + }, + activation: { + title: { + zh: '连接 Notion 账号', + en: 'Connect your Notion account', + ja: 'Notion アカウントを接続', + es: 'Conecte su cuenta de Notion', + fr: 'Connectez votre compte Notion', + de: 'Notion-Konto verbinden', + ru: 'Подключите аккаунт Notion', + pt: 'Conecte sua conta do Notion', + }, + body: { + zh: 'Notion 插件已开启。连接你的 Notion 账号后,就可以在对话中使用它。', + en: 'The Notion plugin is on. Connect your Notion account to use it in conversations.', + ja: 'Notion プラグインがオンになりました。Notion アカウントを接続すると、会話の中で使用できます。', + es: 'El complemento de Notion está activado. Conecte su cuenta de Notion para usarlo en las conversaciones.', + fr: 'Le plugin Notion est activé. Connectez votre compte Notion pour l’utiliser dans les conversations.', + de: 'Das Notion-Plugin ist aktiviert. Verbinden Sie Ihr Notion-Konto, um es in Unterhaltungen zu verwenden.', + ru: 'Плагин Notion включён. Подключите аккаунт Notion, чтобы использовать его в беседах.', + pt: 'O plugin do Notion está ativado. Conecte sua conta do Notion para usá-lo nas conversas.', + }, + }, + detail: { + disconnected: { + zh: '连接 Notion 账号后,可以在对话中搜索、读取和编辑你授权的页面与数据库。', + en: 'Connect your Notion account to search, read, and edit the pages and databases you authorize, right from a conversation.', + ja: 'Notion アカウントを接続すると、承認したページやデータベースを会話の中から直接検索、閲覧、編集できます。', + es: 'Conecte su cuenta de Notion para buscar, leer y editar las páginas y bases de datos que autorice, directamente desde una conversación.', + fr: 'Connectez votre compte Notion pour rechercher, lire et modifier les pages et bases de données que vous autorisez, directement depuis une conversation.', + de: 'Verbinden Sie Ihr Notion-Konto, um die von Ihnen freigegebenen Seiten und Datenbanken direkt aus einer Unterhaltung heraus zu durchsuchen, zu lesen und zu bearbeiten.', + ru: 'Подключите аккаунт Notion, чтобы искать, читать и редактировать разрешённые вами страницы и базы данных прямо из беседы.', + pt: 'Conecte sua conta do Notion para pesquisar, ler e editar as páginas e os bancos de dados que você autorizar, direto de uma conversa.', + }, + waitingBrowser: { + zh: '已打开 Notion 授权页面。在 Notion 中确认后,回到这里查看结果。', + en: 'The Notion authorization page is open. Confirm in Notion, then come back here to see the result.', + ja: 'Notion の認可ページを開きました。Notion で確定したら、ここに戻って結果を確認してください。', + es: 'La página de autorización de Notion está abierta. Confirme en Notion y luego vuelva aquí para ver el resultado.', + fr: 'La page d’autorisation Notion est ouverte. Confirmez dans Notion, puis revenez ici pour voir le résultat.', + de: 'Die Notion-Autorisierungsseite ist geöffnet. Bestätigen Sie in Notion und kehren Sie dann hierher zurück, um das Ergebnis zu sehen.', + ru: 'Страница авторизации Notion открыта. Подтвердите в Notion, затем вернитесь сюда, чтобы увидеть результат.', + pt: 'A página de autorização do Notion está aberta. Confirme no Notion e depois volte aqui para ver o resultado.', + }, + authorizing: { + zh: '正在与 Notion 完成授权。', + en: 'Finishing authorization with Notion.', + ja: 'Notion での認可を完了しています。', + es: 'Completando la autorización con Notion.', + fr: 'Finalisation de l’autorisation avec Notion.', + de: 'Die Autorisierung mit Notion wird abgeschlossen.', + ru: 'Завершение авторизации в Notion.', + pt: 'Concluindo a autorização com o Notion.', + }, + connecting: { + zh: '正在连接 Notion。', + en: 'Connecting to Notion.', + ja: 'Notion に接続しています。', + es: 'Conectando con Notion.', + fr: 'Connexion à Notion en cours.', + de: 'Verbindung mit Notion wird hergestellt.', + ru: 'Подключение к Notion.', + pt: 'Conectando ao Notion.', + }, + connected: { + zh: '可以在对话中直接请 Agent 使用 Notion。', + en: 'Ask the agent to use Notion directly in a conversation.', + ja: '会話の中でエージェントに Notion の使用を直接依頼できます。', + es: 'Pida al agente que use Notion directamente en una conversación.', + fr: 'Demandez à l’agent d’utiliser Notion directement dans une conversation.', + de: 'Bitten Sie den Agenten, Notion direkt in einer Unterhaltung zu verwenden.', + ru: 'Попросите агента использовать Notion прямо в беседе.', + pt: 'Peça ao agente que use o Notion diretamente em uma conversa.', + }, + rejected: { + zh: 'Notion 不再接受当前授权,请重新连接。', + en: 'Notion no longer accepts the current authorization. Connect again.', + ja: 'Notion は現在の認可を受け付けなくなりました。再度接続してください。', + es: 'Notion ya no acepta la autorización actual. Vuelva a conectar.', + fr: 'Notion n’accepte plus l’autorisation actuelle. Reconnectez-vous.', + de: 'Notion akzeptiert die aktuelle Autorisierung nicht mehr. Verbinden Sie erneut.', + ru: 'Notion больше не принимает текущую авторизацию. Подключитесь снова.', + pt: 'O Notion não aceita mais a autorização atual. Conecte novamente.', + }, + scope: { + zh: '当前授权缺少所需权限。重新连接时,请在 Notion 中确认权限。', + en: 'The current authorization lacks required permissions. Confirm them in Notion when you connect again.', + ja: '現在の認可には必要な権限が不足しています。再度接続するときに、Notion で権限を確認してください。', + es: 'A la autorización actual le faltan permisos necesarios. Confírmelos en Notion cuando vuelva a conectar.', + fr: 'L’autorisation actuelle ne dispose pas des permissions requises. Confirmez-les dans Notion lors de la reconnexion.', + de: 'Der aktuellen Autorisierung fehlen erforderliche Berechtigungen. Bestätigen Sie diese in Notion, wenn Sie erneut verbinden.', + ru: 'Текущей авторизации не хватает нужных разрешений. Подтвердите их в Notion при повторном подключении.', + pt: 'A autorização atual não tem as permissões necessárias. Confirme-as no Notion ao conectar novamente.', + }, + }, + signOut: { + title: { + zh: '退出 Notion 登录?', + en: 'Sign out of Notion?', + ja: 'Notion からサインアウトしますか?', + es: '¿Cerrar sesión en Notion?', + fr: 'Se déconnecter de Notion ?', + de: 'Von Notion abmelden?', + ru: 'Выйти из Notion?', + pt: 'Sair do Notion?', + }, + body: { + zh: '将删除 DSH 保存的 Notion 授权,之后对话中无法使用 Notion。如需在 Notion 一侧撤销连接,请到 Notion 的设置中处理。', + en: 'This deletes the Notion authorization DSH saved, so conversations can no longer use Notion. To revoke the connection on Notion\'s side, use Notion\'s settings.', + ja: 'DSH が保存した Notion の認可を削除します。以後、会話の中で Notion は使用できなくなります。Notion 側で接続を取り消すには、Notion の設定から行ってください。', + es: 'Se eliminará la autorización de Notion que guardó DSH, por lo que las conversaciones ya no podrán usar Notion. Para revocar la conexión del lado de Notion, use la configuración de Notion.', + fr: 'Cela supprime l’autorisation Notion enregistrée par DSH : les conversations ne pourront plus utiliser Notion. Pour révoquer la connexion côté Notion, utilisez les paramètres de Notion.', + de: 'Dadurch wird die von DSH gespeicherte Notion-Autorisierung gelöscht, sodass Unterhaltungen Notion nicht mehr verwenden können. Um die Verbindung auf Notion-Seite zu widerrufen, verwenden Sie die Einstellungen von Notion.', + ru: 'Сохранённая DSH авторизация Notion будет удалена, и беседы больше не смогут использовать Notion. Чтобы отозвать подключение на стороне Notion, воспользуйтесь настройками Notion.', + pt: 'Isso exclui a autorização do Notion salva pelo DSH, e as conversas não poderão mais usar o Notion. Para revogar a conexão no lado do Notion, use as configurações do Notion.', + }, + }, + notice: { + connected: { + zh: 'Notion 已连接', + en: 'Notion connected', + ja: 'Notion を接続しました', + es: 'Notion conectado', + fr: 'Notion connecté', + de: 'Notion verbunden', + ru: 'Notion подключён', + pt: 'Notion conectado', + }, + signedOut: { + zh: '已退出 Notion 登录', + en: 'Signed out of Notion', + ja: 'Notion からサインアウトしました', + es: 'Sesión de Notion cerrada', + fr: 'Déconnecté de Notion', + de: 'Von Notion abgemeldet', + ru: 'Выполнен выход из Notion', + pt: 'Você saiu do Notion', + }, + }, +} diff --git a/packages/connector/notion/tests/plugin.spec.ts b/packages/connector/notion/tests/plugin.spec.ts new file mode 100644 index 0000000000..849185fa87 --- /dev/null +++ b/packages/connector/notion/tests/plugin.spec.ts @@ -0,0 +1,139 @@ +/** Notion plugin over a real MCP manager profile and a loopback OAuth MCP server. */ + +import { expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import ConnectorAccounts from '@deepseek-ai/dsh-client-ui-connector-account' +import type { ConnectorAccountsView } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import McpAccounts from '@deepseek-ai/dsh-mcp-account' +import { parseCredentialKey } from '@deepseek-ai/dsh-credentials' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import type { McpManagedServerStatus } from '@deepseek-ai/dsh-mcp-manager' +import McpResources from '@deepseek-ai/dsh-mcp-resources' +import { createScope } from '@deepseek-ai/dsh-scope' +import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import { callback, oauthWorld, phase } from '../../../mcp/mcp-client/tests/oauth-fixture.ts' +import { managerProfile } from '../../../mcp/mcp-manager/tests/profile-fixture.ts' +import { COPY } from '../src/locales.ts' +import * as Notion from '../src/index.ts' + +// Verbatim pin of the model-visible guidance in src/index.ts. +const GUIDANCE = 'Tools named `mcp__notion__*` come from the Notion plugin. In user-facing replies, call it the Notion plugin (Notion 插件 in Chinese), not MCP.' + + ' If no `mcp__notion__*` tool appears in your tool list, Notion is not connected yet; ask the user to connect it on the Notion plugin page in Plugins.' + +async function fixture(servers: Record = {}) { + const world = await oauthWorld() + await world.ctx.plugin(McpResources) + await managerProfile(world.ctx, { base: { servers } }) + const view = () => world.ctx.mcpManager.list().find(entry => entry.name === 'notion') + const state = async (expected: McpManagedServerStatus['state']) => { + await vi.waitFor(() => { expect(view()?.status.state).toBe(expected) }, { timeout: 5000 }) + } + const mount = (config: Partial = {}) => world.ctx.plugin(Notion, { url: world.origin + '/mcp', ...config }) + const prompt = async () => renderPrompt(await world.ctx.systemPrompt.assemble()) + const ping = () => executeToolFixture(world.ctx, { + callId: ToolCallId('notion-ping'), name: 'mcp__notion__ping', arguments: {}, signal: new AbortController().signal, + }) + const grant = async () => (await world.ctx.credentials.describeRecord(parseCredentialKey('mcp-client/notion'))).configured + const agent = async (): Promise => { + const holder: { ctx?: Context } = {} + const created = holder as Agent + await world.ctx.plugin({ inject: ['tools'], apply(inner: Context) { holder.ctx = createScope(inner, created).ctx } }) + await world.ctx.serial('agent/created', { agent: created, source: 'startup' }) + return created + } + const authorize = async () => { + await world.ctx.mcpManager.startAuthorization('notion') + expect(await callback(await phase(() => view()?.authorization, 'waiting-browser'))).toBe(200) + await state('connected') + } + return { ...world, view, state, mount, prompt, ping, grant, agent, authorize } +} + +it('defaults to the hosted Notion endpoint', () => { + expect(Notion.Config({})).toEqual({ url: 'https://mcp.notion.com/mcp', toolLoading: 'on-demand' }) +}) + +it('registers Notion for the plugin lifetime and reuses the saved grant after reloading', async () => { + const b = await fixture() + // Eager tools register for the Host, so the test calls them without an agent. + const first = b.mount({ toolLoading: 'eager' }) + await first.await() + await b.state('waiting-authorization') + expect(b.view()?.status).toMatchObject({ reason: 'missing' }) + expect(await b.prompt()).toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + + await b.authorize() + expect(await b.ping()).toMatchObject({ isError: false }) + + await first.dispose() + expect(b.view()).toBeUndefined() + expect(await b.prompt()).not.toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + expect(await b.grant()).toBe(true) + + const tokens = b.tokens() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(await b.ping()).toMatchObject({ isError: false }) + expect(b.view()?.authorization).toBeUndefined() + expect(b.tokens()).toBe(tokens) + expect(b.registrations()).toBe(1) +}) + +it('keeps Notion tools hidden from an agent until it loads them, unless loading is eager', async () => { + const b = await fixture() + const agent = await b.agent() + const onDemand = b.mount() + await onDemand.await() + await b.authorize() + expect(b.ctx.tools.get('mcp__notion__ping', agent)).toBeUndefined() + expect(b.ctx.tools.get('mcp__notion__load_tools', agent)).toBeDefined() + expect(await executeToolFixture(b.ctx, { + callId: ToolCallId('notion-load'), name: 'mcp__notion__load_tools', arguments: { tools: ['ping'] }, + signal: new AbortController().signal, agent, + })).toMatchObject({ isError: false, value: 'Loaded: mcp__notion__ping.' }) + expect(b.ctx.tools.get('mcp__notion__ping', agent)).toBeDefined() + + await onDemand.dispose() + const other = await b.agent() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(b.ctx.tools.get('mcp__notion__ping', other)).toBeDefined() +}) + +/** Read the account stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('account stream ended') + if (predicate(next.value)) return next.value + } +} + +it('shows the Notion account on the Plugins page while the account registry runs, and withdraws it with the plugin', async () => { + const b = await fixture() + await b.ctx.plugin(ConnectorAccounts) + await b.ctx.plugin(McpAccounts) + const stream = b.ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const plugin = b.mount() + await plugin.await() + const shown = await until(stream, view => view.accounts[0]?.display.phase === 'disconnected') + expect(shown.accounts).toHaveLength(1) + expect(shown.accounts[0]).toMatchObject({ + key: 'mcp:notion', packageName: '@deepseek-ai/dsh-notion', + copy: { title: COPY.title, activation: { connect: COPY.connect } }, display: { phase: 'disconnected' }, + }) + await plugin.dispose() + await until(stream, view => view.accounts.length === 0) +}) + +it('refuses to load when a configured server already uses the Notion name', async () => { + const b = await fixture({ notion: { transport: 'streamable-http', url: 'https://notion.example/mcp', enabled: false } }) + await expect(b.mount().await()).rejects.toThrow('server "notion" is already configured or registered') + expect(await b.prompt()).not.toContain(GUIDANCE) +}) diff --git a/packages/connector/notion/tsconfig.json b/packages/connector/notion/tsconfig.json new file mode 100644 index 0000000000..64cc75ae5b --- /dev/null +++ b/packages/connector/notion/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../mcp/mcp-manager" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../mcp/mcp-account" + } + ] +} diff --git a/packages/connector/tencent-docs/README.i18n.yaml b/packages/connector/tencent-docs/README.i18n.yaml new file mode 100644 index 0000000000..cf65da47a5 --- /dev/null +++ b/packages/connector/tencent-docs/README.i18n.yaml @@ -0,0 +1,73 @@ +# 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/connector/tencent-docs/README.md +/: + en: f2aa025c1a83f5d1 + zh: cd338274e8c0369d +/deepseek-ai-dsh-tencent-docs: + en: ff0576142fce4834 + zh: d023d707f178caca +/deepseek-ai-dsh-tencent-docs/summary: + en: c047ee71e7afbc74 + zh: 04803010ff621ffc +/deepseek-ai-dsh-tencent-docs/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-tencent-docs/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-tencent-docs/use-this-package/install-into-a-profile: + en: 7295c38ae39a6fa9 + zh: 916aa4d0957947d5 +/deepseek-ai-dsh-tencent-docs/use-this-package/authorize-and-sign-out: + en: 80317ae1536c2be7 + zh: 7fd6047630341d86 +/deepseek-ai-dsh-tencent-docs/use-this-package/turn-off-and-uninstall: + en: cdf842ac6315592d + zh: 4da861bf7b4b0103 +/deepseek-ai-dsh-tencent-docs/use-this-package/configure: + en: 78ac23e5b8c3b3b8 + zh: c7647d4d295b09a1 +/deepseek-ai-dsh-tencent-docs/understand-the-implementation: + en: 8a265026213ccfb1 + zh: 5cefdd54f3f54850 +/deepseek-ai-dsh-tencent-docs/further-exploration: + en: ed7d1edadf2feef5 + zh: 6746823e51e4f4f3 +/deepseek-ai-dsh-tencent-docs/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-tencent-docs/model-experience/naming-and-connection-guidance: + en: 01b6ec6d681e457b + zh: 7fe0d1c9d1037bd4 +/deepseek-ai-dsh-tencent-docs/model-experience/naming-and-connection-guidance/what-the-model-sees: + en: 88651686be8bfac8 + zh: 565d22517eb75caa +/deepseek-ai-dsh-tencent-docs/model-experience/naming-and-connection-guidance/what-the-model-sees/guidance-text: + en: 8f57292f6821da96 + zh: b2d3bc7e5c9cbc05 +/deepseek-ai-dsh-tencent-docs/model-experience/naming-and-connection-guidance/token-effect: + en: 84d7d1b6d163d9c7 + zh: 67702d3c0af1e71b +/deepseek-ai-dsh-tencent-docs/model-experience/naming-and-connection-guidance/kv-cache-effect: + en: 9c7a599f4647412c + zh: 673c0dff65e62cd8 +/deepseek-ai-dsh-tencent-docs/model-experience/tencent-docs-server-tools-and-instructions: + en: 9b36d4220cb15c69 + zh: c4a42cf41e188a96 +/deepseek-ai-dsh-tencent-docs/model-experience/tencent-docs-server-tools-and-instructions/what-the-model-sees: + en: 0d667e69e5ecdc0d + zh: a27973e262047d22 +/deepseek-ai-dsh-tencent-docs/model-experience/tencent-docs-server-tools-and-instructions/token-effect: + en: 111920ef3a87ba01 + zh: b376cc9090aeac84 +/deepseek-ai-dsh-tencent-docs/model-experience/tencent-docs-server-tools-and-instructions/kv-cache-effect: + en: d75083f436e3d0a4 + zh: 0c822645ff1ca2a4 +/deepseek-ai-dsh-tencent-docs/known-limitations-and-deferred-work: + en: 1247abbc5ca63d64 + zh: e8ab350f9970bfe4 +/deepseek-ai-dsh-tencent-docs/known-limitations-and-deferred-work/dev-note: + en: 4fa2f13da1b0f858 + zh: c66d6c8e3bd8bc34 diff --git a/packages/connector/tencent-docs/README.md b/packages/connector/tencent-docs/README.md new file mode 100644 index 0000000000..49ccaaaaf2 --- /dev/null +++ b/packages/connector/tencent-docs/README.md @@ -0,0 +1,155 @@ +--- +description: "Connect Tencent Docs' hosted MCP server through the shared MCP manager, authorize it with OAuth, and use its tools in conversations." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-tencent-docs + +English | [中文](README.zh.md) + +## Summary + +The Tencent Docs plugin registers Tencent Docs' hosted MCP server, `https://docs.qq.com/openapi/mcp`, with the Host's shared [MCP manager](../../mcp/mcp-manager/README.md) while the plugin is loaded. The user connects a Tencent Docs account from the plugin's page on the Web sidebar's **Plugins** page; afterwards every conversation on that Host can use the server's tools, and the model is told to call it the Tencent Docs plugin. The manager owns the connection, OAuth authorization, saved grant, and sign-out, which the shared [MCP account service](../../mcp/mcp-account/README.md) shows on the Plugins page. It runs in the Web and Desktop compositions. + +## 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 + +### Install into a profile + +Install the package as a bundle, for example from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-tencent-docs +``` + +The bundle patch inserts the `tencent-docs` row after the profile's other layers. The plugin requires the `mcpManager` and `systemPrompt` services: the [base bundle](../../bundle/base/README.md) provides `systemPrompt`, and the Web and Desktop compositions add the MCP manager through [`dsh-web-app`](../../bundle/web-app/README.md). In a profile without the MCP manager, such as `headless`, the plugin does not activate, and startup prints a warning that names the missing `mcpManager` service. + +### Authorize and sign out + +The plugin registers the server `tencent-docs` with the fixed OAuth credential key `mcp-client/tencent-docs`. Without a saved grant the server waits for authorization and exposes no Tencent Docs tools. With a saved grant the manager connects at startup and refreshes tokens as needed. Tencent Docs' tools load [on demand](../../mcp/mcp-client/README.md#on-demand-tool-loading) by default: the system prompt lists them, and each agent loads the ones it needs with `mcp__tencent-docs__load_tools`. + +While the plugin is on, its page on the **Plugins** page shows a **Tencent Docs account** section, and a tag beside the title reads Not connected, Connecting, Connected, Reconnect, or Unavailable. Switching the plugin on from the list while no account is connected offers **Connect Tencent Docs**, which opens the plugin's page and starts authorization. + +| Section state | Action | +|---|---| +| Not connected, or the grant expired, no longer matches the settings, was rejected, or lacks permissions | **Connect Tencent Docs** or **Connect again** starts an authorization attempt | +| Waiting for you to confirm in the browser | The browser that started the attempt opens Tencent Docs' authorization page once; **Open authorization page** opens it again, and **Cancel** ends the attempt | +| Connected | **Sign out** asks for confirmation, then deletes the local grant | +| Cannot connect right now | **Retry** restarts the server and keeps the existing grant | + +Authorization must be completed in a browser on the Host machine. After the user approves access in Tencent Docs, the callback page says DSH received the authorization; the section then shows the result. Leaving the page does not cancel an attempt, which the Host owns. A failed attempt shows **Authorization was not completed. Try again.**; a failed page action shows a toast. Sign-out keeps the client registration and does not revoke the tokens Tencent Docs issued. + +The page follows the account through the [`connectorAccounts` Remote](../../client/ui-connector-account/README.md) under the key `mcp:tencent-docs`, and its buttons start `connect`, `sign-out`, or `retry` or cancel the attempt there. On the Host, [`dsh-mcp-account`](../../mcp/mcp-account/README.md) runs them through the manager's [OAuth operations](../../mcp/mcp-manager/README.md#oauth-authorization): `startAuthorization('tencent-docs')` returns an attempt whose `authorizationUrl` the stream reports, `cancelAuthorization('tencent-docs', id)` cancels it, `signOut('tencent-docs')` deletes the grant, and `restart('tencent-docs')` retries. Other Remote clients can use the same operations. + +### Turn off and uninstall + +Turning the row off in Plugin Manager, or uninstalling the package, ends the registration: the Tencent Docs tools leave the model's tool set, and the saved grant stays in the credentials store, so reinstalling reuses it. To remove the grant, sign out while the plugin is loaded, or delete the `mcp-client/tencent-docs` record from `$DSH_HOME/.credentials.yaml` as the [local credentials provider](../../credentials/credentials-local/README.md) documents. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `url` | `https://docs.qq.com/openapi/mcp` | Streamable HTTP MCP endpoint of the Tencent Docs server | +| `toolLoading` | `on-demand` | `on-demand` keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends every tool definition with every request | + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-tencent-docs) is the exhaustive source of supported fields. Connection and authorization budgets use the manager and mcp-client defaults. The saved grant is bound to `url`; changing it requires connecting the account again. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts one row with id `tencent-docs` naming this package, so the package is both the bundle and its only row; `config` overrides target that id. The Host half, [`src/index.ts`](src/index.ts), makes two registrations, both effects of the plugin's fiber: `ctx.mcpManager.register('tencent-docs', …)` adds a Streamable HTTP entry with the configured `url` and OAuth credential key, and `ctx.systemPrompt.section()` adds the naming guidance at the `MCP_SERVERS` order. The server name fixes the `mcp__tencent-docs__` tool namespace, and the credential key fixes the grant address, so a reloaded or reinstalled plugin reaches the same tools and grant. The manager validates the entry when it is registered; a configured or registered server that already uses the name or key makes the plugin fail to load before the guidance is added. The entry sets no `scope`, so authorization requests the `docs:read docs:write docs:manage` scopes listed in the protected-resource metadata that Tencent Docs' 401 challenge names, and the authorization page keeps the `authType=2` query of Tencent Docs' authorization endpoint. + +While the account registry runs, the plugin also calls `ctx.mcpAccounts.register({ server: 'tencent-docs', packageName: '@deepseek-ai/dsh-tencent-docs', copy })`, where [`src/locales.ts`](src/locales.ts) holds the text that names Tencent Docs in every shipped language; [`dsh-mcp-account`](../../mcp/mcp-account/README.md) then registers the account with the connector account registry, which renders the section, guidance, tag, and toast described above. A composition without the registry, such as a headless profile, loads the plugin without the account section. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [MCP manager](../../mcp/mcp-manager/README.md) — registration lifetime, status, OAuth authorization, and sign-out. +- [MCP client](../../mcp/mcp-client/README.md) — connection, tool naming, OAuth grant refresh, and redaction. +- [MCP subsystem](../../../docs/subsystems/mcp.md) — how the MCP packages fit together. +- [Plugin Manager](../../boot/plugin-manager/README.md) — installation and enablement. +- [MCP account service](../../mcp/mcp-account/README.md) — how the manager's status and authorization map to the account section. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the section, tag, guidance, and notices the account registration shows. +- [Plugins page](../../client/ui-plugin-manager/README.md#use-this-package) — the bundle page those surfaces occupy. + +----- + + +## Model Experience + +### Naming and connection guidance + +#### What the model sees + +While the plugin is loaded, the system prompt contains the text below after the MCP server sections, whether or not Tencent Docs is authorized. + +##### Guidance text + +```markdown +Tools named `mcp__tencent-docs__*` come from the Tencent Docs plugin. In user-facing replies, call it the Tencent Docs plugin (腾讯文档插件 in Chinese), not MCP. If no `mcp__tencent-docs__*` tool appears in your tool list, Tencent Docs is not connected yet; ask the user to connect it on the Tencent Docs plugin page in Plugins. +``` + +#### Token effect + +The three fixed sentences add about 80 tokens to every request while the plugin is loaded. + +#### KV Cache effect + +The guidance is prefix-stable: it changes only when the plugin loads or unloads, not when authorization or the connection changes. + +### Tencent Docs server tools and instructions + +#### What the model sees + +After authorization, the model sees Tencent Docs' server instructions under `### MCP server: tencent-docs` and, with the default `toolLoading: on-demand`, the loader `mcp__tencent-docs__load_tools` and a [catalog of Tencent Docs' tools](../../mcp/mcp-client/README.md#model-experience) in the system prompt; each tool it loads then appears as `mcp__tencent-docs__` with Tencent Docs' description and input schema. Many Tencent Docs tool names contain a dot, such as `doc.create_with_markdown`; the catalog lists them unchanged, and their loaded names replace the dot and add a hash suffix, such as `mcp__tencent-docs__doc_create_with_markdown_ff0986999909`, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. With `eager`, every tool appears from the start, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. With `on-demand`, the loader and the catalog appear only once Tencent Docs is connected. While the plugin is loaded, including before authorization, the [shared resource tools](../../mcp/mcp-resources/README.md#model-experience) and their server-name prompt list `tencent-docs`. + +#### Token effect + +Tencent Docs' server defines the tool set and instructions, and their size can change without a DSH update. With `on-demand`, a connected Tencent Docs costs about 3,000 characters of instructions, the loader, and a catalog of about 37,900 characters for its 225 tools, plus the definitions an agent has loaded; with `eager`, all 225 definitions repeat on every request. + +#### KV Cache effect + +Tencent Docs' instructions (or, with `eager`, its tools) appear when the connection succeeds and disappear when authorization is withdrawn or the plugin unloads; each change can invalidate reuse from the first changed token. With `on-demand`, the catalog changes only when Tencent Docs' tool list does, and each load changes the agent's next tool list, as the [MCP client](../../mcp/mcp-client/README.md#model-experience) documents. The shared resource tools stay unchanged across connection changes. + +## Known Limitations and Deferred Work + + + +- The Tencent Docs account section exists only while the plugin is on. To sign out after turning the plugin off, turn it on again or delete the grant record. +- Only the Web and Desktop compositions mount the MCP manager; other profiles leave the plugin inactive. +- The authorization callback is `http://127.0.0.1:` on the Host, so the browser that completes authorization must run on the Host machine. A Web Host reached from another machine cannot finish authorization. +- Desktop listens on an OS-assigned port for each launch. Authorizing again after a restart registers a new OAuth client and keeps the earlier registration record; saved grants refresh normally across restarts. +- Before the account is connected, the shared resource prompt still lists `tencent-docs` as a server name, and resource calls to it fail until the user connects. +- One Tencent Docs authorization serves the whole Host; there is no account or workspace picker. +- Turning the plugin off or uninstalling it keeps the local grant. Signing out deletes the local grant, but DSH does not revoke the tokens Tencent Docs issued; Tencent Docs' authorization server publishes no revocation endpoint. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Host specs run the plugin against the MCP manager and the mcp-client loopback OAuth server fixture; another checks that the account registry serves the Tencent Docs account with its text and withdraws it with the plugin. The `tencent-docs-plugin` session snapshot replays the Tencent Docs row without a saved grant, so it pins the naming guidance and verifies that no request reaches the server. The Web e2e fixture follows the hosted metadata layout: the challenge names resource metadata under the MCP path, that metadata lists the `docs:*` scopes, and the authorization endpoint carries its own query. + +
diff --git a/packages/connector/tencent-docs/README.zh.md b/packages/connector/tencent-docs/README.zh.md new file mode 100644 index 0000000000..db41c0ad8c --- /dev/null +++ b/packages/connector/tencent-docs/README.zh.md @@ -0,0 +1,155 @@ +--- +description: "通过共用的 MCP 管理器接入腾讯文档托管的 MCP 服务器,经 OAuth 授权后在对话中使用其工具。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-tencent-docs + +[English](README.md) | 中文 + +## 概述 + +腾讯文档插件在加载期间把腾讯文档托管的 MCP 服务器 `https://docs.qq.com/openapi/mcp` 注册到 Host 共用的 [MCP 管理器](../../mcp/mcp-manager/README.zh.md)。用户在 Web 侧栏**插件**页面的插件详情页中连接腾讯文档账号,之后该 Host 上的所有对话都能使用这个服务器的工具,模型也会被告知把它称为腾讯文档插件。连接、OAuth 授权、已保存的 grant 和退出登录都由管理器负责,并由共用的 [MCP 账号服务](../../mcp/mcp-account/README.zh.md)显示在插件页面上。插件运行在 Web 与 Desktop 组合中。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +将本包作为 bundle 安装,例如在 Web 侧栏的**插件**页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-tencent-docs +``` + +bundle patch 在 profile 其他层之后插入 `tencent-docs` 行。插件需要 `mcpManager` 与 `systemPrompt` 服务:[base bundle](../../bundle/base/README.zh.md) 提供 `systemPrompt`,Web 与 Desktop 组合通过 [`dsh-web-app`](../../bundle/web-app/README.zh.md) 补上 MCP 管理器。在没有 MCP 管理器的 profile(例如 `headless`)中,插件不会激活,启动时会打印一条警告,指出缺少 `mcpManager` 服务。 + +### 授权与退出登录 + +插件以固定的 OAuth 凭据 key `mcp-client/tencent-docs` 注册服务器 `tencent-docs`。没有已保存的 grant 时,服务器等待授权,不提供腾讯文档工具。有已保存的 grant 时,管理器在启动时连接,并按需刷新 token。腾讯文档的工具默认[按需加载](../../mcp/mcp-client/README.zh.md#on-demand-tool-loading):系统提示词列出这些工具,每个 agent 用 `mcp__tencent-docs__load_tools` 加载需要的工具。 + +插件开启期间,它在**插件**页面的详情页显示 **腾讯文档账号**区块,标题旁的标签显示未连接、连接中、已连接、需要重新连接或暂时无法连接。在列表中开启插件而尚未连接账号时,页面提示**连接腾讯文档**,点击后打开插件详情页并发起授权。 + +| 区块状态 | 操作 | +|---|---| +| 未连接,或授权已过期、与当前设置不再匹配、被拒绝、缺少权限 | **连接腾讯文档** 或**重新连接**发起一次授权尝试 | +| 等待你在浏览器中确认 | 发起尝试的浏览器打开一次腾讯文档授权页面;**打开授权页面**再次打开,**取消**结束这次尝试 | +| 已连接 | **退出登录**确认后删除本地 grant | +| 暂时无法连接 | **重试**重启服务器并保留现有授权 | + +授权必须在 Host 所在机器的浏览器中完成。用户在腾讯文档中同意授权后,回调页面说明 DSH 已收到授权,区块随后显示结果。离开页面不会取消授权尝试,尝试由 Host 持有。授权失败时显示**授权未完成,请重试**;页面操作失败时显示 toast。退出登录保留客户端注册,不会撤销腾讯文档签发的 token。 + +页面通过 [`connectorAccounts` Remote](../../client/ui-connector-account/README.zh.md) 以 key `mcp:tencent-docs` 跟随账号,其按钮在该 Remote 上发起 `connect`、`sign-out` 或 `retry`,或取消授权尝试。在 Host 上,[`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 通过管理器的 [OAuth 操作](../../mcp/mcp-manager/README.zh.md#oauth-authorization)执行它们:`startAuthorization('tencent-docs')` 返回一次授权尝试,其 `authorizationUrl` 由流报告,`cancelAuthorization('tencent-docs', id)` 取消它,`signOut('tencent-docs')` 删除 grant,`restart('tencent-docs')` 重试。其他 Remote 客户端可以使用同样的操作。 + +### 停用与卸载 + +在 Plugin Manager 中关闭该行或卸载本包都会结束注册:腾讯文档工具从模型的工具集中撤下,已保存的 grant 留在凭据存储中,因此重新安装会复用它。要删除 grant,请在插件加载期间退出登录,或按[本地凭据提供方](../../credentials/credentials-local/README.zh.md)的说明,从 `$DSH_HOME/.credentials.yaml` 中删除 `mcp-client/tencent-docs` 记录。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `url` | `https://docs.qq.com/openapi/mcp` | 腾讯文档服务器的 Streamable HTTP MCP 端点 | +| `toolLoading` | `on-demand` | `on-demand` 让腾讯文档的工具在 agent 加载前对其隐藏;`eager` 在每次请求中发送全部工具定义 | + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tencent-docs)是受支持字段的完整来源。连接与授权的预算使用管理器和 mcp-client 的默认值。已保存的 grant 与 `url` 绑定,修改后需要重新连接账号。 + +----- + + +## 理解实现 + +
+实现内部机制——点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 插入一行 id 为 `tencent-docs` 的条目,指向本包,因此本包既是 bundle,也是其唯一的一行;`config` 覆盖以该 id 为目标。Host 侧的 [`src/index.ts`](src/index.ts) 进行两项注册,二者都是插件 fiber 的 effect:`ctx.mcpManager.register('tencent-docs', …)` 以配置的 `url` 和 OAuth 凭据 key 添加一个 Streamable HTTP 条目,`ctx.systemPrompt.section()` 在 `MCP_SERVERS` 排序位置添加称呼指引。服务器名固定了 `mcp__tencent-docs__` 工具命名空间,凭据 key 固定了 grant 地址,因此重新加载或重新安装的插件会得到同样的工具和 grant。管理器在注册时校验条目;如果已配置或已注册的服务器占用了该名称或 key,插件会在添加指引之前加载失败。条目未设置 `scope`,因此授权请求腾讯文档 401 challenge 所指资源元数据中列出的 `docs:read docs:write docs:manage` scope,授权页面保留腾讯文档授权端点自带的 `authType=2` 查询参数。 + +账号注册表运行时,插件还调用 `ctx.mcpAccounts.register({ server: 'tencent-docs', packageName: '@deepseek-ai/dsh-tencent-docs', copy })`,其中 [`src/locales.ts`](src/locales.ts) 以每种已发布语言保存指明腾讯文档的文案;随后由 [`dsh-mcp-account`](../../mcp/mcp-account/README.zh.md) 把账号登记到连接器账号注册表,由注册表渲染上文所述的区块、引导、标签与 toast。没有注册表的组合(如 headless profile)加载插件时不带账号区块。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md)——这个应用插件所属的分组。 +- [MCP 管理器](../../mcp/mcp-manager/README.zh.md)——注册生命周期、状态、OAuth 授权与退出登录。 +- [MCP 客户端](../../mcp/mcp-client/README.zh.md)——连接、工具命名、OAuth grant 刷新与脱敏。 +- [MCP 子系统](../../../docs/subsystems/mcp.zh.md)——各 MCP 包如何协同。 +- [Plugin Manager](../../boot/plugin-manager/README.zh.md)——安装与启用。 +- [MCP 账号服务](../../mcp/mcp-account/README.zh.md)——管理器的状态与授权如何映射到账号区块。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md)——账号注册后显示的区块、标签、引导与提示。 +- [插件页面](../../client/ui-plugin-manager/README.zh.md#use-this-package)——这些界面所在的 bundle 详情页。 + +----- + + +## 模型体验 + +### 称呼与连接指引 + +#### 模型看到什么 + +插件加载期间,无论腾讯文档是否已授权,系统提示词都会在 MCP 服务器各节之后包含下面这段文字。 + +##### 指引文本 + +```markdown +Tools named `mcp__tencent-docs__*` come from the Tencent Docs plugin. In user-facing replies, call it the Tencent Docs plugin (腾讯文档插件 in Chinese), not MCP. If no `mcp__tencent-docs__*` tool appears in your tool list, Tencent Docs is not connected yet; ask the user to connect it on the Tencent Docs plugin page in Plugins. +``` + +#### Token 影响 + +插件加载期间,这三句固定文字为每次请求增加约 80 个 token。 + +#### KV Cache 影响 + +这段指引保持前缀稳定:只在插件加载或卸载时变化,授权或连接状态变化不会改变它。 + +### 腾讯文档服务器工具与说明 + +#### 模型看到什么 + +授权之后,模型会在 `### MCP server: tencent-docs` 之下看到腾讯文档的服务器说明;在默认的 `toolLoading: on-demand` 下,还会看到加载器 `mcp__tencent-docs__load_tools`,以及系统提示词中的[腾讯文档工具目录](../../mcp/mcp-client/README.zh.md#model-experience),加载的每个工具随后以 `mcp__tencent-docs__` 命名,带有腾讯文档提供的描述和输入 schema。腾讯文档的许多工具名包含点号,例如 `doc.create_with_markdown`;目录按原样列出这些名称,加载后的名称把点号替换掉并加上哈希后缀,例如 `mcp__tencent-docs__doc_create_with_markdown_ff0986999909`,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。设为 `eager` 时,所有工具从一开始就出现,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。设为 `on-demand` 时,加载器和目录只在腾讯文档连接后出现。插件加载期间(包括授权之前),[共用的资源工具](../../mcp/mcp-resources/README.zh.md#model-experience)及其服务器名提示词都会列出 `tencent-docs`。 + +#### Token 影响 + +工具集与服务器说明由腾讯文档服务器定义,其大小可能在 DSH 不更新的情况下变化。设为 `on-demand` 时,已连接的腾讯文档的开销是约 3,000 字符的服务器说明、加载工具、225 个工具约 37,900 字符的目录,以及 agent 已加载的定义;设为 `eager` 时,全部 225 个定义在每次请求中重复出现。 + +#### KV Cache 影响 + +腾讯文档的服务器说明(设为 `eager` 时则是其工具)在连接成功时出现,在授权被撤回或插件卸载时消失;每次变化都可能使从第一个变化 token 起的复用失效。设为 `on-demand` 时,目录只在腾讯文档的工具列表变化时变化,每次加载都会改变该 agent 下一次请求的工具列表,详见 [MCP 客户端](../../mcp/mcp-client/README.zh.md#model-experience)。共用的资源工具在连接变化前后保持不变。 + +## 已知限制与延期工作 + + + +- 腾讯文档账号区块只在插件开启时存在。关闭插件后如需退出登录,请先重新开启插件,或删除 grant 记录。 +- 只有 Web 与 Desktop 组合挂载 MCP 管理器;在其他 profile 中插件保持未激活。 +- 授权回调地址是 Host 上的 `http://127.0.0.1:`,因此完成授权的浏览器必须运行在 Host 所在机器上。从另一台机器访问的 Web Host 无法完成授权。 +- Desktop 每次启动都监听操作系统分配的端口。重启后再次授权会注册一个新的 OAuth 客户端,并保留之前的注册记录;已保存的 grant 在重启前后正常刷新。 +- 账号连接之前,共享资源的提示词仍把 `tencent-docs` 列为服务器名,对它的资源调用会失败,直到用户完成连接。 +- 一次腾讯文档授权供整个 Host 使用;没有账号或工作区选择器。 +- 停用或卸载插件会保留本地 grant。退出登录会删除本地 grant,但 DSH 不会撤销腾讯文档已签发的 token;腾讯文档的授权服务器没有公布撤销端点。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +Host 侧单测让插件运行在 MCP 管理器和 mcp-client 的回环 OAuth 服务器夹具之上;另一项单测检查账号注册表提供带文案的腾讯文档账号,并随插件一起撤下。`tencent-docs-plugin` 会话快照在没有已保存 grant 的情况下回放腾讯文档行,因此它固定称呼指引,并验证没有请求到达服务器。Web e2e 的夹具按托管服务的元数据布局:challenge 指向 MCP 路径下的资源元数据,该元数据列出 `docs:*` scope,授权端点自带查询参数。 + +
diff --git a/packages/connector/tencent-docs/cordis.patch.yml b/packages/connector/tencent-docs/cordis.patch.yml new file mode 100644 index 0000000000..23f53d6cf1 --- /dev/null +++ b/packages/connector/tencent-docs/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: tencent-docs + name: '@deepseek-ai/dsh-tencent-docs' diff --git a/packages/connector/tencent-docs/docs/DETAIL.md b/packages/connector/tencent-docs/docs/DETAIL.md new file mode 100644 index 0000000000..520776f448 --- /dev/null +++ b/packages/connector/tencent-docs/docs/DETAIL.md @@ -0,0 +1 @@ +![The connected Tencent Docs account on the plugin page and a conversation that creates a doc in Tencent Docs](preview.svg) diff --git a/packages/connector/tencent-docs/docs/DETAIL.zh.md b/packages/connector/tencent-docs/docs/DETAIL.zh.md new file mode 100644 index 0000000000..2ebf86bb9a --- /dev/null +++ b/packages/connector/tencent-docs/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已连接的腾讯文档账号,以及在对话中创建一份腾讯文档](preview.zh.svg) diff --git a/packages/connector/tencent-docs/docs/preview.svg b/packages/connector/tencent-docs/docs/preview.svg new file mode 100644 index 0000000000..91fd249d1c --- /dev/null +++ b/packages/connector/tencent-docs/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/tencent-docs/docs/preview.zh.svg b/packages/connector/tencent-docs/docs/preview.zh.svg new file mode 100644 index 0000000000..a342047dca --- /dev/null +++ b/packages/connector/tencent-docs/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/tencent-docs/icon.svg b/packages/connector/tencent-docs/icon.svg new file mode 100644 index 0000000000..2449934a91 --- /dev/null +++ b/packages/connector/tencent-docs/icon.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages/connector/tencent-docs/locale/de.json b/packages/connector/tencent-docs/locale/de.json new file mode 100644 index 0000000000..2284cfb22f --- /dev/null +++ b/packages/connector/tencent-docs/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Docs-Plugin", + "description": "Verwenden Sie Tencent Docs-Inhalte, auf die Sie Zugriff haben, in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/en.json b/packages/connector/tencent-docs/locale/en.json new file mode 100644 index 0000000000..c43eb2ab69 --- /dev/null +++ b/packages/connector/tencent-docs/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Docs plugin", + "description": "Use the Tencent Docs content you can access in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/es.json b/packages/connector/tencent-docs/locale/es.json new file mode 100644 index 0000000000..eb1c08e064 --- /dev/null +++ b/packages/connector/tencent-docs/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de Tencent Docs", + "description": "Use en las conversaciones el contenido de Tencent Docs al que tiene acceso.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/fr.json b/packages/connector/tencent-docs/locale/fr.json new file mode 100644 index 0000000000..fe74189286 --- /dev/null +++ b/packages/connector/tencent-docs/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin Tencent Docs", + "description": "Utilisez dans les conversations le contenu Tencent Docs auquel vous avez accès.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/ja.json b/packages/connector/tencent-docs/locale/ja.json new file mode 100644 index 0000000000..ce9027ca0f --- /dev/null +++ b/packages/connector/tencent-docs/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Docs プラグイン", + "description": "会話の中で、アクセス権のある Tencent Docs のコンテンツを使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/pt.json b/packages/connector/tencent-docs/locale/pt.json new file mode 100644 index 0000000000..1e01fa8e73 --- /dev/null +++ b/packages/connector/tencent-docs/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do Tencent Docs", + "description": "Use nas conversas o conteúdo do Tencent Docs ao qual você tem acesso.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/ru.json b/packages/connector/tencent-docs/locale/ru.json new file mode 100644 index 0000000000..d913856bde --- /dev/null +++ b/packages/connector/tencent-docs/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин Tencent Docs", + "description": "Используйте в беседах доступный вам контент Tencent Docs.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-docs/locale/zh.json b/packages/connector/tencent-docs/locale/zh.json new file mode 100644 index 0000000000..b3c7dfec79 --- /dev/null +++ b/packages/connector/tencent-docs/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "腾讯文档插件", + "description": "在对话中使用你有权限的腾讯文档内容。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/tencent-docs/package.json b/packages/connector/tencent-docs/package.json new file mode 100644 index 0000000000..1974bb2d3d --- /dev/null +++ b/packages/connector/tencent-docs/package.json @@ -0,0 +1,67 @@ +{ + "name": "@deepseek-ai/dsh-tencent-docs", + "description": "Tencent Docs plugin: Tencent Docs' hosted MCP server, authorized through the shared MCP manager", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/tencent-docs" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "scripts": { + "bundle": "tsdown", + "watch": "tsdown --watch" + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-mcp-account": "workspace:*", + "@deepseek-ai/dsh-mcp-manager": "workspace:*", + "@deepseek-ai/dsh-mcp-resources": "workspace:*", + "@deepseek-ai/dsh-scope": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-testkit": "workspace:*" + } +} diff --git a/packages/connector/tencent-docs/src/index.ts b/packages/connector/tencent-docs/src/index.ts new file mode 100644 index 0000000000..6a340853fc --- /dev/null +++ b/packages/connector/tencent-docs/src/index.ts @@ -0,0 +1,68 @@ +/** + * Tencent Docs plugin: registers Tencent Docs' hosted MCP server with the + * shared MCP manager for this plugin's lifetime, tells the model to call it the + * Tencent Docs plugin, and shows the account on the Plugins page while the + * account registry runs. The manager owns connection, OAuth authorization, + * saved grants, and sign-out; once a grant exists, the server's + * `mcp__tencent-docs__*` tools are listed in the system prompt and each agent + * loads the ones it needs. + * @module @deepseek-ai/dsh-tencent-docs + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-mcp-account' +import type {} from '@deepseek-ai/dsh-mcp-manager' +import type {} from '@deepseek-ai/dsh-system-prompt' +import { COPY } from './locales.ts' + +export const name = 'tencent-docs' +export const inject = ['mcpManager', 'systemPrompt'] + +// One shared account per Host: a fixed server name keeps tool names stable and +// a fixed credential key lets a reinstalled plugin reuse its saved grant. +const SERVER_NAME = 'tencent-docs' +const CREDENTIAL_KEY = 'mcp-client/tencent-docs' +const GUIDANCE = 'Tools named `mcp__tencent-docs__*` come from the Tencent Docs plugin. In user-facing replies, call it the Tencent Docs plugin (腾讯文档插件 in Chinese), not MCP.' + + ' If no `mcp__tencent-docs__*` tool appears in your tool list, Tencent Docs is not connected yet; ask the user to connect it on the Tencent Docs plugin page in Plugins.' + +/** Tencent Docs MCP endpoint and tool loading for the managed server entry. */ +export interface Config { + /** Streamable HTTP MCP endpoint; defaults to Tencent Docs' hosted server. */ + url: string + /** `on-demand` (default) keeps Tencent Docs' tools hidden from each agent until it loads them; `eager` sends all of them. */ + toolLoading: 'eager' | 'on-demand' +} + +/* jscpd:ignore-start -- deliberate twin of dsh-notion and dsh-linear: the same MCP server and guidance registrations. */ +/** Runtime configuration schema for the Tencent Docs plugin. */ +export const Config: z, Config> = z.object({ + url: z.string().default('https://docs.qq.com/openapi/mcp'), + toolLoading: z.union(['eager', 'on-demand']).default('on-demand'), +}) + +/** + * Register the Tencent Docs server, its naming guidance, and, while the account registry runs, its Plugins page account; all + * are withdrawn when the plugin unloads. + * @param ctx - Context carrying the MCP manager and system prompt. + * @param config - Tencent Docs endpoint and tool loading. + * @throws when another configured or registered server already uses the `tencent-docs` name or credential key. + */ +export function apply(ctx: Context, config: Config): void { + ctx.mcpManager.register(SERVER_NAME, { + transport: 'streamable-http', + url: config.url, + oauth: { credentialKey: CREDENTIAL_KEY }, + toolLoading: config.toolLoading, + }) + // Sections at one order sort by name, so `tencent-docs` follows every `mcp…` server section. + ctx.systemPrompt.section({ + name: SERVER_NAME, + order: ctx.systemPrompt.getSectionOrder('MCP_SERVERS'), + text: GUIDANCE, + }) + ctx.inject(['mcpAccounts'], (scope) => { + scope.effect(() => scope.mcpAccounts.register({ server: SERVER_NAME, packageName: '@deepseek-ai/dsh-tencent-docs', copy: COPY }), 'tencent-docs: Plugins page account') + }) +} +/* jscpd:ignore-end */ diff --git a/packages/connector/tencent-docs/src/locales.ts b/packages/connector/tencent-docs/src/locales.ts new file mode 100644 index 0000000000..bfef4fd88f --- /dev/null +++ b/packages/connector/tencent-docs/src/locales.ts @@ -0,0 +1,167 @@ +/** The Plugins page text that names Tencent Docs; the shared account copy comes from the account surfaces' dictionary. */ +import type { McpAccountCopy } from '@deepseek-ai/dsh-mcp-account' + +/** Every language the Web app ships. */ +type ShippedText = Readonly> + +/** Tencent Docs' account text in every shipped language. */ +export const COPY: McpAccountCopy = { + title: { + zh: '腾讯文档账号', + en: 'Tencent Docs account', + ja: 'Tencent Docs アカウント', + es: 'Cuenta de Tencent Docs', + fr: 'Compte Tencent Docs', + de: 'Tencent Docs-Konto', + ru: 'Аккаунт Tencent Docs', + pt: 'Conta do Tencent Docs', + }, + connect: { + zh: '连接腾讯文档', + en: 'Connect Tencent Docs', + ja: 'Tencent Docs を接続', + es: 'Conectar Tencent Docs', + fr: 'Connecter Tencent Docs', + de: 'Tencent Docs verbinden', + ru: 'Подключить Tencent Docs', + pt: 'Conectar Tencent Docs', + }, + activation: { + title: { + zh: '连接腾讯文档账号', + en: 'Connect your Tencent Docs account', + ja: 'Tencent Docs アカウントを接続', + es: 'Conecte su cuenta de Tencent Docs', + fr: 'Connectez votre compte Tencent Docs', + de: 'Tencent Docs-Konto verbinden', + ru: 'Подключите аккаунт Tencent Docs', + pt: 'Conecte sua conta do Tencent Docs', + }, + body: { + zh: '腾讯文档插件已开启。连接你的腾讯文档账号后,就可以在对话中使用它。', + en: 'The Tencent Docs plugin is on. Connect your Tencent Docs account to use it in conversations.', + ja: 'Tencent Docs プラグインがオンになりました。Tencent Docs アカウントを接続すると、会話の中で使用できます。', + es: 'El complemento de Tencent Docs está activado. Conecte su cuenta de Tencent Docs para usarlo en las conversaciones.', + fr: 'Le plugin Tencent Docs est activé. Connectez votre compte Tencent Docs pour l’utiliser dans les conversations.', + de: 'Das Tencent Docs-Plugin ist aktiviert. Verbinden Sie Ihr Tencent Docs-Konto, um es in Unterhaltungen zu verwenden.', + ru: 'Плагин Tencent Docs включён. Подключите аккаунт Tencent Docs, чтобы использовать его в беседах.', + pt: 'O plugin do Tencent Docs está ativado. Conecte sua conta do Tencent Docs para usá-lo nas conversas.', + }, + }, + detail: { + disconnected: { + zh: '连接腾讯文档账号后,可以在对话中读取和编辑你有权限的腾讯文档。', + en: 'Connect your Tencent Docs account to read and edit the Tencent Docs you can access, right from a conversation.', + ja: 'Tencent Docs アカウントを接続すると、アクセス権のある Tencent Docs のドキュメントを会話の中から直接閲覧、編集できます。', + es: 'Conecte su cuenta de Tencent Docs para leer y editar los documentos de Tencent Docs a los que tiene acceso, directamente desde una conversación.', + fr: 'Connectez votre compte Tencent Docs pour lire et modifier les documents Tencent Docs auxquels vous avez accès, directement depuis une conversation.', + de: 'Verbinden Sie Ihr Tencent Docs-Konto, um Tencent Docs-Dokumente, auf die Sie Zugriff haben, direkt aus einer Unterhaltung heraus zu lesen und zu bearbeiten.', + ru: 'Подключите аккаунт Tencent Docs, чтобы читать и редактировать доступные вам документы Tencent Docs прямо из беседы.', + pt: 'Conecte sua conta do Tencent Docs para ler e editar os documentos do Tencent Docs aos quais você tem acesso, direto de uma conversa.', + }, + waitingBrowser: { + zh: '已打开腾讯文档授权页面。在腾讯文档中确认后,回到这里查看结果。', + en: 'The Tencent Docs authorization page is open. Confirm in Tencent Docs, then come back here to see the result.', + ja: 'Tencent Docs の認可ページを開きました。Tencent Docs で確定したら、ここに戻って結果を確認してください。', + es: 'La página de autorización de Tencent Docs está abierta. Confirme en Tencent Docs y luego vuelva aquí para ver el resultado.', + fr: 'La page d’autorisation Tencent Docs est ouverte. Confirmez dans Tencent Docs, puis revenez ici pour voir le résultat.', + de: 'Die Tencent Docs-Autorisierungsseite ist geöffnet. Bestätigen Sie in Tencent Docs und kehren Sie dann hierher zurück, um das Ergebnis zu sehen.', + ru: 'Страница авторизации Tencent Docs открыта. Подтвердите в Tencent Docs, затем вернитесь сюда, чтобы увидеть результат.', + pt: 'A página de autorização do Tencent Docs está aberta. Confirme no Tencent Docs e depois volte aqui para ver o resultado.', + }, + authorizing: { + zh: '正在与腾讯文档完成授权。', + en: 'Finishing authorization with Tencent Docs.', + ja: 'Tencent Docs での認可を完了しています。', + es: 'Completando la autorización con Tencent Docs.', + fr: 'Finalisation de l’autorisation avec Tencent Docs.', + de: 'Die Autorisierung mit Tencent Docs wird abgeschlossen.', + ru: 'Завершение авторизации в Tencent Docs.', + pt: 'Concluindo a autorização com o Tencent Docs.', + }, + connecting: { + zh: '正在连接腾讯文档。', + en: 'Connecting to Tencent Docs.', + ja: 'Tencent Docs に接続しています。', + es: 'Conectando con Tencent Docs.', + fr: 'Connexion à Tencent Docs en cours.', + de: 'Verbindung mit Tencent Docs wird hergestellt.', + ru: 'Подключение к Tencent Docs.', + pt: 'Conectando ao Tencent Docs.', + }, + connected: { + zh: '可以在对话中直接请 Agent 使用腾讯文档。', + en: 'Ask the agent to use Tencent Docs directly in a conversation.', + ja: '会話の中でエージェントに Tencent Docs の使用を直接依頼できます。', + es: 'Pida al agente que use Tencent Docs directamente en una conversación.', + fr: 'Demandez à l’agent d’utiliser Tencent Docs directement dans une conversation.', + de: 'Bitten Sie den Agenten, Tencent Docs direkt in einer Unterhaltung zu verwenden.', + ru: 'Попросите агента использовать Tencent Docs прямо в беседе.', + pt: 'Peça ao agente que use o Tencent Docs diretamente em uma conversa.', + }, + rejected: { + zh: '腾讯文档不再接受当前授权,请重新连接。', + en: 'Tencent Docs no longer accepts the current authorization. Connect again.', + ja: 'Tencent Docs は現在の認可を受け付けなくなりました。再度接続してください。', + es: 'Tencent Docs ya no acepta la autorización actual. Vuelva a conectar.', + fr: 'Tencent Docs n’accepte plus l’autorisation actuelle. Reconnectez-vous.', + de: 'Tencent Docs akzeptiert die aktuelle Autorisierung nicht mehr. Verbinden Sie erneut.', + ru: 'Tencent Docs больше не принимает текущую авторизацию. Подключитесь снова.', + pt: 'O Tencent Docs não aceita mais a autorização atual. Conecte novamente.', + }, + scope: { + zh: '当前授权缺少所需权限。重新连接时,请在腾讯文档中确认权限。', + en: 'The current authorization lacks required permissions. Confirm them in Tencent Docs when you connect again.', + ja: '現在の認可には必要な権限が不足しています。再度接続するときに、Tencent Docs で権限を確認してください。', + es: 'A la autorización actual le faltan permisos necesarios. Confírmelos en Tencent Docs cuando vuelva a conectar.', + fr: 'L’autorisation actuelle ne dispose pas des permissions requises. Confirmez-les dans Tencent Docs lors de la reconnexion.', + de: 'Der aktuellen Autorisierung fehlen erforderliche Berechtigungen. Bestätigen Sie diese in Tencent Docs, wenn Sie erneut verbinden.', + ru: 'Текущей авторизации не хватает нужных разрешений. Подтвердите их в Tencent Docs при повторном подключении.', + pt: 'A autorização atual não tem as permissões necessárias. Confirme-as no Tencent Docs ao conectar novamente.', + }, + }, + signOut: { + title: { + zh: '退出腾讯文档登录?', + en: 'Sign out of Tencent Docs?', + ja: 'Tencent Docs からサインアウトしますか?', + es: '¿Cerrar sesión en Tencent Docs?', + fr: 'Se déconnecter de Tencent Docs ?', + de: 'Von Tencent Docs abmelden?', + ru: 'Выйти из Tencent Docs?', + pt: 'Sair do Tencent Docs?', + }, + body: { + zh: '将删除 DSH 保存的腾讯文档授权,之后对话中无法使用腾讯文档。', + en: 'This deletes the Tencent Docs authorization DSH saved, so conversations can no longer use Tencent Docs.', + ja: 'DSH が保存した Tencent Docs の認可を削除します。以後、会話の中で Tencent Docs は使用できなくなります。', + es: 'Se eliminará la autorización de Tencent Docs que guardó DSH, por lo que las conversaciones ya no podrán usar Tencent Docs.', + fr: 'Cela supprime l’autorisation Tencent Docs enregistrée par DSH : les conversations ne pourront plus utiliser Tencent Docs.', + de: 'Dadurch wird die von DSH gespeicherte Tencent Docs-Autorisierung gelöscht, sodass Unterhaltungen Tencent Docs nicht mehr verwenden können.', + ru: 'Сохранённая DSH авторизация Tencent Docs будет удалена, и беседы больше не смогут использовать Tencent Docs.', + pt: 'Isso exclui a autorização do Tencent Docs salva pelo DSH, e as conversas não poderão mais usar o Tencent Docs.', + }, + }, + notice: { + connected: { + zh: '腾讯文档已连接', + en: 'Tencent Docs connected', + ja: 'Tencent Docs を接続しました', + es: 'Tencent Docs conectado', + fr: 'Tencent Docs connecté', + de: 'Tencent Docs verbunden', + ru: 'Tencent Docs подключён', + pt: 'Tencent Docs conectado', + }, + signedOut: { + zh: '已退出腾讯文档登录', + en: 'Signed out of Tencent Docs', + ja: 'Tencent Docs からサインアウトしました', + es: 'Sesión de Tencent Docs cerrada', + fr: 'Déconnecté de Tencent Docs', + de: 'Von Tencent Docs abgemeldet', + ru: 'Выполнен выход из Tencent Docs', + pt: 'Você saiu do Tencent Docs', + }, + }, +} diff --git a/packages/connector/tencent-docs/tests/plugin.spec.ts b/packages/connector/tencent-docs/tests/plugin.spec.ts new file mode 100644 index 0000000000..8c0f8a03e8 --- /dev/null +++ b/packages/connector/tencent-docs/tests/plugin.spec.ts @@ -0,0 +1,139 @@ +/** Tencent Docs plugin over a real MCP manager profile and a loopback OAuth MCP server. */ + +import { expect, it, vi } from 'vitest' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import ConnectorAccounts from '@deepseek-ai/dsh-client-ui-connector-account' +import type { ConnectorAccountsView } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import McpAccounts from '@deepseek-ai/dsh-mcp-account' +import { parseCredentialKey } from '@deepseek-ai/dsh-credentials' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import type { McpManagedServerStatus } from '@deepseek-ai/dsh-mcp-manager' +import McpResources from '@deepseek-ai/dsh-mcp-resources' +import { createScope } from '@deepseek-ai/dsh-scope' +import { renderPrompt } from '@deepseek-ai/dsh-system-prompt' +import { callback, oauthWorld, phase } from '../../../mcp/mcp-client/tests/oauth-fixture.ts' +import { managerProfile } from '../../../mcp/mcp-manager/tests/profile-fixture.ts' +import { COPY } from '../src/locales.ts' +import * as TencentDocs from '../src/index.ts' + +// Verbatim pin of the model-visible guidance in src/index.ts. +const GUIDANCE = 'Tools named `mcp__tencent-docs__*` come from the Tencent Docs plugin. In user-facing replies, call it the Tencent Docs plugin (腾讯文档插件 in Chinese), not MCP.' + + ' If no `mcp__tencent-docs__*` tool appears in your tool list, Tencent Docs is not connected yet; ask the user to connect it on the Tencent Docs plugin page in Plugins.' + +async function fixture(servers: Record = {}) { + const world = await oauthWorld() + await world.ctx.plugin(McpResources) + await managerProfile(world.ctx, { base: { servers } }) + const view = () => world.ctx.mcpManager.list().find(entry => entry.name === 'tencent-docs') + const state = async (expected: McpManagedServerStatus['state']) => { + await vi.waitFor(() => { expect(view()?.status.state).toBe(expected) }, { timeout: 5000 }) + } + const mount = (config: Partial = {}) => world.ctx.plugin(TencentDocs, { url: world.origin + '/mcp', ...config }) + const prompt = async () => renderPrompt(await world.ctx.systemPrompt.assemble()) + const ping = () => executeToolFixture(world.ctx, { + callId: ToolCallId('tencent-docs-ping'), name: 'mcp__tencent-docs__ping', arguments: {}, signal: new AbortController().signal, + }) + const grant = async () => (await world.ctx.credentials.describeRecord(parseCredentialKey('mcp-client/tencent-docs'))).configured + const agent = async (): Promise => { + const holder: { ctx?: Context } = {} + const created = holder as Agent + await world.ctx.plugin({ inject: ['tools'], apply(inner: Context) { holder.ctx = createScope(inner, created).ctx } }) + await world.ctx.serial('agent/created', { agent: created, source: 'startup' }) + return created + } + const authorize = async () => { + await world.ctx.mcpManager.startAuthorization('tencent-docs') + expect(await callback(await phase(() => view()?.authorization, 'waiting-browser'))).toBe(200) + await state('connected') + } + return { ...world, view, state, mount, prompt, ping, grant, agent, authorize } +} + +it('defaults to the hosted Tencent Docs endpoint', () => { + expect(TencentDocs.Config({})).toEqual({ url: 'https://docs.qq.com/openapi/mcp', toolLoading: 'on-demand' }) +}) + +it('registers Tencent Docs for the plugin lifetime and reuses the saved grant after reloading', async () => { + const b = await fixture() + // Eager tools register for the Host, so the test calls them without an agent. + const first = b.mount({ toolLoading: 'eager' }) + await first.await() + await b.state('waiting-authorization') + expect(b.view()?.status).toMatchObject({ reason: 'missing' }) + expect(await b.prompt()).toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + + await b.authorize() + expect(await b.ping()).toMatchObject({ isError: false }) + + await first.dispose() + expect(b.view()).toBeUndefined() + expect(await b.prompt()).not.toContain(GUIDANCE) + expect(await b.ping()).toMatchObject({ isError: true }) + expect(await b.grant()).toBe(true) + + const tokens = b.tokens() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(await b.ping()).toMatchObject({ isError: false }) + expect(b.view()?.authorization).toBeUndefined() + expect(b.tokens()).toBe(tokens) + expect(b.registrations()).toBe(1) +}) + +it('keeps Tencent Docs tools hidden from an agent until it loads them, unless loading is eager', async () => { + const b = await fixture() + const agent = await b.agent() + const onDemand = b.mount() + await onDemand.await() + await b.authorize() + expect(b.ctx.tools.get('mcp__tencent-docs__ping', agent)).toBeUndefined() + expect(b.ctx.tools.get('mcp__tencent-docs__load_tools', agent)).toBeDefined() + expect(await executeToolFixture(b.ctx, { + callId: ToolCallId('tencent-docs-load'), name: 'mcp__tencent-docs__load_tools', arguments: { tools: ['ping'] }, + signal: new AbortController().signal, agent, + })).toMatchObject({ isError: false, value: 'Loaded: mcp__tencent-docs__ping.' }) + expect(b.ctx.tools.get('mcp__tencent-docs__ping', agent)).toBeDefined() + + await onDemand.dispose() + const other = await b.agent() + await b.mount({ toolLoading: 'eager' }).await() + await b.state('connected') + expect(b.ctx.tools.get('mcp__tencent-docs__ping', other)).toBeDefined() +}) + +/** Read the account stream until a view satisfies the predicate. */ +async function until( + stream: AsyncIterator, predicate: (view: ConnectorAccountsView) => boolean, +): Promise { + for (;;) { + const next = await stream.next() + if (next.done === true) throw new Error('account stream ended') + if (predicate(next.value)) return next.value + } +} + +it('shows the Tencent Docs account on the Plugins page while the account registry runs, and withdraws it with the plugin', async () => { + const b = await fixture() + await b.ctx.plugin(ConnectorAccounts) + await b.ctx.plugin(McpAccounts) + const stream = b.ctx.connectorAccounts.watch(new AbortController().signal)[Symbol.asyncIterator]() + const plugin = b.mount() + await plugin.await() + const shown = await until(stream, view => view.accounts[0]?.display.phase === 'disconnected') + expect(shown.accounts).toHaveLength(1) + expect(shown.accounts[0]).toMatchObject({ + key: 'mcp:tencent-docs', packageName: '@deepseek-ai/dsh-tencent-docs', + copy: { title: COPY.title, activation: { connect: COPY.connect } }, display: { phase: 'disconnected' }, + }) + await plugin.dispose() + await until(stream, view => view.accounts.length === 0) +}) + +it('refuses to load when a configured server already uses the Tencent Docs name', async () => { + const b = await fixture({ 'tencent-docs': { transport: 'streamable-http', url: 'https://docs.example/mcp', enabled: false } }) + await expect(b.mount().await()).rejects.toThrow('server "tencent-docs" is already configured or registered') + expect(await b.prompt()).not.toContain(GUIDANCE) +}) diff --git a/packages/connector/tencent-docs/tsconfig.json b/packages/connector/tencent-docs/tsconfig.json new file mode 100644 index 0000000000..64cc75ae5b --- /dev/null +++ b/packages/connector/tencent-docs/tsconfig.json @@ -0,0 +1,27 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../mcp/mcp-manager" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../mcp/mcp-account" + } + ] +} diff --git a/packages/connector/tencent-meeting/README.i18n.yaml b/packages/connector/tencent-meeting/README.i18n.yaml new file mode 100644 index 0000000000..2e8f47ff6c --- /dev/null +++ b/packages/connector/tencent-meeting/README.i18n.yaml @@ -0,0 +1,88 @@ +# 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/connector/tencent-meeting/README.md +/: + en: bf058142ad507655 + zh: af4c666af23c6049 +/deepseek-ai-dsh-tencent-meeting: + en: 8d9bc7c10be0189e + zh: df97cf0f74495ad0 +/deepseek-ai-dsh-tencent-meeting/summary: + en: 80e6bcc0f9ec8cdb + zh: 961d98f659e9f054 +/deepseek-ai-dsh-tencent-meeting/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-tencent-meeting/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-tencent-meeting/use-this-package/install-into-a-profile: + en: a33500f6c577f008 + zh: cedbc1c5cdb8bfc6 +/deepseek-ai-dsh-tencent-meeting/use-this-package/what-you-get: + en: 70a1d52b6c0f80af + zh: a3894b2233b5985d +/deepseek-ai-dsh-tencent-meeting/use-this-package/account-operations: + en: ad18981ffd47798a + zh: 1f30d2349a2dd447 +/deepseek-ai-dsh-tencent-meeting/use-this-package/configure: + en: 1730401daedf703e + zh: 5cd9e0bc2699efe8 +/deepseek-ai-dsh-tencent-meeting/understand-the-implementation: + en: 8e10bf200eca551e + zh: 1044452f3c12d584 +/deepseek-ai-dsh-tencent-meeting/further-exploration: + en: a37fc14df39c8a77 + zh: 0f0e795c5f1f9657 +/deepseek-ai-dsh-tencent-meeting/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-tencent-meeting/model-experience/skill-catalog-entries: + en: 7265024b55daf9ef + zh: e99e8d5639c268d9 +/deepseek-ai-dsh-tencent-meeting/model-experience/skill-catalog-entries/what-the-model-sees: + en: 0d7bcb60f6e1a5f8 + zh: b3c39188054f6996 +/deepseek-ai-dsh-tencent-meeting/model-experience/skill-catalog-entries/token-effect: + en: 3fac42fb005f9e2d + zh: 540493014daf3e28 +/deepseek-ai-dsh-tencent-meeting/model-experience/skill-catalog-entries/kv-cache-effect: + en: ce9139edf3309f2b + zh: 23a4744d4d530172 +/deepseek-ai-dsh-tencent-meeting/model-experience/loaded-skill-body: + en: 8955ac196848e69f + zh: 698bcd0773a8f094 +/deepseek-ai-dsh-tencent-meeting/model-experience/loaded-skill-body/what-the-model-sees: + en: d1671b06d763895e + zh: c267463e85e4cfad +/deepseek-ai-dsh-tencent-meeting/model-experience/loaded-skill-body/token-effect: + en: 374e05c93f33526c + zh: 3e36d6182358bb55 +/deepseek-ai-dsh-tencent-meeting/model-experience/loaded-skill-body/kv-cache-effect: + en: 1f6b842a95e14ce4 + zh: d32b51405eabddc4 +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path: + en: b5fed52af6c0d771 + zh: 25b7aa5297583030 +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/what-the-model-sees: + en: 3ffc81ce5500c85c + zh: 28425cf9445d0f8d +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/what-the-model-sees/runtime-context-entry: + en: c91314832f78f460 + zh: aac156ea0b5b816a +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/what-the-model-sees/runtime-context-entry-on-windows: + en: 54f899bbaf7ed198 + zh: 31256473a192427b +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/token-effect: + en: 3fb1f01010d97c7d + zh: c0aa6fb57ceadf95 +/deepseek-ai-dsh-tencent-meeting/model-experience/cli-path/kv-cache-effect: + en: 67398dd4e4b02db9 + zh: a873eacd006fa656 +/deepseek-ai-dsh-tencent-meeting/known-limitations-and-deferred-work: + en: ae40715bad4af72b + zh: fc099653415779c3 +/deepseek-ai-dsh-tencent-meeting/known-limitations-and-deferred-work/dev-note: + en: d67cf464f2df6693 + zh: ff08f0d56a5ea79d diff --git a/packages/connector/tencent-meeting/README.md b/packages/connector/tencent-meeting/README.md new file mode 100644 index 0000000000..3f821c313c --- /dev/null +++ b/packages/connector/tencent-meeting/README.md @@ -0,0 +1,177 @@ +--- +description: "Add the Tencent Meeting plugin to a profile: the official tmeet with its skill, and Tencent Meeting sign-in on the Plugins page." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-tencent-meeting + +English | [中文](README.zh.md) + +## Summary + +The Tencent Meeting plugin lets conversations use Tencent Meeting through the official `tmeet` CLI. It installs a pinned `@tencentcloud/tmeet`, gives the model the absolute path of its platform executable in runtime context, and registers one `tencent-meeting` skill whose guide is the official `tmeet-skill`, downloaded from the CLI's GitHub repository. It registers the account with the [connector account registry](../../client/ui-connector-account/README.md), whose Plugins page section checks the sign-in, signs in through the CLI's authorization page, signs out, and cancels. The CLI keeps the sign-in in its default configuration, which the user's own terminal shares. Only macOS and Windows x64 are supported. + +## 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 + +### Install into a profile + +Install the plugin from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-tencent-meeting +dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting +``` + +`@tencentcloud/tmeet` declares an install script, so the first installation stops with `@tencentcloud/tmeet` among the pending build scripts. On the Plugins page, select **Allow these scripts and retry**; with the CLI, set `allowBuilds` for it to `true` in the profile's `pnpm-workspace.yaml` and run the command again. The script makes the packaged executable executable and runs `tmeet auth logout`, which signs out tmeet on this computer, including the user's own terminal. The approval stays in the profile, so each later installation of a new `@tencentcloud/tmeet` version runs the script and signs out again; sign in again on the plugin page afterwards. When the package has no executable for the computer's platform, or the executable is missing, the plugin fails to load with an error that names the platform or path. + +### What you get + +After the plugin loads, one `tencent-meeting` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the `tmeet-skill` guide and its references with the file tools, and runs `tmeet` by that path through the ordinary Shell tools under the current sandbox and approval policy. When a command reports a missing or expired sign-in, the agent asks the user to connect Tencent Meeting on the plugin page; it runs `tmeet auth login --no-browser` only when the user asks to finish it in the conversation, and requests `sandbox_permissions` with a `justification` on the first attempt because the command writes outside the workspace. + +The guide comes from `skills/tmeet-skill/` of `TencentCloud/tencentmeeting-cli` at tag `v1.0.18` (commit `e631b35`), without `scripts/agent_init.py`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/tencent-meeting/`; until they are in place, the catalog has no `tencent-meeting` skill and the plugin page reports the download. A failed download is retried by the page's check. + +Turning the plugin off in Plugin Manager withdraws the skill, the path from runtime context, and the account section. The CLI sign-in and the downloaded guide stay in place. + + +### Account operations + +The Plugins page drives these operations through the connector account registry, which the Web app loads; a headless profile loads the plugin without it. The Host runs at most one operation at a time and owns it, so leaving the page does not cancel it. + +| Operation | Effect | +|---|---| +| `check` | Checks the account again; each browser that opens the Web app starts one when no operation runs | +| `sign-in` | Runs `auth login --no-browser`, waits for the user to authorize on the Tencent Meeting page, then checks that the server accepts the new sign-in | +| `sign-out` | After the user confirms, runs `auth logout`, which also signs out the user's own terminal, then checks again | +| Cancel | Cancels a sign-in while it waits for authorization and waits for its command to exit; other steps are ignored | + +A check runs `auth status`, which in tmeet 1.0.18 prints plain text and exits with code 0 whether or not a user is signed in. The account reads `signed-out` for `Not logged in.`, for `Session has expired.`, or when `Logged in` comes with an expired refresh token; `connected`, with the user name, when `Logged in` comes with a `UserName:` line, which the CLI prints only after its user-info request to the server succeeds; and `unverified` for any other `Logged in`, for example when that request cannot reach the server. A nonzero exit or other output fails the check and keeps the previous account. The link that `auth login` prints on its `authorize url:` stdout line is offered only when it is an HTTPS address on `meeting.tencent.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the one-time authorization code, is omitted. The process running DSH needs access to the CLI configuration in `~/.tmeet`, the encrypted credentials in `~/Library/Application Support/tmeet`, and the macOS Keychain item that holds their key; `DSH_HOME` does not relocate them. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `binDir` | unset, which runs the installed `@tencentcloud/tmeet` executable for this platform | Absolute directory containing an executable `tmeet`, `tmeet.exe` on Windows | +| `skillsDir` | none | Directory holding the files of `skills/tmeet-skill/` at their repository paths; when set, the guide is not downloaded | + +An account check or sign-out gets the `commandTimeoutMs` of the [`cli-account` row](../cli-account/README.md#use-this-package), 30 seconds by default. Sign-in waits up to 10 minutes for the user, and each command keeps at most 1 MiB of stdout; the CLI account Service fixes both limits. tmeet itself stops waiting for authorization after 5 minutes. The guide is downloaded from the `skillsUrls` of the [`upstream-skills` row](../upstream-skills/README.md#use-this-package), each within its `skillsTimeoutMs`. + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-tencent-meeting) is the exhaustive source of supported fields. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `tencent-meeting` row after the profile's other layers, and the Plugins page keys the account section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It resolves the `tmeet` executable, registers the `tencent-meeting` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the account with `ctx.cliAccounts`. The account view carries the download state, and each check restarts a failed download without waiting for it. `@tencentcloud/tmeet` ships one executable per platform under `dist/`, each named for its platform, and its `bin` is a Node launcher. [`src/directory.ts`](src/directory.ts) therefore picks the executable for `process.platform` and `process.arch` with the same names the launcher uses, and both the runtime context and the plugin's own commands use that path. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the tmeet commands, reads the authorization link from the output lines of `auth login`, and parses the `auth status` text. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. + +[`skills/tencent-meeting/SKILL.md`](skills/tencent-meeting/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the guide, and how to open it. Upstream publishes the guide only in its repository and not in the npm package, so the [upstream skills Service](../upstream-skills/README.md) downloads it; it is a set of files under the skill's base directory, not a separate skill. The pin excludes `scripts/agent_init.py`, which records the calling agent and model in the CLI configuration for upstream telemetry. Where the DSH guidance and the guide disagree, the entry tells the agent to follow the DSH guidance: it uses the plugin's `tmeet` instead of installing one, skips `agent_init.py`, and sends sign-in to the plugin page. References are ordinary files in the guide's directory. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [CLI account Service](../cli-account/README.md) — command execution, the CLI path context, and account operations shared by CLI app plugins. +- [Upstream skills Service](../upstream-skills/README.md) — download, verification, and publication of the guide. +- [Skills](../../../docs/subsystems/skills.md) — catalog publication, loading, and precedence. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the registry and the Plugins page section that drive the account operations. + +----- + + +## Model Experience + +### Skill catalog entries + +#### What the model sees + +The skill catalog lists one `tencent-meeting` skill. Its Chinese description names the Tencent Meeting features it covers and tells the agent to load it, then read the `tmeet-skill` guide, whenever the user mentions Tencent Meeting, a meeting code, or meeting recordings or minutes. + +#### Token effect + +The entry stays in context while the plugin is loaded. Its name and description total about 130 characters. + +#### KV Cache effect + +The catalog is fixed for one plugin version. Loading or unloading the plugin changes the catalog, which is republished as a new message and leaves earlier context in place. + +### Loaded skill body + +#### What the model sees + +A `skill` tool result for `tencent-meeting` contains about 1,200 characters: the DSH guidance, a one-sentence index of the `tmeet-skill` guide, and how to open it. The DSH guidance tells the agent to run the plugin's `tmeet` by the absolute path from the current runtime context, to skip the guide's installation check and its `agent_init.py` step, to ask the user to connect on the plugin page before running `tmeet auth login --no-browser` itself, and to request `sandbox_permissions` for that command from its first attempt; it takes precedence over the guide where they disagree. Its resource base is the downloaded directory, `skillsDir` or `$DSH_HOME/cache/tencent-meeting/skills-`, so the agent opens `skills/tmeet-skill/SKILL.md` with the file tools rather than the `skill` tool and resolves the guide's relative paths against the guide's own directory. + +#### Token effect + +Each load adds the entry body to the retained tool history. The guide, about 18,000 characters, and its reference files arrive as ordinary file-read output. + +#### KV Cache effect + +Loading appends a tool result and does not rewrite earlier context. + +### CLI path + +#### What the model sees + +While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of the executable: `tmeet` in `binDir`, or by default the installed `@tencentcloud/tmeet` executable for this platform, such as `dist/tmeet-macOS-AppleSilicon`. + +##### Runtime-context entry + +```markdown +Tencent Meeting CLI: run `tmeet` by its absolute path ""; the bare name may resolve to another installation or to none. +``` + +##### Runtime-context entry on Windows + +```markdown +Tencent Meeting CLI: run `tmeet` by its absolute path with the call operator, & ''; the bare name may resolve to another installation or to none. +``` + +#### Token effect + +One line of about 115 characters plus the path in each runtime-context snapshot. + +#### KV Cache effect + +The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. + +## Known Limitations and Deferred Work + + + +- Only macOS and Windows x64 are supported; Linux is unverified. `@tencentcloud/tmeet` ships no Windows arm64 executable. +- Installing a new `@tencentcloud/tmeet` version signs out tmeet on this computer, because its approved install script runs `tmeet auth logout`. +- Commands must run on this Host. When a composition runs them elsewhere, such as over SSH, the plugin still loads, and each command that runs `tmeet` fails because the path does not exist there. +- The plugin uses the CLI's default configuration. Signing in or out from DSH affects the user's own terminal, and there is no DSH-private account or account picker. +- The account state comes from the plain-text output of tmeet 1.0.18's `auth status`, and the sign-in link from its `authorize url:` line; a CLI version that changes that text fails the check or the sign-in with a retryable result. An account for which the server returns no user name reads as unconfirmed. +- The guide follows upstream tag `v1.0.18`; updating it means a new pin from `scripts/upstream-skills-digest.ts`, after which the entry's index and DSH guidance must be checked against the new guide. +- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has no `tencent-meeting` skill. +- The downloaded guide stays in `$DSH_HOME/cache/tencent-meeting/` after the plugin is removed or pins another commit. + + +### Dev Note + +
+Working context for maintainers — click to expand + +Specs, the `tencent-meeting-skills` session snapshot, and the Web e2e use stand-in executables through `binDir` and local directories through `skillsDir`, so none of them downloads the guide. + +
diff --git a/packages/connector/tencent-meeting/README.zh.md b/packages/connector/tencent-meeting/README.zh.md new file mode 100644 index 0000000000..ffeb37ea54 --- /dev/null +++ b/packages/connector/tencent-meeting/README.zh.md @@ -0,0 +1,177 @@ +--- +description: "把腾讯会议插件加入 profile:官方 tmeet 及其技能,以及插件页上的腾讯会议登录。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-tencent-meeting + +[English](README.md) | 中文 + +## 概述 + +腾讯会议插件让对话通过官方 `tmeet` CLI 使用腾讯会议。它安装固定版本的 `@tencentcloud/tmeet`,在运行时上下文中把其平台可执行文件的绝对路径告诉模型,并注册一个 `tencent-meeting` skill,其子指南是官方 `tmeet-skill`,从该 CLI 的 GitHub 仓库下载。它把账号注册到 [连接器账号注册表](../../client/ui-connector-account/README.zh.md),其插件页区块负责检查登录、通过 CLI 的授权页面登录、退出登录和取消操作。CLI 把登录保存在默认配置中,与用户自己的终端共用。仅支持 macOS 和 Windows x64。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +在 Web 侧栏的 **插件** 页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-tencent-meeting +dsh plugin --profile web remove @deepseek-ai/dsh-tencent-meeting +``` + +`@tencentcloud/tmeet` 声明了安装脚本,因此第一次安装会停下来,待处理的构建脚本中列出 `@tencentcloud/tmeet`。在插件页面选择 **允许这些脚本并重试**;使用 CLI 时,在 profile 的 `pnpm-workspace.yaml` 中把它的 `allowBuilds` 设为 `true`,然后重新运行命令。该脚本会把包里的可执行文件设为可执行,并运行 `tmeet auth logout`,这会退出这台电脑上 tmeet 的登录,包括用户自己的终端。这项允许会保留在 profile 中,因此之后每次安装新版本的 `@tencentcloud/tmeet` 都会运行该脚本并再次退出登录;之后在插件页面重新登录即可。包里没有当前平台的可执行文件,或可执行文件缺失时,插件加载会失败,错误信息会给出平台或路径。 + +### 你会得到 + +插件加载后,技能目录中会多一个 `tencent-meeting` skill。Agent 用 `skill` 工具加载它,用文件工具打开 `tmeet-skill` 子指南及其参考文件,并在当前沙箱和审批策略下通过普通 Shell 工具按这个路径运行 `tmeet`。命令报告未登录或登录过期时,Agent 会请用户在插件页面连接腾讯会议;只有用户要求在对话中完成时,它才运行 `tmeet auth login --no-browser`,并且因为该命令会写入工作区之外,第一次尝试就带 `justification` 申请 `sandbox_permissions`。 + +子指南来自 `TencentCloud/tencentmeeting-cli` 标签 `v1.0.18`(提交 `e631b35`)中的 `skills/tmeet-skill/`,不含 `scripts/agent_init.py`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/tencent-meeting/`;文件就位之前,skill 目录中没有 `tencent-meeting` skill,插件页会报告下载状态。下载失败时,由插件页的检查重试。 + +在 Plugin Manager 中关闭插件会撤下这个 skill、运行时上下文中的路径和账号区块。CLI 的登录和已下载的子指南会保留。 + + +### 账号操作 + +插件页通过 连接器账号注册表发起这些操作,注册表由 Web 应用加载;headless profile 加载插件时没有它。Host 同一时间最多运行一个操作并持有它,因此离开页面不会取消它。 + +| 操作 | 效果 | +|---|---| +| `check` | 重新检查账号;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `sign-in` | 运行 `auth login --no-browser`,等待用户在腾讯会议页面授权,然后检查服务端是否接受新的登录 | +| `sign-out` | 用户确认后运行 `auth logout`,这也会退出用户自己终端里的登录,然后重新检查 | +| 取消 | 在登录等待授权时取消它,并等待其命令退出;其他步骤会被忽略 | + +检查运行 `auth status`。在 tmeet 1.0.18 中,它只输出纯文本,无论是否有用户登录,退出码都是 0。输出 `Not logged in.` 或 `Session has expired.`,或 `Logged in` 伴随已过期的 refresh token 时,账号为 `signed-out`;`Logged in` 伴随 `UserName:` 行时为 `connected` 并带用户名,CLI 只有在向服务端请求用户信息成功后才会打印这一行;其他 `Logged in` 为 `unverified`,例如该请求连不上服务端。退出码非零或其他输出会使检查失败,并保留之前的账号状态。`auth login` 在 stdout 的 `authorize url:` 行打印的链接,只有是 `meeting.tencent.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有一次性授权码,因此会被省略。运行 DSH 的进程需要能访问 `~/.tmeet` 中的 CLI 配置、`~/Library/Application Support/tmeet` 中的加密凭据,以及保存其密钥的 macOS 钥匙串项;`DSH_HOME` 不会改变它们的位置。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `binDir` | 不设置,此时运行当前平台已安装的 `@tencentcloud/tmeet` 可执行文件 | 包含可执行 `tmeet`(Windows 上为 `tmeet.exe`)的绝对目录 | +| `skillsDir` | 无 | 按仓库路径存放 `skills/tmeet-skill/` 文件的目录;设置后不下载子指南 | + +账号检查和退出登录使用 [`cli-account` 行](../cli-account/README.zh.md#use-this-package)的 `commandTimeoutMs`,默认 30 秒。登录最多等待用户 10 分钟,每条命令最多保留 1 MiB stdout;这两个上限由 CLI 账号 Service 固定。tmeet 自身在 5 分钟后停止等待授权。子指南从 [`upstream-skills` 行](../upstream-skills/README.zh.md#use-this-package)的 `skillsUrls` 下载,每个前缀的时限是该行的 `skillsTimeoutMs`。 + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-tencent-meeting)是受支持字段的完整来源。 + +----- + + +## 理解实现 + +
+实现细节 — 点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `tencent-meeting` 行插入,插件页以本包名作为账号区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它解析 `tmeet` 可执行文件,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `tencent-meeting` skill 注册到 `ctx.upstreamSkills`,并把这个路径和账号注册到 `ctx.cliAccounts`。账号视图携带下载状态,每次检查都会在不等待的情况下重新开始失败的下载。`@tencentcloud/tmeet` 在 `dist/` 下为每个平台提供一个按平台命名的可执行文件,其 `bin` 是一个 Node 启动器。因此 [`src/directory.ts`](src/directory.ts) 按 `process.platform` 和 `process.arch`,用与该启动器相同的文件名选出可执行文件,运行时上下文和插件自己的命令都使用这个路径。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,同一时间只运行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用 tmeet 命令完成每个操作,从 `auth login` 的输出行读取授权链接,并解析 `auth status` 的文本。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时会取消进行中的操作、中止正在运行的命令,并在其进程退出后结束。 + +[`skills/tencent-meeting/SKILL.md`](skills/tencent-meeting/SKILL.md) 是本包携带的唯一 skill:DSH 指引、子指南索引,以及打开子指南的方式。上游只在其仓库中发布这个子指南,npm 包里没有,因此由[上游技能 Service](../upstream-skills/README.zh.md) 下载;它是 skill 基础目录下的一组文件,不是独立的 skill。固定信息排除了 `scripts/agent_init.py`,它用于把调用方 Agent 和模型记录到 CLI 配置中供上游统计。DSH 指引与子指南不一致时,入口要求 Agent 以 DSH 指引为准:使用插件提供的 `tmeet` 而不是自行安装,跳过 `agent_init.py`,并把登录交给插件页面。参考文件是子指南目录中的普通文件。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md) — 本应用插件所属的分组。 +- [CLI 账号 Service](../cli-account/README.zh.md) — CLI 应用插件共用的命令执行、CLI 路径上下文与账号操作。 +- [上游技能 Service](../upstream-skills/README.zh.md) — 子指南的下载、校验与发布。 +- [Skills](../../../docs/subsystems/skills.zh.md) — 目录发布、加载与优先级。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md) — 发起账号操作的注册表和插件页区块。 + +----- + + +## 模型体验 + +### 技能目录条目 + +#### 模型看到的内容 + +技能目录列出一个 `tencent-meeting` skill。它的中文描述列出涵盖的腾讯会议功能,并要求 Agent 在用户提到腾讯会议、会议号、会议录制或纪要时先加载它,再读取 `tmeet-skill` 子指南。 + +#### Token 影响 + +插件加载期间,该条目一直留在上下文中。名称和描述合计约 130 个字符。 + +#### KV Cache 影响 + +同一插件版本的目录是固定的。加载或卸载插件会改变目录,目录会作为新消息重新发布,之前的上下文保持不变。 + +### 加载后的技能正文 + +#### 模型看到的内容 + +`tencent-meeting` 的 `skill` 工具结果约 1,200 个字符:DSH 指引、一句话的 `tmeet-skill` 子指南索引,以及打开方式。DSH 指引要求 Agent 按当前运行时上下文给出的绝对路径运行插件提供的 `tmeet`,跳过子指南的安装检查和 `agent_init.py` 步骤,在自己运行 `tmeet auth login --no-browser` 之前先请用户在插件页面连接,并在该命令第一次尝试时就申请 `sandbox_permissions`;两者不一致时以 DSH 指引为准。它的资源目录是下载目录,即 `skillsDir` 或 `$DSH_HOME/cache/tencent-meeting/skills-<摘要>`,因此 Agent 用文件工具而不是 `skill` 工具打开 `skills/tmeet-skill/SKILL.md`,并以子指南自己的目录解析其中的相对路径。 + +#### Token 影响 + +每次加载都会把入口正文加入保留的工具历史。子指南约 18,000 个字符,它和参考文件都以普通的文件读取输出进入上下文。 + +#### KV Cache 影响 + +加载会追加一条工具结果,不会改写之前的上下文。 + +### CLI 路径 + +#### 模型看到的内容 + +该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出可执行文件的路径:`binDir` 中的 `tmeet`,或者默认使用当前平台已安装的 `@tencentcloud/tmeet` 可执行文件,例如 `dist/tmeet-macOS-AppleSilicon`。 + +##### 运行时上下文条目 + +```markdown +Tencent Meeting CLI: run `tmeet` by its absolute path ""; the bare name may resolve to another installation or to none. +``` + +##### Windows 上的运行时上下文条目 + +```markdown +Tencent Meeting CLI: run `tmeet` by its absolute path with the call operator, & ''; the bare name may resolve to another installation or to none. +``` + +#### Token 影响 + +每份运行时上下文快照中一行,约 115 个字符加上路径。 + +#### KV Cache 影响 + +系统提示词不变;加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 + +## 已知限制与延期工作 + + + +- 仅支持 macOS 和 Windows x64;Linux 未经验证。`@tencentcloud/tmeet` 没有 Windows arm64 可执行文件。 +- 安装新版本的 `@tencentcloud/tmeet` 会退出这台电脑上 tmeet 的登录,因为已允许的安装脚本会运行 `tmeet auth logout`。 +- 命令必须在本 Host 上运行。组合把命令放到别处运行(例如通过 SSH)时,插件仍会加载,但每条运行 `tmeet` 的命令都会因为那里没有这个路径而失败。 +- 插件使用 CLI 的默认配置。在 DSH 中登录或退出登录会影响用户自己的终端,没有 DSH 专用的账号,也没有账号选择。 +- 账号状态来自 tmeet 1.0.18 `auth status` 的纯文本输出,登录链接来自它的 `authorize url:` 行;改变这些文本的 CLI 版本会使检查或登录失败,并给出可重试的结果。服务端没有返回用户名的账号会显示为待确认。 +- 子指南对应上游标签 `v1.0.18`;更新它要用 `scripts/upstream-skills-digest.ts` 生成新的固定信息,之后对照新的子指南检查入口的索引和 DSH 指引。 +- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,Agent 没有 `tencent-meeting` skill。 +- 插件卸载或改为固定其他提交后,已下载的子指南仍留在 `$DSH_HOME/cache/tencent-meeting/`。 + + +### 开发备注 + +
+维护者工作上下文 — 点击展开 + +单元测试、`tencent-meeting-skills` 会话快照和 Web 端到端测试通过 `binDir` 使用替身可执行文件,通过 `skillsDir` 使用本地目录,因此都不会下载子指南。 + +
diff --git a/packages/connector/tencent-meeting/cordis.patch.yml b/packages/connector/tencent-meeting/cordis.patch.yml new file mode 100644 index 0000000000..24eedb603e --- /dev/null +++ b/packages/connector/tencent-meeting/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: tencent-meeting + name: '@deepseek-ai/dsh-tencent-meeting' diff --git a/packages/connector/tencent-meeting/docs/DETAIL.md b/packages/connector/tencent-meeting/docs/DETAIL.md new file mode 100644 index 0000000000..4f457ba849 --- /dev/null +++ b/packages/connector/tencent-meeting/docs/DETAIL.md @@ -0,0 +1 @@ +![The connected Tencent Meeting account on the plugin page and a conversation that schedules a meeting](preview.svg) diff --git a/packages/connector/tencent-meeting/docs/DETAIL.zh.md b/packages/connector/tencent-meeting/docs/DETAIL.zh.md new file mode 100644 index 0000000000..61272af0ef --- /dev/null +++ b/packages/connector/tencent-meeting/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已连接的腾讯会议账号,以及在对话中预定一场腾讯会议](preview.zh.svg) diff --git a/packages/connector/tencent-meeting/docs/preview.svg b/packages/connector/tencent-meeting/docs/preview.svg new file mode 100644 index 0000000000..0941208e50 --- /dev/null +++ b/packages/connector/tencent-meeting/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/tencent-meeting/docs/preview.zh.svg b/packages/connector/tencent-meeting/docs/preview.zh.svg new file mode 100644 index 0000000000..ab32da6b89 --- /dev/null +++ b/packages/connector/tencent-meeting/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/tencent-meeting/icon.svg b/packages/connector/tencent-meeting/icon.svg new file mode 100644 index 0000000000..a3e3c0e6ef --- /dev/null +++ b/packages/connector/tencent-meeting/icon.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/packages/connector/tencent-meeting/locale/de.json b/packages/connector/tencent-meeting/locale/de.json new file mode 100644 index 0000000000..5c7e527ff8 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Meeting-Plugin", + "description": "Verwenden Sie Besprechungen, Aufzeichnungen, Protokolle und Besprechungsberichte von Tencent Meeting in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/en.json b/packages/connector/tencent-meeting/locale/en.json new file mode 100644 index 0000000000..a29594c2c9 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Meeting plugin", + "description": "Use Tencent Meeting meetings, recordings, minutes, and meeting reports in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/es.json b/packages/connector/tencent-meeting/locale/es.json new file mode 100644 index 0000000000..c740c6bc47 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de Tencent Meeting", + "description": "Use las reuniones, grabaciones, actas e informes de reuniones de Tencent Meeting en las conversaciones.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/fr.json b/packages/connector/tencent-meeting/locale/fr.json new file mode 100644 index 0000000000..36fdd9d561 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin Tencent Meeting", + "description": "Utilisez les réunions, les enregistrements, les comptes rendus et les rapports de réunion de Tencent Meeting dans les conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/ja.json b/packages/connector/tencent-meeting/locale/ja.json new file mode 100644 index 0000000000..c2ff1e4c30 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Tencent Meeting プラグイン", + "description": "会話の中で Tencent Meeting の会議、録画、議事録、会議レポートを使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/pt.json b/packages/connector/tencent-meeting/locale/pt.json new file mode 100644 index 0000000000..dc8c2ec916 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do Tencent Meeting", + "description": "Use reuniões, gravações, atas e relatórios de reunião do Tencent Meeting nas conversas.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/ru.json b/packages/connector/tencent-meeting/locale/ru.json new file mode 100644 index 0000000000..027b1b511d --- /dev/null +++ b/packages/connector/tencent-meeting/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин Tencent Meeting", + "description": "Используйте встречи, записи, протоколы и отчёты о встречах Tencent Meeting в беседах.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/tencent-meeting/locale/zh.json b/packages/connector/tencent-meeting/locale/zh.json new file mode 100644 index 0000000000..7ca9fcbce7 --- /dev/null +++ b/packages/connector/tencent-meeting/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "腾讯会议插件", + "description": "在对话中使用腾讯会议的会议、录制、纪要和会议报告。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/tencent-meeting/package.json b/packages/connector/tencent-meeting/package.json new file mode 100644 index 0000000000..08272e3040 --- /dev/null +++ b/packages/connector/tencent-meeting/package.json @@ -0,0 +1,64 @@ +{ + "name": "@deepseek-ai/dsh-tencent-meeting", + "description": "Tencent Meeting plugin: the official tmeet with its skill, and account connection from the Plugins page", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/tencent-meeting" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "skills", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@tencentcloud/tmeet": "1.0.18" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-upstream-skills": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-skill": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-upstream-skills": "workspace:*" + } +} diff --git a/packages/connector/tencent-meeting/skills/tencent-meeting/SKILL.md b/packages/connector/tencent-meeting/skills/tencent-meeting/SKILL.md new file mode 100644 index 0000000000..4caac69dd0 --- /dev/null +++ b/packages/connector/tencent-meeting/skills/tencent-meeting/SKILL.md @@ -0,0 +1,24 @@ +--- +name: tencent-meeting +description: 腾讯会议插件:通过 tmeet 使用腾讯会议的会议创建与查询、受邀者管理、录制与转写、智能纪要和元宝纪要、会议报告、会中控制和事件订阅。用户提到腾讯会议、会议号、会议录制或纪要时,先加载本技能,再读取 tmeet-skill 子指南。 +--- + +# 腾讯会议插件 + +## DSH 指引 + +- 在面向用户的回复中,把这项集成称为“腾讯会议插件”。`tmeet` 由腾讯会议插件安装,按当前 runtime context 给出的绝对路径运行,不要直接按名称运行。不要执行 `npm install -g @tencentcloud/tmeet`,也不要用其他方式另装或升级 `tmeet`。 +- `tmeet` 的登录保存在这台电脑的默认配置目录,与用户自己终端里的 `tmeet` 共用。除非用户要求,不要执行 `tmeet auth logout`。 +- 首次运行 `tmeet` 业务命令前,先读 `tmeet-skill` 子指南。本节与该子指南冲突时以本节为准:跳过它“安装与初始化”一节的安装检查;跳过运行 `scripts/agent_init.py` 的要求,DSH 不提供这个脚本,`tmeet` 不依赖它。 +- 命令提示未登录或需要重新登录(例如 `user config is empty`、`user identity expired`、`refresh token failed`)时,先请用户在「插件」中打开腾讯会议插件页面,点击“连接腾讯会议”并完成授权;用户完成后再继续。只有用户要求在本次对话中完成登录时,才执行 `tmeet auth login --no-browser`:它先输出授权链接,再最多等待 5 分钟,把链接完整告诉用户。它会把登录凭据写到工作区之外,保存被拒绝时这次授权也会作废:第一次运行就把 Shell 工具的 `sandbox_permissions` 设为能写工作区之外的最窄模式,并填写 `justification`。 +- 其他 `tmeet` 命令在现有沙箱中运行;只有凭据、锁或日志写入被拒绝时,才设置 `sandbox_permissions`。 +- 不要索取或输出 AccessToken、RefreshToken 等凭据。 + +## 子指南索引 + +- `tmeet-skill`:腾讯会议官方 CLI 的使用说明,涵盖全部命令、查询命令的选择准则、安全规则、需要用户二次确认的操作和常见错误;首次运行 `tmeet` 业务命令前先读。会议、录制、报告、通讯录、会中控制、纪要、应用信息、事件和问题排查各模块的参数与示例在它的 `references/` 中。 + +## 打开子指南 + +- 子指南不是独立的 skill,不要用 `skill` 工具加载;用文件读取工具打开本技能目录下的 `skills/tmeet-skill/SKILL.md`。 +- 子指南中的相对路径(例如 `references/tmeet-meeting.md`)相对子指南自己的目录 `skills/tmeet-skill/`。 diff --git a/packages/connector/tencent-meeting/src/account.ts b/packages/connector/tencent-meeting/src/account.ts new file mode 100644 index 0000000000..728b709cbe --- /dev/null +++ b/packages/connector/tencent-meeting/src/account.ts @@ -0,0 +1,88 @@ +/** + * Check, sign-in, and sign-out of the default tmeet account that the user's terminal shares, as the operations + * `ctx.cliAccounts` runs. + */ + +import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' +import type { UpstreamSkillsHandle } from '@deepseek-ai/dsh-upstream-skills/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { + TencentMeetingAccountState, TencentMeetingCommand, TencentMeetingOperationKind, TencentMeetingPhase, TencentMeetingSignIn, +} from './types.ts' + +const LOGIN_LINK = /^authorize url: (https:\/\/\S+)[ \t]*$/u + +type Control = CliOperationControl + +/** The upstream guide whose state the account carries and whose failed download each check restarts. */ +type Guides = Pick + +/** + * Read the text `auth status` prints; tmeet 1.0.18 has no machine-readable status and exits 0 whether or not a user is + * signed in. `Logged in` alone does not show that the server accepts the sign-in: the CLI prints the user name only + * after its user-info request succeeds, refreshing the token first when needed. + * @returns the account, or undefined for output this version does not print. + */ +function readStatus(stdout: string): TencentMeetingSignIn | undefined { + if (/^[ \t]*(?:Not logged in|Session has expired)\./mu.test(stdout)) return { state: 'signed-out' } + if (!/^Logged in$/mu.test(stdout)) return undefined + if (/^[ \t]*RefreshToken:[ \t]+expired\b/mu.test(stdout)) return { state: 'signed-out' } + const userName = /^[ \t]*UserName:[ \t]+(\S.*?)[ \t]*$/mu.exec(stdout)?.[1] + return userName === undefined ? { state: 'unverified' } : { state: 'connected', userName } +} + +/* jscpd:ignore-start -- CLI app plugins with downloaded guides bind their operations to the guides alike. */ +/** + * Bind the Tencent Meeting account operations to the upstream guide. + * @param guides - the registered upstream guide. + * @returns the function that carries out one operation with tmeet and publishes the account each check observes; it + * throws when a command fails, prints an unknown status, or leaves no verified sign-in after a sign-in. + */ +export function performWith(guides: Guides): (kind: TencentMeetingOperationKind, control: Control, signal: AbortSignal) => Promise { + return async (kind, control, signal) => { + switch (kind) { + case 'check': + await check(guides, control, signal) + return + case 'sign-in': return signIn(guides, control, signal) + case 'sign-out': return signOut(guides, control, signal) + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) + } + } +} +/* jscpd:ignore-end */ + +/** Sign in through the CLI's authorization page, then confirm that the server accepts the new sign-in. */ +async function signIn(guides: Guides, control: Control, signal: AbortSignal): Promise { + control.stage('authorizing') + const login = await control.run('auth-login', ['auth', 'login', '--no-browser'], signal, { + awaitsUser: true, + onLine: (stream, line) => { + const link = stream === 'stdout' ? LOGIN_LINK.exec(line) : null + if (link !== null) control.offer(link[1] as string) + }, + }) + if (login.exitCode !== 0) throw new Error(`tencent-meeting: auth login exited with ${String(login.exitCode)}`) + control.stage('checking') + if ((await check(guides, control, signal)).state !== 'connected') throw new Error('tencent-meeting: auth login left no verified sign-in') +} + +/** Clear the default sign-in, which also signs out the user's own terminal, then check again. */ +async function signOut(guides: Guides, control: Control, signal: AbortSignal): Promise { + control.stage('signing-out') + const logout = await control.run('auth-logout', ['auth', 'logout'], signal) + if (logout.exitCode !== 0) throw new Error(`tencent-meeting: auth logout exited with ${String(logout.exitCode)}`) + await check(guides, control, signal) +} + +/** Restart a failed download of the guide without waiting for it, then read the default account, publish it, and return it. */ +async function check(guides: Guides, control: Control, signal: AbortSignal): Promise { + guides.retry() + const result = await control.run('auth-status', ['auth', 'status'], signal) + const signIn = result.exitCode === 0 ? readStatus(result.stdout) : undefined + if (signIn === undefined) throw new Error(`tencent-meeting: auth status exited with ${String(result.exitCode)} or printed an unknown status`) + const account: TencentMeetingAccountState = { ...signIn, skills: guides.state } + control.publish(account) + return account +} diff --git a/packages/connector/tencent-meeting/src/directory.ts b/packages/connector/tencent-meeting/src/directory.ts new file mode 100644 index 0000000000..dc5f5e277e --- /dev/null +++ b/packages/connector/tencent-meeting/src/directory.ts @@ -0,0 +1,61 @@ +/** Managed tmeet location: the platform executable that `@tencentcloud/tmeet` ships under its own name. */ + +import { accessSync, constants } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +/** The name tmeet's guides run it by. */ +export const PROGRAM = 'tmeet' + +/** + * Name the executable file a `binDir` holds. + * @param platform - the Host platform. + * @returns `tmeet`, or `tmeet.exe` on Windows. + */ +export function executableFileName(platform: NodeJS.Platform): string { + return platform === 'win32' ? `${PROGRAM}.exe` : PROGRAM +} + +/** Platform executables in the package's `dist`, named as the package's own launcher maps them. */ +const PLATFORM_EXECUTABLES: Readonly>> = { + 'darwin-arm64': 'tmeet-macOS-AppleSilicon', + 'darwin-x64': 'tmeet-macOS-Intel', + 'linux-arm64': 'tmeet-Linux-ARM64', + 'linux-x64': 'tmeet-Linux-x86_64', + 'win32-x64': 'tmeet-Windows-x86_64.exe', +} + +function requireExecutable(program: string, remedy: string): void { + try { + accessSync(program, constants.X_OK) + } catch (error) { + throw new Error(`tencent-meeting: ${program} is not executable; ${remedy}`, { cause: error }) + } +} + +function platformExecutable(): string { + const executable = PLATFORM_EXECUTABLES[`${process.platform}-${process.arch}`] + if (executable === undefined) { + throw new Error(`tencent-meeting: @tencentcloud/tmeet has no executable for ${process.platform}-${process.arch}; set binDir`) + } + return join(dirname(fileURLToPath(import.meta.resolve('@tencentcloud/tmeet/package.json'))), 'dist', executable) +} + +/** + * Locate the managed executable. + * @param binDir - absolute override holding an executable `tmeet`, `tmeet.exe` on Windows; defaults to the installed `@tencentcloud/tmeet` + * executable for this platform. + * @returns the absolute path of the executable. + * @throws when the platform has no packaged executable or the executable is missing or not executable. + */ +export function resolveCliExecutable(binDir: string | undefined): string { + if (binDir !== undefined) { + const file = executableFileName(process.platform) + const executable = join(binDir, file) + requireExecutable(executable, `set binDir to a directory containing an executable ${file}`) + return executable + } + const executable = platformExecutable() + requireExecutable(executable, 'reinstall the plugin or set binDir') + return executable +} diff --git a/packages/connector/tencent-meeting/src/index.ts b/packages/connector/tencent-meeting/src/index.ts new file mode 100644 index 0000000000..39e3711779 --- /dev/null +++ b/packages/connector/tencent-meeting/src/index.ts @@ -0,0 +1,68 @@ +/** + * Tencent Meeting plugin: registers the managed tmeet and its account with `ctx.cliAccounts`, which tells the model the + * CLI's absolute path and shows the account on the Plugins page, and registers the `tencent-meeting` entry skill with + * `ctx.upstreamSkills`, which downloads the upstream guide it indexes. The CLI's default sign-in is shared with the + * user's own terminal. + * @module @deepseek-ai/dsh-tencent-meeting + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-cli-account' +import type {} from '@deepseek-ai/dsh-upstream-skills' +import { performWith } from './account.ts' +import { PROGRAM, resolveCliExecutable } from './directory.ts' +import { dictionaries, type TencentMeetingTextKey } from './locales.ts' +import { copy, operations, presentAccount, TENCENT_MEETING_PACKAGE } from './presentation.ts' +import { ENTRY, TMEET_SKILLS } from './skills.ts' +import type { TencentMeetingAccountState, TencentMeetingCommand, TencentMeetingOperationKind, TencentMeetingPhase } from './types.ts' + +/** Plugin name. */ +export const name = 'tencent-meeting' + +/* jscpd:ignore-start -- CLI app plugins with downloaded guides declare the same services, config, and registration. */ +/** Services the CLI's account and the entry skill register with. */ +export const inject = ['cliAccounts', 'upstreamSkills'] + +/** Where tmeet and the upstream guide are. */ +export interface Config { + /** Absolute directory holding the `tmeet` executable; defaults to the installed `@tencentcloud/tmeet` executable for this platform. */ + binDir?: string + /** Absolute directory holding the upstream guide at its repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} + +/** Validates {@link Config}. */ +export const Config: z = z.object({ + binDir: z.string().min(1), + skillsDir: z.string().min(1), +}) + +/** + * Register the entry skill, and the CLI with its account, whose view follows the guide's download. + * @param ctx - Context carrying the CLI account Service and the upstream skills Service. + * @param config - CLI location and the guide's directory. + * @throws when this platform has no packaged `tmeet`, `tmeet` is not executable, or `skillsDir` is not a directory. + */ +export function apply(ctx: Context, config: Config): void { + const executable = resolveCliExecutable(config.binDir) + const guides = ctx.upstreamSkills.register({ name, entry: ENTRY, set: TMEET_SKILLS, skillsDir: config.skillsDir }) + const account = ctx.cliAccounts.register< + TencentMeetingAccountState, TencentMeetingOperationKind, TencentMeetingPhase, TencentMeetingCommand, TencentMeetingTextKey + >({ + name, + packageName: TENCENT_MEETING_PACKAGE, + cli: { product: 'Tencent Meeting', program: PROGRAM, executable }, + account: { state: 'unchecked', skills: guides.state }, + check: 'check', + cancellable: ['authorizing'], + authorizationHosts: ['meeting.tencent.com'], + perform: performWith(guides), + dictionaries, + operations, + copy, + present: presentAccount, + }) + ctx.effect(() => guides.watch((skills) => { account.publish({ ...account.snapshot().account, skills }) }), 'tencent-meeting: guide') +} +/* jscpd:ignore-end */ diff --git a/packages/connector/tencent-meeting/src/locales.ts b/packages/connector/tencent-meeting/src/locales.ts new file mode 100644 index 0000000000..533ee400de --- /dev/null +++ b/packages/connector/tencent-meeting/src/locales.ts @@ -0,0 +1,287 @@ +/** The Tencent Meeting text the Plugins page shows; the browser resolves it in its active language. */ + +/** Chinese dictionary and key source. */ +export const zh = { + 'section.title': '腾讯会议账号', + 'status.checking': '正在检查连接', + 'status.disconnected': '未连接', + 'status.unavailable': '暂时无法确认登录状态', + 'status.connected': '已连接', + 'step.authorizing': '等待在腾讯会议页面授权', + 'step.connecting': '正在连接', + 'step.signing-out': '正在退出登录', + 'detail.disconnected': '登录腾讯会议账号后,就可以在对话中使用会议、录制、纪要和会议报告等功能。', + 'detail.unavailable': '已保留现有登录,可以稍后重试。', + 'detail.connected': '已登录为 {name}。可以在对话中直接请 Agent 使用腾讯会议。', + 'detail.authorizing': '在打开的腾讯会议页面中确认授权,完成后回到这里查看结果。页面没有打开时,点击“打开腾讯会议页面”。', + 'skills.downloading': '正在从 GitHub 下载腾讯会议技能,下载完成后即可在对话中使用。', + 'skills.failed': '腾讯会议技能没能下载,Agent 暂时用不了腾讯会议的子指南。请确认这台电脑能访问 GitHub,然后重试。', + hint: '腾讯会议账号与这台电脑终端里的 tmeet 共用;关闭插件不会退出登录。', + failed: '操作未完成,请重试', + 'action.connect': '连接腾讯会议', + 'action.open': '打开腾讯会议页面', + 'action.cancel': '取消', + 'action.signOut': '退出登录', + 'action.retry': '重试', + 'badge.connected': '已连接', + 'badge.disconnected': '未连接', + 'badge.connecting': '连接中', + 'badge.unavailable': '待确认', + 'signOut.title': '退出腾讯会议登录?', + 'signOut.body': '将退出 tmeet 的登录,这台电脑终端里的 tmeet 也会一起退出。', + 'activation.title': '连接腾讯会议账号', + 'activation.body': '腾讯会议插件已开启。连接你的腾讯会议账号后,就可以在对话中使用它。', + 'notice.connected': '腾讯会议已连接', + 'notice.signed-out': '已退出腾讯会议登录', +} + +/** Every key of the Tencent Meeting text. */ +export type TencentMeetingTextKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + 'section.title': 'Tencent Meeting account', + 'status.checking': 'Checking connection', + 'status.disconnected': 'Not connected', + 'status.unavailable': 'Cannot confirm sign-in right now', + 'status.connected': 'Connected', + 'step.authorizing': 'Waiting for authorization on the Tencent Meeting page', + 'step.connecting': 'Connecting', + 'step.signing-out': 'Signing out', + 'detail.disconnected': 'Sign in to Tencent Meeting to use meetings, recordings, minutes, meeting reports, and other features in conversations.', + 'detail.unavailable': 'The existing sign-in is kept. Try again later.', + 'detail.connected': 'Signed in as {name}. Ask the agent to use Tencent Meeting directly in a conversation.', + 'detail.authorizing': 'Confirm the authorization on the Tencent Meeting page that opened, then come back here to see the result. If the page did not open, select Open Tencent Meeting page.', + 'skills.downloading': 'Downloading the Tencent Meeting skill from GitHub. It becomes available in conversations when the download finishes.', + 'skills.failed': 'The Tencent Meeting skill could not be downloaded, so the agent cannot use the Tencent Meeting guide yet. Check that this computer can reach GitHub, then retry.', + hint: 'The Tencent Meeting account is shared with tmeet in this computer\'s terminal. Turning the plugin off does not sign it out.', + failed: 'The action did not finish. Try again.', + 'action.connect': 'Connect Tencent Meeting', + 'action.open': 'Open Tencent Meeting page', + 'action.cancel': 'Cancel', + 'action.signOut': 'Sign out', + 'action.retry': 'Retry', + 'badge.connected': 'Connected', + 'badge.disconnected': 'Not connected', + 'badge.connecting': 'Connecting', + 'badge.unavailable': 'Unconfirmed', + 'signOut.title': 'Sign out of Tencent Meeting?', + 'signOut.body': 'This signs out tmeet, including tmeet in this computer\'s terminal.', + 'activation.title': 'Connect your Tencent Meeting account', + 'activation.body': 'The Tencent Meeting plugin is on. Connect your Tencent Meeting account to use it in conversations.', + 'notice.connected': 'Tencent Meeting connected', + 'notice.signed-out': 'Signed out of Tencent Meeting', +} + +/** Japanese dictionary. */ +export const ja: Record = { + 'section.title': 'Tencent Meeting アカウント', + 'status.checking': '接続を確認中', + 'status.disconnected': '未接続', + 'status.unavailable': '現在サインイン状態を確認できません', + 'status.connected': '接続済み', + 'step.authorizing': 'Tencent Meeting ページでの認可を待っています', + 'step.connecting': '接続中', + 'step.signing-out': 'サインアウト中', + 'detail.disconnected': 'Tencent Meeting にサインインすると、会話の中で会議、録画、議事録、会議レポートなどの機能を使用できます。', + 'detail.unavailable': '現在のサインイン状態は保持されています。しばらくしてから再試行してください。', + 'detail.connected': '{name} としてサインインしています。会話の中でエージェントに Tencent Meeting の使用を直接依頼できます。', + 'detail.authorizing': '開いた Tencent Meeting ページで認可を確定し、完了したらここに戻って結果を確認してください。ページが開かない場合は、「Tencent Meeting ページを開く」を選択してください。', + 'skills.downloading': 'GitHub から Tencent Meeting のスキルをダウンロードしています。ダウンロードが完了すると、会話の中で使用できます。', + 'skills.failed': 'Tencent Meeting のスキルをダウンロードできなかったため、エージェントはまだ Tencent Meeting のガイドを使用できません。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', + hint: 'Tencent Meeting アカウントは、このコンピューターのターミナルにある tmeet と共有されます。プラグインをオフにしてもサインアウトはされません。', + failed: '操作が完了しませんでした。もう一度お試しください。', + 'action.connect': 'Tencent Meeting を接続', + 'action.open': 'Tencent Meeting ページを開く', + 'action.cancel': 'キャンセル', + 'action.signOut': 'サインアウト', + 'action.retry': '再試行', + 'badge.connected': '接続済み', + 'badge.disconnected': '未接続', + 'badge.connecting': '接続中', + 'badge.unavailable': '未確認', + 'signOut.title': 'Tencent Meeting からサインアウトしますか?', + 'signOut.body': 'tmeet からサインアウトします。このコンピューターのターミナルにある tmeet もサインアウトされます。', + 'activation.title': 'Tencent Meeting アカウントを接続', + 'activation.body': 'Tencent Meeting プラグインがオンになりました。Tencent Meeting アカウントを接続すると、会話の中で使用できます。', + 'notice.connected': 'Tencent Meeting を接続しました', + 'notice.signed-out': 'Tencent Meeting からサインアウトしました', +} + +/** Spanish dictionary. */ +export const es: Record = { + 'section.title': 'Cuenta de Tencent Meeting', + 'status.checking': 'Comprobando la conexión', + 'status.disconnected': 'No conectado', + 'status.unavailable': 'No se puede confirmar el inicio de sesión en este momento', + 'status.connected': 'Conectado', + 'step.authorizing': 'Esperando la autorización en la página de Tencent Meeting', + 'step.connecting': 'Conectando', + 'step.signing-out': 'Cerrando sesión', + 'detail.disconnected': 'Inicie sesión en Tencent Meeting para usar reuniones, grabaciones, actas, informes de reuniones y otras funciones en las conversaciones.', + 'detail.unavailable': 'Se conserva el inicio de sesión actual. Inténtelo de nuevo más tarde.', + 'detail.connected': 'Sesión iniciada como {name}. Pida al agente que use Tencent Meeting directamente en una conversación.', + 'detail.authorizing': 'Confirme la autorización en la página de Tencent Meeting que se abrió y luego vuelva aquí para ver el resultado. Si la página no se abrió, seleccione “Abrir página de Tencent Meeting”.', + 'skills.downloading': 'Descargando la habilidad de Tencent Meeting desde GitHub. Estará disponible en las conversaciones cuando termine la descarga.', + 'skills.failed': 'No se pudo descargar la habilidad de Tencent Meeting, por lo que el agente aún no puede usar la guía de Tencent Meeting. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', + hint: 'La cuenta de Tencent Meeting se comparte con tmeet en la terminal de esta computadora. Desactivar el complemento no cierra su sesión.', + failed: 'La acción no se completó. Inténtelo de nuevo.', + 'action.connect': 'Conectar Tencent Meeting', + 'action.open': 'Abrir página de Tencent Meeting', + 'action.cancel': 'Cancelar', + 'action.signOut': 'Cerrar sesión', + 'action.retry': 'Reintentar', + 'badge.connected': 'Conectado', + 'badge.disconnected': 'No conectado', + 'badge.connecting': 'Conectando', + 'badge.unavailable': 'Sin confirmar', + 'signOut.title': '¿Cerrar sesión en Tencent Meeting?', + 'signOut.body': 'Se cerrará la sesión de tmeet, incluido tmeet en la terminal de esta computadora.', + 'activation.title': 'Conecte su cuenta de Tencent Meeting', + 'activation.body': 'El complemento de Tencent Meeting está activado. Conecte su cuenta de Tencent Meeting para usarlo en las conversaciones.', + 'notice.connected': 'Tencent Meeting conectado', + 'notice.signed-out': 'Sesión de Tencent Meeting cerrada', +} + +/** French dictionary. */ +export const fr: Record = { + 'section.title': 'Compte Tencent Meeting', + 'status.checking': 'Vérification de la connexion', + 'status.disconnected': 'Non connecté', + 'status.unavailable': 'Impossible de confirmer la connexion pour le moment', + 'status.connected': 'Connecté', + 'step.authorizing': 'En attente de l’autorisation sur la page Tencent Meeting', + 'step.connecting': 'Connexion en cours', + 'step.signing-out': 'Déconnexion en cours', + 'detail.disconnected': 'Connectez-vous à Tencent Meeting pour utiliser les réunions, les enregistrements, les comptes rendus, les rapports de réunion et d’autres fonctionnalités dans les conversations.', + 'detail.unavailable': 'La connexion existante est conservée. Réessayez plus tard.', + 'detail.connected': 'Connecté en tant que {name}. Demandez à l’agent d’utiliser Tencent Meeting directement dans une conversation.', + 'detail.authorizing': 'Confirmez l’autorisation sur la page Tencent Meeting qui s’est ouverte, puis revenez ici pour voir le résultat. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page Tencent Meeting ».', + 'skills.downloading': 'Téléchargement de la compétence Tencent Meeting depuis GitHub. Elle sera disponible dans les conversations une fois le téléchargement terminé.', + 'skills.failed': 'La compétence Tencent Meeting n’a pas pu être téléchargée : l’agent ne peut donc pas encore utiliser le guide Tencent Meeting. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', + hint: 'Le compte Tencent Meeting est partagé avec tmeet dans le terminal de cet ordinateur. Désactiver le plugin ne le déconnecte pas.', + failed: 'L’action n’a pas abouti. Réessayez.', + 'action.connect': 'Connecter Tencent Meeting', + 'action.open': 'Ouvrir la page Tencent Meeting', + 'action.cancel': 'Annuler', + 'action.signOut': 'Se déconnecter', + 'action.retry': 'Réessayer', + 'badge.connected': 'Connecté', + 'badge.disconnected': 'Non connecté', + 'badge.connecting': 'Connexion en cours', + 'badge.unavailable': 'Non confirmé', + 'signOut.title': 'Se déconnecter de Tencent Meeting ?', + 'signOut.body': 'Cela déconnecte tmeet, y compris tmeet dans le terminal de cet ordinateur.', + 'activation.title': 'Connectez votre compte Tencent Meeting', + 'activation.body': 'Le plugin Tencent Meeting est activé. Connectez votre compte Tencent Meeting pour l’utiliser dans les conversations.', + 'notice.connected': 'Tencent Meeting connecté', + 'notice.signed-out': 'Déconnecté de Tencent Meeting', +} + +/** German dictionary. */ +export const de: Record = { + 'section.title': 'Tencent Meeting-Konto', + 'status.checking': 'Verbindung wird geprüft', + 'status.disconnected': 'Nicht verbunden', + 'status.unavailable': 'Anmeldung kann gerade nicht bestätigt werden', + 'status.connected': 'Verbunden', + 'step.authorizing': 'Warten auf die Autorisierung auf der Tencent Meeting-Seite', + 'step.connecting': 'Wird verbunden', + 'step.signing-out': 'Wird abgemeldet', + 'detail.disconnected': 'Melden Sie sich bei Tencent Meeting an, um Besprechungen, Aufzeichnungen, Protokolle, Besprechungsberichte und weitere Funktionen in Unterhaltungen zu verwenden.', + 'detail.unavailable': 'Die bestehende Anmeldung bleibt erhalten. Versuchen Sie es später erneut.', + 'detail.connected': 'Angemeldet als {name}. Bitten Sie den Agenten, Tencent Meeting direkt in einer Unterhaltung zu verwenden.', + 'detail.authorizing': 'Bestätigen Sie die Autorisierung auf der geöffneten Tencent Meeting-Seite und kehren Sie dann hierher zurück, um das Ergebnis zu sehen. Falls sich die Seite nicht geöffnet hat, wählen Sie „Tencent Meeting-Seite öffnen“.', + 'skills.downloading': 'Die Fertigkeit von Tencent Meeting wird von GitHub heruntergeladen. Sie steht in Unterhaltungen zur Verfügung, sobald der Download abgeschlossen ist.', + 'skills.failed': 'Die Fertigkeit von Tencent Meeting konnte nicht heruntergeladen werden, daher kann der Agent die Tencent Meeting-Anleitung noch nicht verwenden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', + hint: 'Das Tencent Meeting-Konto wird mit tmeet im Terminal dieses Computers geteilt. Wenn Sie das Plugin deaktivieren, bleibt es angemeldet.', + failed: 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', + 'action.connect': 'Tencent Meeting verbinden', + 'action.open': 'Tencent Meeting-Seite öffnen', + 'action.cancel': 'Abbrechen', + 'action.signOut': 'Abmelden', + 'action.retry': 'Erneut versuchen', + 'badge.connected': 'Verbunden', + 'badge.disconnected': 'Nicht verbunden', + 'badge.connecting': 'Wird verbunden', + 'badge.unavailable': 'Unbestätigt', + 'signOut.title': 'Von Tencent Meeting abmelden?', + 'signOut.body': 'Dadurch wird tmeet abgemeldet, auch tmeet im Terminal dieses Computers.', + 'activation.title': 'Tencent Meeting-Konto verbinden', + 'activation.body': 'Das Tencent Meeting-Plugin ist aktiviert. Verbinden Sie Ihr Tencent Meeting-Konto, um es in Unterhaltungen zu verwenden.', + 'notice.connected': 'Tencent Meeting verbunden', + 'notice.signed-out': 'Von Tencent Meeting abgemeldet', +} + +/** Russian dictionary. */ +export const ru: Record = { + 'section.title': 'Аккаунт Tencent Meeting', + 'status.checking': 'Проверка подключения', + 'status.disconnected': 'Не подключено', + 'status.unavailable': 'Сейчас не удаётся подтвердить вход', + 'status.connected': 'Подключено', + 'step.authorizing': 'Ожидание авторизации на странице Tencent Meeting', + 'step.connecting': 'Подключение', + 'step.signing-out': 'Выполняется выход', + 'detail.disconnected': 'Войдите в Tencent Meeting, чтобы использовать в беседах встречи, записи, протоколы, отчёты о встречах и другие функции.', + 'detail.unavailable': 'Текущий вход сохранён. Повторите попытку позже.', + 'detail.connected': 'Выполнен вход как {name}. Попросите агента использовать Tencent Meeting прямо в беседе.', + 'detail.authorizing': 'Подтвердите авторизацию на открывшейся странице Tencent Meeting, затем вернитесь сюда, чтобы увидеть результат. Если страница не открылась, нажмите «Открыть страницу Tencent Meeting».', + 'skills.downloading': 'Навык Tencent Meeting загружается с GitHub. Он станет доступен в беседах, когда загрузка завершится.', + 'skills.failed': 'Не удалось загрузить навык Tencent Meeting, поэтому агент пока не может использовать руководство Tencent Meeting. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', + hint: 'Аккаунт Tencent Meeting общий с tmeet в терминале этого компьютера. Отключение плагина не приводит к выходу из аккаунта.', + failed: 'Действие не завершено. Повторите попытку.', + 'action.connect': 'Подключить Tencent Meeting', + 'action.open': 'Открыть страницу Tencent Meeting', + 'action.cancel': 'Отмена', + 'action.signOut': 'Выйти', + 'action.retry': 'Повторить', + 'badge.connected': 'Подключено', + 'badge.disconnected': 'Не подключено', + 'badge.connecting': 'Подключение', + 'badge.unavailable': 'Не подтверждено', + 'signOut.title': 'Выйти из Tencent Meeting?', + 'signOut.body': 'Будет выполнен выход из tmeet, в том числе для tmeet в терминале этого компьютера.', + 'activation.title': 'Подключите аккаунт Tencent Meeting', + 'activation.body': 'Плагин Tencent Meeting включён. Подключите аккаунт Tencent Meeting, чтобы использовать его в беседах.', + 'notice.connected': 'Tencent Meeting подключён', + 'notice.signed-out': 'Выполнен выход из Tencent Meeting', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + 'section.title': 'Conta do Tencent Meeting', + 'status.checking': 'Verificando a conexão', + 'status.disconnected': 'Não conectado', + 'status.unavailable': 'Não é possível confirmar o login no momento', + 'status.connected': 'Conectado', + 'step.authorizing': 'Aguardando a autorização na página do Tencent Meeting', + 'step.connecting': 'Conectando', + 'step.signing-out': 'Saindo', + 'detail.disconnected': 'Entre no Tencent Meeting para usar reuniões, gravações, atas, relatórios de reunião e outros recursos nas conversas.', + 'detail.unavailable': 'O login atual foi mantido. Tente novamente mais tarde.', + 'detail.connected': 'Conectado como {name}. Peça ao agente que use o Tencent Meeting diretamente em uma conversa.', + 'detail.authorizing': 'Confirme a autorização na página do Tencent Meeting que foi aberta e depois volte aqui para ver o resultado. Se a página não abriu, selecione “Abrir página do Tencent Meeting”.', + 'skills.downloading': 'Baixando a habilidade do Tencent Meeting do GitHub. Ela ficará disponível nas conversas quando o download terminar.', + 'skills.failed': 'Não foi possível baixar a habilidade do Tencent Meeting, então o agente ainda não pode usar o guia do Tencent Meeting. Verifique se este computador consegue acessar o GitHub e tente novamente.', + hint: 'A conta do Tencent Meeting é compartilhada com o tmeet no terminal deste computador. Desativar o plugin não encerra a sessão dela.', + failed: 'A ação não foi concluída. Tente novamente.', + 'action.connect': 'Conectar Tencent Meeting', + 'action.open': 'Abrir página do Tencent Meeting', + 'action.cancel': 'Cancelar', + 'action.signOut': 'Sair', + 'action.retry': 'Tentar novamente', + 'badge.connected': 'Conectado', + 'badge.disconnected': 'Não conectado', + 'badge.connecting': 'Conectando', + 'badge.unavailable': 'Não confirmado', + 'signOut.title': 'Sair do Tencent Meeting?', + 'signOut.body': 'Isso encerra a sessão do tmeet, incluindo o tmeet no terminal deste computador.', + 'activation.title': 'Conecte sua conta do Tencent Meeting', + 'activation.body': 'O plugin do Tencent Meeting está ativado. Conecte sua conta do Tencent Meeting para usá-lo nas conversas.', + 'notice.connected': 'Tencent Meeting conectado', + 'notice.signed-out': 'Você saiu do Tencent Meeting', +} + +/** The dictionary of every shipped language. */ +export const dictionaries = { zh, en, ja, es, fr, de, ru, pt } diff --git a/packages/connector/tencent-meeting/src/presentation.ts b/packages/connector/tencent-meeting/src/presentation.ts new file mode 100644 index 0000000000..58a22acb52 --- /dev/null +++ b/packages/connector/tencent-meeting/src/presentation.ts @@ -0,0 +1,122 @@ +/** The Tencent Meeting account section the Plugins page shows for each Host view. */ +import type { CliAccountText } from '@deepseek-ai/dsh-cli-account/types' +import type { + ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountNote, + ConnectorAccountOperation, +} from '@deepseek-ai/dsh-client-ui-connector-account/types' +import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { TencentMeetingTextKey } from './locales.ts' +import type { TencentMeetingOperationKind, TencentMeetingState } from './types.ts' + +type Text = CliAccountText + +/** The npm package whose bundle page carries the account section. */ +export const TENCENT_MEETING_PACKAGE = '@deepseek-ai/dsh-tencent-meeting' + +/* jscpd:ignore-start -- CLI app plugins declare page operations, copy, and commands alike, each with its own text. */ +/** + * List the operations the section's buttons start; signing in and out report a notice in the browser that started them. + * @param text - writes a key of the Tencent Meeting text in every shipped language. + * @returns the operations with their notices. + */ +export function operations(text: Text): readonly ConnectorAccountOperation[] { + return [ + { kind: 'check' }, + { kind: 'sign-in', notice: text('notice.connected') }, + { kind: 'sign-out', notice: text('notice.signed-out') }, + ] +} + +/** + * Write the section's title and hint, and the prompt after the bundle is switched on while signed out. + * @param text - writes a key of the Tencent Meeting text in every shipped language. + * @returns the section's fixed text. + */ +export function copy(text: Text): ConnectorAccountCopy { + return { + title: text('section.title'), + hint: text('hint'), + activation: { title: text('activation.title'), body: text('activation.body'), connect: text('action.connect') }, + } +} + +const CHECK = { kind: 'start', operation: 'check' } as const +const SIGN_IN = { kind: 'start', operation: 'sign-in' } as const +const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const +/* jscpd:ignore-end */ + +/* jscpd:ignore-start -- CLI app plugins whose guides download report the same states, each in its own text. */ +/** The row that reports a guide that is not in place yet; a failed download offers a check, which restarts it. */ +function skillsNotes(skills: UpstreamSkillsState, text: Text): ConnectorAccountNote[] { + switch (skills) { + case 'installed': return [] + case 'downloading': return [{ text: text('skills.downloading') }] + case 'failed': return [{ text: text('skills.failed'), button: { label: text('action.retry'), command: CHECK } }] + /* v8 ignore next -- closed skills state union */ + default: return assertNever(skills) + } +} +/* jscpd:ignore-end */ + +type Operation = NonNullable + +function step(operation: Operation): 'step.authorizing' | 'step.connecting' | 'step.signing-out' { + if (operation.kind === 'sign-out') return 'step.signing-out' + return operation.phase === 'authorizing' ? 'step.authorizing' : 'step.connecting' +} + +/** The section while a sign-in or sign-out runs: its step, the authorization page while waiting there, and cancel. */ +function presentOperation(operation: Operation, notes: ConnectorAccountNote[], text: Text): ConnectorAccountDisplay { + const authorizing = step(operation) === 'step.authorizing' && operation.authorizationUrl !== undefined + const buttons: ConnectorAccountButton[] = [] + if (authorizing) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) + if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + return { + phase: 'connecting', status: text(step(operation)), badge: text('badge.connecting'), buttons, notes, + ...authorizing ? { detail: text('detail.authorizing') } : {}, + } +} + +/** + * The account section for one Host view. + * @param view - the default tmeet account, the operation in progress, and the last result. + * @param text - writes a key of the Tencent Meeting text in every shipped language. + * @returns the phase, status, tag, buttons, detail, guide download row, and failure guidance. + */ +export function presentAccount(view: TencentMeetingState, text: Text): ConnectorAccountDisplay { + const notes = skillsNotes(view.account.skills, text) + const { account, operation } = view + if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes } + if (operation !== undefined) return presentOperation(operation, notes, text) + const failed = view.result?.outcome === 'failed' + // The Service adds the failed command and its exit code. + const failure: { failure?: ConnectorAccountFailure } = failed ? { failure: { text: text('failed') } } : {} + const unavailable: ConnectorAccountDisplay = { + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes, ...failure, + } + switch (account.state) { + case 'unchecked': return failed ? unavailable : { phase: 'checking', status: text('status.checking'), buttons: [], notes } + case 'unverified': return unavailable + case 'signed-out': + return { + phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), + buttons: [{ label: text('action.connect'), command: SIGN_IN, variant: 'primary' }], connect: SIGN_IN, + detail: text('detail.disconnected'), notes, ...failure, + } + /* jscpd:ignore-start -- CLI app plugins that sign out offer the same confirmed sign-out button. */ + case 'connected': + return { + phase: 'connected', status: text('status.connected'), badge: text('badge.connected'), + buttons: [{ + label: text('action.signOut'), command: SIGN_OUT, + confirm: { title: text('signOut.title'), body: text('signOut.body'), label: text('action.signOut') }, + }], + detail: text('detail.connected', { name: account.userName }), notes, ...failure, + } + /* jscpd:ignore-end */ + /* v8 ignore next -- closed account state union */ + default: return assertNever(account) + } +} diff --git a/packages/connector/tencent-meeting/src/skills.ts b/packages/connector/tencent-meeting/src/skills.ts new file mode 100644 index 0000000000..a49209ce29 --- /dev/null +++ b/packages/connector/tencent-meeting/src/skills.ts @@ -0,0 +1,21 @@ +/** The packaged `tencent-meeting` entry skill and the upstream guide it indexes. */ + +import { fileURLToPath } from 'node:url' +import type { UpstreamSkillSet } from '@deepseek-ai/dsh-upstream-skills' + +/** The packaged entry, which opens the guide by its repository path `skills/tmeet-skill/SKILL.md`. */ +export const ENTRY = fileURLToPath(new URL('../skills/tencent-meeting/SKILL.md', import.meta.url)) + +/** + * The official tmeet guide at the release the plugin installs, without `scripts/agent_init.py`, which the entry tells the + * agent to skip because DSH runs `tmeet` by its absolute path. + */ +export const TMEET_SKILLS: UpstreamSkillSet = { + repository: 'TencentCloud/tencentmeeting-cli', + commit: 'e631b355da2b001d24b82f453b65d96f39c59865', + directory: 'skills/tmeet-skill', + exclude: ['skills/tmeet-skill/scripts/agent_init.py'], + license: 'LICENSE', + bytes: 181_429, + sha256: '9bbdf81af17a49e1610063acd2a29f274313411e64a91e028588e3feb55bb7db', +} diff --git a/packages/connector/tencent-meeting/src/types.ts b/packages/connector/tencent-meeting/src/types.ts new file mode 100644 index 0000000000..1cd5b58000 --- /dev/null +++ b/packages/connector/tencent-meeting/src/types.ts @@ -0,0 +1,29 @@ +/** Credential-free Tencent Meeting account and operation views the Plugins page presenter reads. */ + +import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' +import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' + +/** The default tmeet account as the latest `auth status` observed it. */ +export type TencentMeetingSignIn = + | { readonly state: 'unchecked' | 'signed-out' | 'unverified' } + | { readonly state: 'connected'; readonly userName: string } + +/** The default tmeet account and where the upstream guide stands. */ +export type TencentMeetingAccountState = TencentMeetingSignIn & { + /** Whether the guide the `tencent-meeting` skill indexes is in place, downloading, or unavailable until a check retries it. */ + readonly skills: UpstreamSkillsState +} + +/** The account operations the Plugins page starts. */ +export type TencentMeetingOperationKind = 'check' | 'sign-in' | 'sign-out' + +/** Tencent Meeting steps of an operation, besides the Service's `checking` and `cancelling`. */ +export type TencentMeetingPhase = 'authorizing' | 'signing-out' + +/** The tmeet commands an operation runs; a failed operation reports its last one with that command's exit code. */ +export type TencentMeetingCommand = 'auth-status' | 'auth-login' | 'auth-logout' + +/** The complete Tencent Meeting view the presenter reads after each change. */ +export type TencentMeetingState = CliAccountView< + TencentMeetingAccountState, TencentMeetingOperationKind, TencentMeetingPhase, TencentMeetingCommand +> diff --git a/packages/connector/tencent-meeting/tests/account.spec.ts b/packages/connector/tencent-meeting/tests/account.spec.ts new file mode 100644 index 0000000000..e66c9d0332 --- /dev/null +++ b/packages/connector/tencent-meeting/tests/account.spec.ts @@ -0,0 +1,254 @@ +/** Account operations over a scripted tmeet: status text, sign-in, sign-out, cancellation, and the Plugins page wiring. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import type { ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { executableFileName } from '../src/directory.ts' +import * as TencentMeeting from '../src/index.ts' +import type { TencentMeetingOperationKind, TencentMeetingState } from '../src/types.ts' +import { createHost, type CliReply, type ScriptedProcess, type ScriptedSubprocess, type TencentMeetingPage } from './harness.ts' + +const STATUS = 'auth status' +const LOGIN = 'auth login --no-browser' +const LOGOUT = 'auth logout' +const LOGIN_LINK = 'https://meeting.tencent.com/marketplace/tencentmeeting-cli-auth.html?code=fixture-code' + +const CONNECTED: CliReply = { + stdout: 'Logged in\n OpenId: ou_fixture\n UserName: 测试 用户\n' + + ' AccessToken: valid (expires at 2026-11-01 10:00:00, remaining 15d 0h 6m)\n' + + ' RefreshToken: valid (expires at 2027-01-01 10:00:00, remaining 76d 0h 6m)\n', +} +const NOT_LOGGED_IN: CliReply = { stdout: 'Not logged in. Please use \'tmeet auth login\' to authenticate.\n' } +const SESSION_EXPIRED: CliReply = { stdout: ' Session has expired. Please use \'tmeet auth login\' to re-authenticate.\n' } +const REFRESH_EXPIRED: CliReply = { + stdout: 'Logged in\n OpenId: ou_fixture\n AccessToken: expired (at 2026-09-01 10:00:00)\n RefreshToken: expired (at 2026-10-01 10:00:00)\n', +} +const UNVERIFIED: CliReply = { + stdout: 'Logged in\n OpenId: ou_fixture\n AccessToken: valid (expires at 2026-11-01 10:00:00, remaining 15d 0h 6m)\n' + + ' RefreshToken: valid (expires at 2027-01-01 10:00:00, remaining 76d 0h 6m)\n', +} + +type Script = (process: ScriptedProcess) => void + +let ctx: Context +let subprocess: ScriptedSubprocess +let binDir: string +let skillsDir: string +/** The account the plugin registered, as the Plugins page registry drives it. */ +let account: TencentMeetingPage['source'] +let script: Record + +/** Start a Host and load the plugin on it; without `skillsDir` the plugin downloads the guide. */ +async function load(config: Pick | 'configured' = 'configured'): Promise { + const host = await createHost() + ;({ ctx, subprocess, binDir, skillsDir } = host) + subprocess.respond = (process) => { + const handler = script[process.spec.argv.slice(1).join(' ')] + if (handler === undefined) process.reply({ exitCode: 1, stderr: `unexpected: ${process.spec.argv.join(' ')}` }) + else if (Array.isArray(handler)) process.reply(handler.length > 1 ? handler.shift()! : handler[0]!) + else handler(process) + } + await ctx.plugin(TencentMeeting, { binDir, ...config === 'configured' ? { skillsDir } : config }) + account = host.pages[0]!.source +} + +beforeEach(() => { + script = {} +}) + +afterEach(async () => { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + vi.unstubAllGlobals() + await rm(binDir, { recursive: true, force: true }) + await rm(skillsDir, { recursive: true, force: true }) +}) + +/** Start an operation as a page button does; the CLI account Service starts it before returning. */ +const start = (kind: TencentMeetingOperationKind): ConnectorOperationId => { + const id = account.start(kind) + if (typeof id !== 'string') throw new Error('the operation did not start at once') + return id +} +const commands = () => subprocess.processes.map(process => process.spec.argv.slice(1).join(' ')) +const errors = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'error').map((message): unknown => message.args) +const settled = async (id: ConnectorOperationId): Promise => { + await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) }) + return account.snapshot() +} + +describe('Tencent Meeting account operations', () => { + beforeEach(() => load()) + + it.each<[string, CliReply, TencentMeetingState['account']]>([ + ['a sign-in the server accepts', CONNECTED, { state: 'connected', userName: '测试 用户', skills: 'installed' }], + ['no sign-in', NOT_LOGGED_IN, { state: 'signed-out', skills: 'installed' }], + ['a sign-in the CLI cleared after a failed refresh', SESSION_EXPIRED, { state: 'signed-out', skills: 'installed' }], + ['a sign-in whose refresh token expired', REFRESH_EXPIRED, { state: 'signed-out', skills: 'installed' }], + ['a stored sign-in the server did not confirm', UNVERIFIED, { state: 'unverified', skills: 'installed' }], + ])('checks %s', async (_name, reply, expected) => { + script[STATUS] = [reply] + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking', cancellable: false }) + expect(await settled(id)).toEqual({ account: expected, result: { id, kind: 'check', outcome: 'succeeded' } }) + }) + + it.each<[string, CliReply]>([ + ['a failed status command', { exitCode: 1, stderr: 'Error: failed to read user config' }], + ['a status this version does not print', { stdout: 'Signed in as ou_fixture\n' }], + ])('keeps the previous account and reports only the command and exit code on %s', async (_name, reply) => { + script[STATUS] = [reply] + const result = await settled(start('check')) + expect(result).toEqual({ + account: { state: 'unchecked', skills: 'installed' }, + result: { id: result.result?.id, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: reply.exitCode ?? 0 } }, + }) + expect(errors()).toEqual([['tencent-meeting: account operation failed: %o', { + id: result.result?.id, kind: 'check', phase: 'checking', command: 'auth-status', exitCode: reply.exitCode ?? 0, + }]]) + }) + + it('signs in through the authorization page, offers only trusted links, and confirms the sign-in', async () => { + script[STATUS] = [CONNECTED] + const login = Promise.withResolvers() + script[LOGIN] = (process) => { login.resolve(process) } + + const id = start('sign-in') + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing', cancellable: true }) + const authorizing = await login.promise + authorizing.write('stderr', `authorize url: ${LOGIN_LINK}\n`) + authorizing.write('stdout', '\nPlease open the following URL in your browser to authorize\n\n') + authorizing.write('stdout', 'authorize url: http://meeting.tencent.com/insecure\nauthorize url: https://evil.example/auth\n') + authorizing.write('stdout', `authorize url: ${LOGIN_LINK}\n\nwaiting for authorization...\n`) + await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: LOGIN_LINK }) }) + authorizing.reply({ stdout: 'Login successful. Start managing your meetings using tmeet.\n' }) + + expect(await settled(id)).toEqual({ + account: { state: 'connected', userName: '测试 用户', skills: 'installed' }, result: { id, kind: 'sign-in', outcome: 'succeeded' }, + }) + expect(commands()).toEqual([LOGIN, STATUS]) + expect(errors()).toEqual([]) + }) + + it.each<[string, Record, NonNullable['failure']]>([ + ['a failed sign-in', { [LOGIN]: [{ exitCode: 1, stdout: `authorize url: ${LOGIN_LINK}\n` }] }, { command: 'auth-login', exitCode: 1 }], + ['a sign-in the server did not confirm', { [LOGIN]: [{}], [STATUS]: [UNVERIFIED] }, { command: 'auth-status', exitCode: 0 }], + ])('fails on %s without exposing CLI output', async (_name, replies, failure) => { + Object.assign(script, replies) + const result = await settled(start('sign-in')) + expect(result.result).toMatchObject({ kind: 'sign-in', outcome: 'failed', failure }) + expect(JSON.stringify({ result, errors: errors() })).not.toContain('fixture-code') + }) + + it('cancels only while waiting for authorization and withdraws the link', async () => { + script[LOGIN] = (process) => { process.write('stdout', `authorize url: ${LOGIN_LINK}\n`) } + const id = start('sign-in') + await vi.waitFor(() => { expect(account.snapshot().operation?.authorizationUrl).toBe(LOGIN_LINK) }) + await account.cancel('other' as ConnectorOperationId) + expect(account.snapshot().operation?.phase).toBe('authorizing') + + const cancelling = account.cancel(id) + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'cancelling', cancellable: false }) + await cancelling + expect(account.snapshot()).toEqual({ account: { state: 'unchecked', skills: 'installed' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } }) + expect(subprocess.processes[0]?.terminated).toBe(true) + expect(errors()).toEqual([]) + }) + + it('signs out without cancellation, then checks again', async () => { + script[STATUS] = [NOT_LOGGED_IN] + const logout = Promise.withResolvers() + script[LOGOUT] = (process) => { logout.resolve(process) } + const id = start('sign-out') + const signingOut = await logout.promise + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-out', phase: 'signing-out', cancellable: false }) + await account.cancel(id) + signingOut.reply({ stdout: 'Logout success, welcome to use it again.\n' }) + + expect(await settled(id)).toEqual({ account: { state: 'signed-out', skills: 'installed' }, result: { id, kind: 'sign-out', outcome: 'succeeded' } }) + expect(commands()).toEqual([LOGOUT, STATUS]) + }) + + it('reports a failed sign-out without checking again', async () => { + script[LOGOUT] = [{ exitCode: 1, stderr: 'Error: logout failed' }] + const result = await settled(start('sign-out')) + expect(result.result).toMatchObject({ kind: 'sign-out', outcome: 'failed', failure: { command: 'auth-logout', exitCode: 1 } }) + expect(commands()).toEqual([LOGOUT]) + }) +}) + +describe('Tencent Meeting guide the plugin downloads', () => { + let home: string + /** Answers each request for the guide's archive. */ + let archive: () => Promise + + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-home-')) + vi.stubEnv('DSH_HOME', home) + vi.stubGlobal('fetch', () => archive()) + }) + + afterEach(() => rm(home, { recursive: true, force: true })) + + it('restarts a failed download of the guide on each check without waiting for it, and reports the state it leaves', async () => { + archive = () => Promise.reject(new Error('offline')) + await load({}) + await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }) + + archive = () => new Promise(() => {}) + script[STATUS] = [NOT_LOGGED_IN] + const id = start('check') + expect(account.snapshot().account).toEqual({ state: 'unchecked', skills: 'downloading' }) + expect(await settled(id)).toEqual({ account: { state: 'signed-out', skills: 'downloading' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + }) + + it('reports a new state of the guide with the current account', async () => { + const download = Promise.withResolvers() + archive = () => download.promise + await load({}) + script[STATUS] = [NOT_LOGGED_IN] + expect((await settled(start('check'))).account).toEqual({ state: 'signed-out', skills: 'downloading' }) + + download.reject(new Error('offline')) + + await vi.waitFor(() => { expect(account.snapshot().account).toEqual({ state: 'signed-out', skills: 'failed' }) }) + }) +}) + +describe('Tencent Meeting on the Plugins page', () => { + beforeEach(() => load()) + + const finished = async (id: ConnectorOperationId): Promise => (await settled(id)).result + + it('checks on refresh, then starts checks, sign-ins, and sign-outs one at a time and cancels a sign-in', async () => { + script[STATUS] = [NOT_LOGGED_IN] + account.refresh() + const check = account.snapshot().operation + expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked', skills: 'installed' }, operation: { kind: 'check' } }) + expect(await finished(check!.id)).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + expect(account.snapshot().account).toEqual({ state: 'signed-out', skills: 'installed' }) + expect(subprocess.lookups[0]?.command).toBe(join(binDir, executableFileName(process.platform))) + expect(await finished(start('check'))).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + + script[LOGIN] = () => {} + const signingIn = start('sign-in') + expect(() => start('check')).toThrow('another account operation is in progress') + await vi.waitFor(() => { expect(commands().at(-1)).toBe(LOGIN) }) + await account.cancel(signingIn) + expect(await finished(signingIn)).toMatchObject({ kind: 'sign-in', outcome: 'cancelled' }) + expect(subprocess.processes.at(-1)?.terminated).toBe(true) + + script[LOGOUT] = [{}] + expect(await finished(start('sign-out'))).toMatchObject({ kind: 'sign-out', outcome: 'succeeded' }) + }) + + it('stops account work on disposal', async () => { + script[STATUS] = () => {} + account.refresh() + await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) + await ctx.fiber.dispose() + expect(subprocess.processes[0]?.terminated).toBe(true) + }) +}) diff --git a/packages/connector/tencent-meeting/tests/directory.spec.ts b/packages/connector/tencent-meeting/tests/directory.spec.ts new file mode 100644 index 0000000000..6081a3db3b --- /dev/null +++ b/packages/connector/tencent-meeting/tests/directory.spec.ts @@ -0,0 +1,48 @@ +/** The managed executable: `tmeet` in a configured `binDir`, or the installed platform executable. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { expect, it, onTestFinished } from 'vitest' +import { executableFileName, resolveCliExecutable } from '../src/directory.ts' +import { createBinDir } from './harness.ts' + +const PLATFORM_EXECUTABLES: Readonly>> = { + 'darwin-arm64': 'tmeet-macOS-AppleSilicon', + 'darwin-x64': 'tmeet-macOS-Intel', + 'linux-arm64': 'tmeet-Linux-ARM64', + 'linux-x64': 'tmeet-Linux-x86_64', + 'win32-x64': 'tmeet-Windows-x86_64.exe', +} +const executable = PLATFORM_EXECUTABLES[`${process.platform}-${process.arch}`] +const PACKAGE_DIST = join(dirname(fileURLToPath(import.meta.resolve('@tencentcloud/tmeet/package.json'))), 'dist') +const FILE = process.platform === 'win32' ? 'tmeet.exe' : 'tmeet' + +it('names the executable file with the .exe extension on Windows only', () => { + expect(executableFileName('win32')).toBe('tmeet.exe') + expect(executableFileName('darwin')).toBe('tmeet') +}) + +it.runIf(executable !== undefined)('defaults to the installed platform executable', () => { + expect(resolveCliExecutable(undefined)).toBe(join(PACKAGE_DIST, executable!)) +}) + +it('names a platform the package ships no executable for', () => { + const arch = Object.getOwnPropertyDescriptor(process, 'arch')! + Object.defineProperty(process, 'arch', { ...arch, value: 'fixture-arch' }) + onTestFinished(() => { Object.defineProperty(process, 'arch', arch) }) + expect(() => resolveCliExecutable(undefined)) + .toThrow(`tencent-meeting: @tencentcloud/tmeet has no executable for ${process.platform}-fixture-arch; set binDir`) +}) + +it('accepts a configured directory and names its missing executable with the remedy', async () => { + const binDir = await createBinDir() + const empty = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-empty-')) + onTestFinished(async () => { + await rm(binDir, { recursive: true, force: true }) + await rm(empty, { recursive: true, force: true }) + }) + expect(resolveCliExecutable(binDir)).toBe(join(binDir, FILE)) + expect(() => resolveCliExecutable(empty)) + .toThrow(`tencent-meeting: ${join(empty, FILE)} is not executable; set binDir to a directory containing an executable ${FILE}`) +}) diff --git a/packages/connector/tencent-meeting/tests/harness.ts b/packages/connector/tencent-meeting/tests/harness.ts new file mode 100644 index 0000000000..9490ddad61 --- /dev/null +++ b/packages/connector/tencent-meeting/tests/harness.ts @@ -0,0 +1,164 @@ +/** + * A Host for Tencent Meeting plugin specs: scripted tmeet processes, a temporary bin directory and guide directory, and a + * recording Plugins page registry. + */ + +import { chmod, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { PassThrough } from 'node:stream' +import { Context } from '@deepseek-ai/cordis' +import CliAccounts from '@deepseek-ai/dsh-cli-account' +import type { ConnectorAccountRegistration } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import SkillRegistry from '@deepseek-ai/dsh-skill' +import { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import type { + SubprocessCollectedOutputs, + SubprocessHandle, + SubprocessOutcome, + SubprocessSpawnSpec, + SubprocessTerminalEnvironment, +} from '@deepseek-ai/dsh-subprocess' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import UpstreamSkills, { type Config as UpstreamSkillsConfig } from '@deepseek-ai/dsh-upstream-skills' +import { executableFileName } from '../src/directory.ts' +import type { TencentMeetingState } from '../src/types.ts' + +/** Output and exit facts one scripted command reports. */ +export interface CliReply { + stdout?: string + stderr?: string + exitCode?: number | null + signal?: NodeJS.Signals | null +} + +/** A piped process whose managed range exits on termination. */ +export class ScriptedProcess implements SubprocessHandle { + readonly stdin = undefined + readonly stdout = new PassThrough() + readonly stderr = new PassThrough() + readonly control = undefined + readonly collected: SubprocessCollectedOutputs = {} + readonly done: Promise + terminated = false + private readonly outcome = Promise.withResolvers() + private readonly exit = Promise.withResolvers() + + constructor(readonly spec: SubprocessSpawnSpec) { + this.done = this.outcome.promise + spec.signal?.addEventListener('abort', () => { this.terminate() }, { once: true }) + } + + /** Write output while the command keeps running. */ + write(stream: 'stdout' | 'stderr', text: string): void { + this[stream].write(text) + } + + /** Finish the command with the given output; the managed range stays alive until termination. */ + reply(reply: CliReply): void { + if (reply.stdout !== undefined) this.stdout.write(reply.stdout) + if (reply.stderr !== undefined) this.stderr.write(reply.stderr) + this.close() + this.outcome.resolve({ exitCode: reply.exitCode === undefined ? 0 : reply.exitCode, signal: reply.signal ?? null }) + } + + terminate(): void { + this.terminated = true + this.close() + this.outcome.resolve({ exitCode: null, signal: 'SIGTERM' }) + this.exit.resolve(true) + } + + private close(): void { + if (!this.stdout.writableEnded) this.stdout.end() + if (!this.stderr.writableEnded) this.stderr.end() + } + + waitForExit(): Promise { + return this.exit.promise + } +} + +/** Host subprocess runtime whose lookups and spawns are recorded and answered by `respond`. */ +export class ScriptedSubprocess extends SubprocessRuntime { + readonly lookups: Array<{ command: string; env: Readonly> | undefined }> = [] + readonly processes: ScriptedProcess[] = [] + lookup: (signal?: AbortSignal) => Promise = () => Promise.resolve('/fixture/bin/tmeet') + respond: (process: ScriptedProcess) => void | Promise = (process) => { process.reply({ stdout: '{}' }) } + + override resolveExecutable(command: string, env?: Readonly>, signal?: AbortSignal): Promise { + this.lookups.push({ command, env }) + return this.lookup(signal) + } + + override terminalEnvironment(): Promise { + return Promise.resolve({ platform: 'posix' }) + } + + override spawn(spec: SubprocessSpawnSpec): ScriptedProcess { + spec.signal?.throwIfAborted() + const process = new ScriptedProcess(spec) + this.processes.push(process) + queueMicrotask(() => { void this.respond(process) }) + return process + } + + override spawnTerminal(): Promise { + throw new Error('tmeet commands never allocate a terminal') + } +} + +/** + * Create a temporary directory holding an executable `tmeet` placeholder, `tmeet.exe` on Windows. + * @returns the absolute bin directory. + */ +export async function createBinDir(): Promise { + const directory = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-bin-')) + await writeFile(join(directory, executableFileName(process.platform)), '') + await chmod(join(directory, executableFileName(process.platform)), 0o755) + return directory +} + +/** What the Tencent Meeting plugin registers for the Plugins page. */ +export type TencentMeetingPage = ConnectorAccountRegistration + +/** The services the Tencent Meeting plugin runs on, before the plugin itself loads. */ +export interface TencentMeetingHost { + readonly ctx: Context + readonly subprocess: ScriptedSubprocess + /** The `binDir` to load the plugin with. */ + readonly binDir: string + /** An empty directory to load the plugin with as `skillsDir`, so that it downloads nothing. */ + readonly skillsDir: string + /** Every account registered for the Plugins page, in order; the registry keeps them after withdrawal. */ + readonly pages: TencentMeetingPage[] + /** How many of those accounts were withdrawn. */ + withdrawn: number +} + +/** + * Start a Host with the skill registry, a scripted subprocess runtime, the system prompt, a Plugins page registry that + * records registrations, the CLI account Service with a 5-second command deadline, and the upstream skills Service. + * @param skills - where the upstream skills Service downloads from; defaults to the Service's own defaults. + * @returns the Host; the caller loads the Tencent Meeting plugin with `binDir`, disposes `ctx.fiber`, and removes + * `binDir` and `skillsDir`. + */ +export async function createHost(skills: Partial = {}): Promise { + const ctx = new Context() + await ctx.plugin(SkillRegistry) + await ctx.plugin(ScriptedSubprocess) + await ctx.plugin(SystemPrompt) + const host: TencentMeetingHost = { + ctx, subprocess: ctx.subprocess as ScriptedSubprocess, binDir: await createBinDir(), + skillsDir: await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-skills-')), pages: [], withdrawn: 0, + } + ctx.provide('connectorAccounts', { + register: (page: TencentMeetingPage) => { + host.pages.push(page) + return () => { host.withdrawn += 1 } + }, + }) + await ctx.plugin(CliAccounts, { commandTimeoutMs: 5_000 }) + await ctx.plugin(UpstreamSkills, skills) + return host +} diff --git a/packages/connector/tencent-meeting/tests/plugin.spec.ts b/packages/connector/tencent-meeting/tests/plugin.spec.ts new file mode 100644 index 0000000000..63f4579922 --- /dev/null +++ b/packages/connector/tencent-meeting/tests/plugin.spec.ts @@ -0,0 +1,100 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { renderContextSections } from '@deepseek-ai/dsh-system-prompt' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cliPathContextText } from '@deepseek-ai/dsh-cli-account/src/context.ts' +import { executableFileName } from '../src/directory.ts' +import * as TencentMeeting from '../src/index.ts' +import { TENCENT_MEETING_PACKAGE } from '../src/presentation.ts' +import { createHost, type TencentMeetingHost } from './harness.ts' + +describe('Config', () => { + it('takes the CLI directory and the guide directory, which are optional and never empty', () => { + expect(TencentMeeting.Config({})).toEqual({}) + expect(TencentMeeting.Config({ binDir: '/opt/tmeet/bin', skillsDir: '/opt/tmeet/skills' })).toEqual({ binDir: '/opt/tmeet/bin', skillsDir: '/opt/tmeet/skills' }) + expect(() => TencentMeeting.Config({ binDir: '' })).toThrow() + expect(() => TencentMeeting.Config({ skillsDir: '' })).toThrow() + }) +}) + +describe('Tencent Meeting plugin', () => { + let host: TencentMeetingHost + let ctx: Context + let binDir: string + let skillsDir: string + + /** Start the Host the plugin loads on; the upstream skills Service downloads from `skills`. */ + async function start(skills?: Parameters[0]): Promise { + host = await createHost(skills) + ;({ ctx, binDir, skillsDir } = host) + } + + afterEach(async () => { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + await rm(binDir, { recursive: true, force: true }) + await rm(skillsDir, { recursive: true, force: true }) + }) + + const runtimeContext = async () => renderContextSections(await ctx.systemPrompt.assemble()) + + it('publishes one tencent-meeting entry skill over the configured guide, with a body that carries the DSH guidance', async () => { + await start() + await ctx.plugin(TencentMeeting, { binDir, skillsDir }) + + const catalog = await ctx.skills.list() + expect(catalog.map(skill => `${skill.provider}/${skill.source}/${skill.name}`)).toEqual(['tencent-meeting/bundled/tencent-meeting']) + + const entry = await ctx.skills.get('tencent-meeting') + expect(entry?.content).toContain('`tmeet` 由腾讯会议插件安装,按当前 runtime context 给出的绝对路径运行,不要直接按名称运行') + expect(entry?.content).toContain('跳过运行 `scripts/agent_init.py` 的要求') + expect(entry?.resourceBase).toEqual({ kind: 'directory', path: skillsDir }) + expect(await ctx.skills.get('tmeet-skill')).toBeUndefined() + }) + + it('reports the guide as downloading and then failed when no skills URL answers, and lists no skill', async () => { + const home = await mkdtemp(join(tmpdir(), 'dsh-tencent-meeting-home-')) + vi.stubEnv('DSH_HOME', home) + try { + await start({ skillsUrls: ['https://127.0.0.1:9'], skillsTimeoutMs: 5_000 }) + await ctx.plugin(TencentMeeting, { binDir }) + const account = host.pages[0]!.source + expect(account.snapshot().account.skills).toBe('downloading') + await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }, { timeout: 10_000 }) + expect(await ctx.skills.list()).toEqual([]) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('gives the executable path in runtime context, and withdraws it and the skills on disposal', async () => { + await start() + const fiber = await ctx.plugin(TencentMeeting, { binDir, skillsDir }) + expect(await runtimeContext()).toEqual([{ + name: 'tencent-meeting:cli', + text: cliPathContextText({ + product: 'Tencent Meeting', program: 'tmeet', executable: join(binDir, executableFileName(process.platform)), + }, process.platform), + }]) + expect(await ctx.skills.list()).not.toEqual([]) + + await fiber.dispose() + + expect(await runtimeContext()).toEqual([]) + expect(await ctx.skills.list()).toEqual([]) + }) + + it('shows the account on the Plugins page while the registry runs, and withdraws it with the plugin', async () => { + await start() + const fiber = await ctx.plugin(TencentMeeting, { binDir, skillsDir }) + expect(host.pages).toHaveLength(1) + expect(host.pages[0]).toMatchObject({ key: TENCENT_MEETING_PACKAGE, packageName: TENCENT_MEETING_PACKAGE }) + expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked', skills: 'installed' }) + + await fiber.dispose() + + expect(host.withdrawn).toBe(1) + }) +}) diff --git a/packages/connector/tencent-meeting/tests/presentation.spec.ts b/packages/connector/tencent-meeting/tests/presentation.spec.ts new file mode 100644 index 0000000000..6daab5ea6b --- /dev/null +++ b/packages/connector/tencent-meeting/tests/presentation.spec.ts @@ -0,0 +1,121 @@ +/** The Tencent Meeting section offers each state's next step, the guide download row, and failure guidance, in every shipped language. */ +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountDisplay, ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { rm } from 'node:fs/promises' +import { afterAll, beforeAll, expect, it } from 'vitest' +import * as TencentMeeting from '../src/index.ts' +import { en, zh, type TencentMeetingTextKey } from '../src/locales.ts' +import type { TencentMeetingState } from '../src/types.ts' +import { createHost, type TencentMeetingHost, type TencentMeetingPage } from './harness.ts' + +const OP = 'op' as ConnectorOperationId +const LINK = 'https://meeting.tencent.com/authorize' +const CHECK = { kind: 'start', operation: 'check' } as const +const SIGN_IN = { kind: 'start', operation: 'sign-in' } as const +const SIGN_OUT = { kind: 'start', operation: 'sign-out' } as const + +/** The key's text as the Chinese and English browsers resolve it. */ +const say = (key: TencentMeetingTextKey): Partial> => ({ zh: zh[key], en: en[key] }) +const zhOf = (text: LocalizedText | undefined): string | undefined => typeof text === 'object' ? text.zh : text +const labels = (display: ConnectorAccountDisplay): (string | undefined)[] => display.buttons.map(button => zhOf(button.label)) + +let host: TencentMeetingHost +/** What the plugin registered for the Plugins page, with the failure details the CLI account Service adds. */ +let page: TencentMeetingPage + +beforeAll(async () => { + host = await createHost() + await host.ctx.plugin(TencentMeeting, { binDir: host.binDir, skillsDir: host.skillsDir }) + page = host.pages[0]! +}) + +afterAll(async () => { + await host.ctx.fiber.dispose() + await rm(host.binDir, { recursive: true, force: true }) + await rm(host.skillsDir, { recursive: true, force: true }) +}) + +const presentAccount = (view: TencentMeetingState): ConnectorAccountDisplay => page.present(view) + +const SIGNED_OUT: TencentMeetingState = { account: { state: 'signed-out', skills: 'installed' } } +const CONNECTED: TencentMeetingState = { account: { state: 'connected', userName: '测试用户', skills: 'installed' } } + +it('offers the next step while signing in', () => { + let shown = presentAccount(SIGNED_OUT) + expect(shown).toMatchObject({ + phase: 'disconnected', status: say('status.disconnected'), badge: say('badge.disconnected'), + detail: say('detail.disconnected'), connect: SIGN_IN, notes: [], + }) + expect(shown.buttons).toMatchObject([{ label: say('action.connect'), command: SIGN_IN, variant: 'primary' }]) + + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'connecting', status: say('step.authorizing'), badge: say('badge.connecting') }) + expect(labels(shown)).toEqual([zh['action.cancel']]) + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', cancellable: true, authorizationUrl: LINK } }) + expect(shown.detail).toMatchObject(say('detail.authorizing')) + expect(shown.buttons.map(button => button.command)).toEqual([{ kind: 'open' }, { kind: 'cancel' }]) + + shown = presentAccount({ ...SIGNED_OUT, operation: { id: OP, kind: 'sign-in', phase: 'checking', cancellable: false } }) + expect(shown).toMatchObject({ status: say('step.connecting'), buttons: [] }) + + for (const view of [ + { ...SIGNED_OUT, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, + { account: { state: 'unchecked', skills: 'installed' } }, + ] as const satisfies readonly TencentMeetingState[]) { + shown = presentAccount(view) + expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [] }) + expect(shown.badge).toBeUndefined() + } +}) + +it('names the signed-in user and asks before signing out', () => { + let shown = presentAccount(CONNECTED) + expect(shown).toMatchObject({ phase: 'connected', status: say('status.connected'), badge: say('badge.connected') }) + expect(zhOf(shown.detail)).toBe(zh['detail.connected'].replace('{name}', '测试用户')) + expect(shown.buttons).toMatchObject([{ + label: say('action.signOut'), command: SIGN_OUT, + confirm: { title: say('signOut.title'), body: say('signOut.body'), label: say('action.signOut') }, + }]) + + shown = presentAccount({ ...CONNECTED, operation: { id: OP, kind: 'sign-out', phase: 'signing-out', cancellable: false } }) + expect(shown).toMatchObject({ status: say('step.signing-out'), buttons: [] }) + expect(shown.detail).toBeUndefined() +}) + +it('reports a failed sign-in with its diagnostic items, and no failure for a cancelled one', () => { + let shown = presentAccount({ ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'failed', failure: { command: 'auth-login', exitCode: 1 } } }) + expect(shown.failure).toMatchObject({ text: say('failed'), details: ['auth-login', 'exit 1'] }) + expect(labels(shown)).toEqual([zh['action.connect']]) + shown = presentAccount({ ...CONNECTED, result: { id: OP, kind: 'sign-out', outcome: 'failed' } }) + expect(shown.failure).toMatchObject({ text: say('failed') }) + expect(shown.failure).not.toHaveProperty('details') + expect(presentAccount({ ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'cancelled' } }).failure).toBeUndefined() +}) + +it('retries an unconfirmed or unreadable sign-in by checking again', () => { + for (const view of [ + { account: { state: 'unverified', skills: 'installed' } }, + { account: { state: 'unchecked', skills: 'installed' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 2 } } }, + ] as const satisfies readonly TencentMeetingState[]) { + const shown = presentAccount(view) + expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable') }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + } +}) + +it('reports a guide that is downloading, and retries a failed download by checking again', () => { + expect(presentAccount({ account: { state: 'signed-out', skills: 'downloading' } }).notes).toMatchObject([{ text: say('skills.downloading') }]) + const [note] = presentAccount({ account: { state: 'signed-out', skills: 'failed' } }).notes + expect(note).toMatchObject({ text: say('skills.failed'), button: { label: say('action.retry'), command: CHECK } }) +}) + +it('names the section, its activation prompt, and the notices of signing in and out', () => { + expect(page.copy).toMatchObject({ + title: say('section.title'), hint: say('hint'), + activation: { title: say('activation.title'), body: say('activation.body'), connect: say('action.connect') }, + }) + expect(page.operations).toMatchObject([ + { kind: 'check' }, { kind: 'sign-in', notice: say('notice.connected') }, { kind: 'sign-out', notice: say('notice.signed-out') }, + ]) + expect(page.operations[0]).not.toHaveProperty('notice') +}) diff --git a/packages/connector/tencent-meeting/tests/skills.spec.ts b/packages/connector/tencent-meeting/tests/skills.spec.ts new file mode 100644 index 0000000000..a1831c72ab --- /dev/null +++ b/packages/connector/tencent-meeting/tests/skills.spec.ts @@ -0,0 +1,38 @@ +/** The bundled entry skill: its index names exactly the pinned upstream guide, and it reaches the model below the pruner threshold. */ +import { readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { renderSkillContent } from '@deepseek-ai/dsh-skill' +import { expect, it } from 'vitest' + +const entry = fileURLToPath(new URL('../skills/tencent-meeting/', import.meta.url)) + +/** The `skills//SKILL.md` directories of the pinned selection, as `scripts/upstream-skills-digest.ts` lists them. */ +const PINNED_GUIDES = ['tmeet-skill'] + +/** + * `packages/bundle/web-app/presets/standard.patch.yml` prunes a tool result only above `thresholdChars: 8192` + * code points; a skill result below it reaches the model intact. + */ +const PRUNER_THRESHOLD_CHARS = 8192 + +/** The body the `skill` tool returns: the file without its YAML frontmatter. */ +function body(): string { + const text = readFileSync(join(entry, 'SKILL.md'), 'utf8') + const end = text.indexOf('\n---\n', 4) + return text.slice(end + '\n---\n'.length) +} + +it('ships only the tencent-meeting entry at the bundled skill root', () => { + expect(readdirSync(fileURLToPath(new URL('../skills/', import.meta.url)))).toEqual(['tencent-meeting']) +}) + +it('renders the entry below the pruner threshold', () => { + const rendered = renderSkillContent({ name: 'tencent-meeting', provider: 'tencent-meeting', resourceBase: { kind: 'directory', path: entry }, content: body() }) + expect(Array.from(rendered).length).toBeLessThan(PRUNER_THRESHOLD_CHARS) +}) + +it('indexes the guide of the pinned selection exactly once', () => { + const indexed = [...body().matchAll(/^- `([a-z-]+)`:/gmu)].map(match => match[1] ?? '') + expect(indexed.toSorted()).toEqual(PINNED_GUIDES) +}) diff --git a/packages/connector/tencent-meeting/tsconfig.json b/packages/connector/tencent-meeting/tsconfig.json new file mode 100644 index 0000000000..be98936daf --- /dev/null +++ b/packages/connector/tencent-meeting/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../upstream-skills" + }, + { + "path": "../../util/values" + }, + { + "path": "../cli-account" + }, + { + "path": "../../client/ui-connector-account/tsconfig.host.json" + } + ] +} diff --git a/packages/connector/upstream-skills/README.i18n.yaml b/packages/connector/upstream-skills/README.i18n.yaml index 6821d0e50c..3889c9128b 100644 --- a/packages/connector/upstream-skills/README.i18n.yaml +++ b/packages/connector/upstream-skills/README.i18n.yaml @@ -24,11 +24,14 @@ en: 2ac0be96902c0c7c zh: a6412287a1ac4487 /deepseek-ai-dsh-upstream-skills/use-this-package/register-an-entry-skill: - en: a4adb17bd22ccf36 - zh: 0afd5dbd5e6d4c11 + en: 61da62916206ff64 + zh: 0aff27fbd61238ae /deepseek-ai-dsh-upstream-skills/use-this-package/kept-files-and-verification: en: 0633b5470e6b4e6c zh: 419916b5b305aa7d +/deepseek-ai-dsh-upstream-skills/use-this-package/replaced-pins: + en: 543da0e2871bec3d + zh: ed80c0c59040440b /deepseek-ai-dsh-upstream-skills/use-this-package/pinning-a-commit: en: ea5587081cc3b471 zh: e0993a154ae79dc1 @@ -45,8 +48,8 @@ en: 2a09699bc1130758 zh: 972fc624936c8c2f /deepseek-ai-dsh-upstream-skills/known-limitations-and-deferred-work: - en: 31293ef35d3c40da - zh: db7b8e190085008e + en: 25e90bc332e990a7 + zh: 3a4a3face42b5c13 /deepseek-ai-dsh-upstream-skills/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/connector/upstream-skills/README.md b/packages/connector/upstream-skills/README.md index 7bdaccdaeb..24740cd9af 100644 --- a/packages/connector/upstream-skills/README.md +++ b/packages/connector/upstream-skills/README.md @@ -88,12 +88,16 @@ export function apply(ctx: Context, config: Config): void { - `set` is the pin that `scripts/upstream-skills-digest.ts` prints. - `skillsDir` is the plugin's own optional config field: a directory that already holds the kept files at their repository paths. When it is set, nothing is downloaded, and a path that is not a directory makes `register` throw. -The returned handle serves the plugin's account view and check. `directory` is `skillsDir`, or `$DSH_HOME/cache//skills-`. `state` is `downloading` while a download runs, otherwise `installed` when that directory exists and `failed` when it does not. `watch(listener)` reports each start and end of a download, and `retry()` starts another download after a failure and returns at once. A plugin shows the state beside its account and calls `retry()` from its check without waiting, so a slow download never holds its account operations. A failed download is logged as a warning. `dispose()` withdraws the registration before the plugin unloads. The contracts in [`src/index.ts`](src/index.ts) and [`src/types.ts`](src/types.ts) are authoritative. +The returned handle serves the plugin's account view and check. `directory` is `skillsDir`; otherwise it is `$DSH_HOME/cache///skills-` in a profile and `$DSH_HOME/cache//skills-` without one. `state` is `downloading` while a download runs, otherwise `installed` when that directory exists and `failed` when it does not. `watch(listener)` reports each start and end of a download, and `retry()` starts another download after a failure and returns at once. A plugin shows the state beside its account and calls `retry()` from its check without waiting, so a slow download never holds its account operations. A failed download is logged as a warning. `dispose()` withdraws the registration before the plugin unloads. The contracts in [`src/index.ts`](src/index.ts) and [`src/types.ts`](src/types.ts) are authoritative. ### Kept files and verification The Service downloads `///tar.gz/` from each `skillsUrls` prefix in order. A prefix that answers with an error status or no body, does not deliver the whole archive within `skillsTimeoutMs`, sends a malformed archive, or sends files that differ from the pin is logged with the prefix, and the next prefix is tried; unloading the plugin stops at once. The Service keeps every regular file under `directory` except the paths in `exclude`, plus `license`, at their repository paths. It refuses an archive with an empty, `.`, or `..` path segment or a backslash in any entry, entries outside its one top-level directory, a kept path that is a link or appears twice, kept files above `bytes`, or no license file. On Windows, node-tar turns backslashes into slashes before the Service reads a path, so the segments they separate are checked instead. The digest hashes each kept file's path, byte length, and content in path order, because GitHub keeps the files of a commit archive stable but not its compressed bytes. Verified files are written to a sibling staging directory, which is then renamed to the handle's `directory`; a directory that another process, such as Desktop beside Web, published first is kept. +### Replaced pins + +Each profile that `dsh` launches has a directory of its own for a plugin's files, `$DSH_HOME/cache//`, which the processes of that profile share. A registration deletes the other pins of that directory once, the first time its own pin is in place there: already at load, or after its download. A plugin update that changes the pin therefore leaves one copy, and the earlier pin stays until the new one is published. The deletion runs in the background, and neither `register` nor the end of a download waits for it; a pin that cannot be deleted is logged as a warning and deleted at a later load. Because a registration deletes the other pins only once, a process whose pin another process of the profile deleted downloads it again at its next check and leaves that process's pin in place; [Known Limitations](#known-limitations-and-deferred-work) describes that case. A composition that `dsh` did not launch has no profile: its pins stay in `$DSH_HOME/cache/`, which several installations may share, and none is deleted. A configured `skillsDir` and its sibling directories are never deleted. + ### Pinning a commit `pnpm exec tsx scripts/upstream-skills-digest.ts --repository / --commit --directory [--exclude ]... [--license LICENSE] [--url ]` downloads the archive from the `--url` prefix, `https://codeload.github.com` by default, keeps the same files, prints the pin as JSON, and lists the kept `SKILL.md` paths on stderr. @@ -143,7 +147,10 @@ A load that finds the files in place lists the entry in the session's first cata - The first load after a new pin needs GitHub or a configured mirror; until a download succeeds, the entry skill is not listed and the plugin shows the `failed` state. -- Published directories stay in `$DSH_HOME/cache/` after a plugin pins another commit and after the plugin is removed; nothing prunes them. A process that exits while it writes a download leaves its `.skills--` staging directory there too. +- Each profile that loads a plugin downloads its own copy of the pin. +- Processes of one profile can run different versions of a plugin at the same time, such as one started before a plugin update and one started after it. The later one deletes the pin the earlier one reads: the earlier process lists no entry skill, and its agents cannot open the guides, until its next check has downloaded the pin again. Both pins then stay until a process of the profile loads the plugin again. +- Removing a plugin leaves its pin in the cache. A process that exits while it writes a download leaves its `.skills--` staging directory there too. Nothing deletes either. +- Without a profile, every pin stays in `$DSH_HOME/cache/` after the plugin pins another commit. - Only the published directory's existence is checked. When files inside it are deleted or changed, the entry skill stays listed over them; deleting the directory makes the next check or load download the pin again. - File modes are not kept, so an upstream script is not executable; the current upstream guides run their scripts through `python3`. - In the experimental Web preview, which runs Host plugins in a browser worker, the Service loads but node-tar does not, so every download fails there. diff --git a/packages/connector/upstream-skills/README.zh.md b/packages/connector/upstream-skills/README.zh.md index 3fbad286db..ab508ee612 100644 --- a/packages/connector/upstream-skills/README.zh.md +++ b/packages/connector/upstream-skills/README.zh.md @@ -88,12 +88,16 @@ export function apply(ctx: Context, config: Config): void { - `set` 是 `scripts/upstream-skills-digest.ts` 输出的固定信息。 - `skillsDir` 是插件自己的可选配置字段:一个已按仓库路径存放保留文件的目录。设置后不下载,路径不是目录时 `register` 抛出异常。 -返回的句柄供插件的账号视图和检查使用。`directory` 是 `skillsDir`,或 `$DSH_HOME/cache//skills-<摘要前 16 位>`。下载进行中时 `state` 为 `downloading`,否则这个目录存在时为 `installed`,不存在时为 `failed`。`watch(listener)` 报告每次下载的开始和结束;`retry()` 在失败后开始新的下载,并立即返回。插件在账号旁显示这个状态,并在检查中调用 `retry()` 而不等待,因此下载再慢也不会占住账号操作。下载失败会记为警告。`dispose()` 在插件卸载之前撤回注册。以 [`src/index.ts`](src/index.ts) 和 [`src/types.ts`](src/types.ts) 中的约定为准。 +返回的句柄供插件的账号视图和检查使用。`directory` 是 `skillsDir`;没有设置时,在 profile 中是 `$DSH_HOME/cache///skills-<摘要前 16 位>`,没有 profile 时是 `$DSH_HOME/cache//skills-<摘要前 16 位>`。下载进行中时 `state` 为 `downloading`,否则这个目录存在时为 `installed`,不存在时为 `failed`。`watch(listener)` 报告每次下载的开始和结束;`retry()` 在失败后开始新的下载,并立即返回。插件在账号旁显示这个状态,并在检查中调用 `retry()` 而不等待,因此下载再慢也不会占住账号操作。下载失败会记为警告。`dispose()` 在插件卸载之前撤回注册。以 [`src/index.ts`](src/index.ts) 和 [`src/types.ts`](src/types.ts) 中的约定为准。 ### 保留的文件与校验 Service 按顺序从每个 `skillsUrls` 前缀下载 `<前缀>///tar.gz/`。某个前缀返回错误状态或空响应体、没有在 `skillsTimeoutMs` 内送达完整归档、发来损坏的归档,或发来的文件与固定信息不符时,记录该前缀并尝试下一个;卸载插件则立即停止。Service 保留 `directory` 下除 `exclude` 列出的路径之外的所有普通文件,以及 `license`,并保持它们的仓库路径。以下归档会被拒绝:任一条目的路径含空段、`.`、`..` 或反斜杠;条目不在唯一的顶层目录下;保留的路径是链接或出现两次;保留的文件超过 `bytes`;没有许可证文件。Windows 上 node-tar 在 Service 读取路径之前已把反斜杠转成 `/`,因此改为检查它分开的各段。摘要按路径顺序对每个保留文件的路径、字节长度和内容做哈希,因为 GitHub 保证提交归档里的文件不变,但不保证压缩后的字节不变。校验通过的文件先写入同级的暂存目录,再改名为句柄的 `directory`;另一个进程(例如与 Web 同时运行的桌面端)先发布的目录会被保留。 +### 替换旧的固定提交 + +每个由 `dsh` 启动的 profile 为每个插件的文件保留自己的目录 `$DSH_HOME/cache//`,这个 profile 的各个进程共用它。一次注册只删除一次该目录下其他固定提交的目录,时机是它自己的固定提交第一次在那里就位时:加载时已在位,或下载完成后。因此插件更新换了固定提交之后只留下一份,新的固定提交发布之前,旧的保持不动。删除在后台进行,`register` 和下载的结束都不等待它;无法删除的目录记为警告,留到之后的加载时再删。由于一次注册只删除一次,某个进程的固定提交被同一 profile 的另一个进程删除后,它在下一次检查时重新下载,并保留那个进程的固定提交;这种情况见[已知限制](#known-limitations-and-deferred-work)。不是由 `dsh` 启动的组合没有 profile:它的固定提交都留在可能被多个安装共用的 `$DSH_HOME/cache/` 中,一个也不删除。配置的 `skillsDir` 及其同级目录从不删除。 + ### 固定提交 `pnpm exec tsx scripts/upstream-skills-digest.ts --repository / --commit <完整提交号> --directory <路径> [--exclude <路径>]... [--license LICENSE] [--url <前缀>]` 从 `--url` 前缀下载归档(默认是 `https://codeload.github.com`),按同样规则保留文件,以 JSON 输出固定信息,并在 stderr 列出保留的 `SKILL.md` 路径。 @@ -143,7 +147,10 @@ Service 按顺序从每个 `skillsUrls` 前缀下载 `<前缀>// - 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,入口技能不会列出,插件显示 `failed` 状态。 -- 插件改为固定其他提交后,以及插件卸载后,已发布的目录仍留在 `$DSH_HOME/cache/` 中,没有任何清理。进程在写入下载内容时退出,也会在那里留下它的暂存目录 `.skills-<摘要>-`。 +- 每个加载该插件的 profile 都各自下载一份固定提交。 +- 同一个 profile 的多个进程可以同时运行同一插件的不同版本,例如一个在插件更新之前启动,另一个在更新之后启动。后启动的进程会删除先启动的进程正在读取的固定提交:先启动的进程不再列出入口技能,其中的 Agent 也打不开子指南,直到它下一次检查重新下载完成。此后两个固定提交都保留,直到这个 profile 的某个进程再次加载该插件。 +- 移除插件后,它的固定提交仍留在缓存中。进程在写入下载内容时退出,也会在那里留下它的暂存目录 `.skills-<摘要>-`。两者都不会被删除。 +- 没有 profile 时,插件改为固定其他提交后,所有固定提交都留在 `$DSH_HOME/cache/` 中。 - 只检查已发布的目录是否存在。目录里的文件被删除或改动后,入口技能仍会基于这些文件列出;删除该目录后,下一次检查或加载会重新下载固定的提交。 - 不保留文件权限,上游脚本不可直接执行;目前的上游子指南都通过 `python3` 运行脚本。 - 实验性 Web 预览把 Host 插件运行在浏览器 worker 中:服务可以加载,但 node-tar 无法加载,因此那里的每次下载都会失败。 diff --git a/packages/connector/upstream-skills/package.json b/packages/connector/upstream-skills/package.json index 31015f2211..d48eaa3b55 100644 --- a/packages/connector/upstream-skills/package.json +++ b/packages/connector/upstream-skills/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-upstream-skills", "description": "Host Service of CLI app plugins: each plugin registers its entry skill and a pinned directory of the vendor's GitHub repository, and the Service downloads that directory into the DSH cache and lists the entry skill over it", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -47,6 +47,7 @@ }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-app-boot": "workspace:*", "@deepseek-ai/dsh-skill": "workspace:*" } } diff --git a/packages/connector/upstream-skills/src/index.ts b/packages/connector/upstream-skills/src/index.ts index b9bcc09f51..d4deab4914 100644 --- a/packages/connector/upstream-skills/src/index.ts +++ b/packages/connector/upstream-skills/src/index.ts @@ -1,16 +1,19 @@ /** * Upstream skills of CLI app plugins: the Host Service `ctx.upstreamSkills` downloads the files that a plugin's entry * skill indexes from one directory of the vendor's GitHub repository at a pinned commit, verifies them, publishes them - * in the DSH cache, and lists the entry skill over them once they are there. + * in the DSH cache, and lists the entry skill over them once they are there. In a profile, each plugin's files have + * a directory of their own, from which a registration deletes the other pins once its own pin is in place. * @module @deepseek-ai/dsh-upstream-skills */ import { randomUUID } from 'node:crypto' import { readFileSync, statSync } from 'node:fs' -import { mkdir, rename, rm } from 'node:fs/promises' +import { mkdir, readdir, rename, rm } from 'node:fs/promises' import { basename, dirname, join, resolve } from 'node:path' import { Service, type Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' +// Also declares `Context.profileContext`, the launcher-provided profile that owns a plugin's downloads. +import type { ProfileContext } from '@deepseek-ai/dsh-app-boot' import { dshCachePath } from '@deepseek-ai/dsh-home-paths' import { BUNDLED_SKILL_RANK, isSkillName } from '@deepseek-ai/dsh-skill' import type { SkillCandidate, SkillDefinition, SkillProvider, SkillProviderControl } from '@deepseek-ai/dsh-skill' @@ -61,8 +64,9 @@ export default class UpstreamSkills extends Service { /** * Register the calling plugin's entry skill and start downloading the upstream files unless they are in place. The * download starts at load so that a session without a client also gets the skill; a failure is logged as a warning - * and waits for `retry()`. The registration belongs to the calling plugin: unloading that plugin aborts the download - * and removes the entry skill. + * and waits for `retry()`. In a profile, the files go to that profile's own directory for the plugin, and the + * registration deletes the other pins there once, the first time its own pin is in place. The registration belongs + * to the calling plugin: unloading that plugin aborts the download and removes the entry skill. * @param registration - the plugin's provider name, entry, pinned files, and optional skills directory. * @returns the handle the plugin's view observes and its check retries. * @throws when the entry has no skill name or description in its frontmatter, `skillsDir` is not a directory, or a @@ -72,10 +76,11 @@ export default class UpstreamSkills extends Service { const caller = this.ctx let provider!: UpstreamSkillProvider const withdraw = caller.skills.registerProvider((control) => { - provider = new UpstreamSkillProvider(registration, this.config, control, caller.logger) + provider = new UpstreamSkillProvider(registration, this.config, control, caller.logger, caller.get('profileContext')) return provider }) provider.retry() + provider.prune() return { directory: provider.directory, get state() { return provider.state }, @@ -86,10 +91,21 @@ export default class UpstreamSkills extends Service { } } +/** The prefix of the directory name a pin is published under; the first 16 digits of its digest follow. */ +const PIN_PREFIX = 'skills-' + /** Lists the entry skill while its upstream files are in place, and owns their download. */ class UpstreamSkillProvider implements SkillProvider { readonly name: string readonly directory: string + /** + * The profile's own directory for this plugin, from which {@link prune} deletes the other pins; the processes of + * the profile share it. Undefined for a configured `skillsDir` and without a profile, where pins share + * `$DSH_HOME/cache/` and all stay. + */ + private readonly pins: string | undefined + /** Whether this registration has started deleting the other pins, which it does once. */ + private pruned = false private readonly candidate: SkillCandidate private readonly content: string private readonly listeners = new Set<(state: UpstreamSkillsState) => void>() @@ -100,15 +116,21 @@ class UpstreamSkillProvider implements SkillProvider { private readonly config: Config, private readonly control: SkillProviderControl, private readonly logger: Context['logger'], + profile: ProfileContext | undefined, ) { this.name = options.name const { skillsDir } = options - if (skillsDir === undefined) { - this.directory = dshCachePath(options.name, `skills-${options.set.sha256.slice(0, 16)}`) - } else { + const pin = `${PIN_PREFIX}${options.set.sha256.slice(0, 16)}` + if (skillsDir !== undefined) { this.directory = resolve(skillsDir) const remedy = `set it to a directory holding the files of ${options.set.directory} at their repository paths` if (!this.installed()) throw new Error(`${options.name}: skillsDir ${skillsDir} is not a directory; ${remedy}`) + } else if (profile === undefined) { + this.directory = dshCachePath(options.name, pin) + } else { + // Only this profile's processes read these pins; one that still runs another plugin version loses its pin. + this.pins = dshCachePath({ dshHome: profile.home }, options.name, profile.name) + this.directory = join(this.pins, pin) } const entry = readEntry(options) this.content = entry.content @@ -160,7 +182,30 @@ class UpstreamSkillProvider implements SkillProvider { }, ).finally(() => { this.running = false - if (!signal.aborted) this.notify() + if (signal.aborted) return + this.notify() + this.prune() + }) + } + + /** + * Start deleting the other pins from the profile's own directory, once per registration: the first time this pin is + * in place there. It returns at once, and does nothing without a profile, for a configured `skillsDir`, or after it + * has started once. A registration whose pin a process running another plugin version deleted therefore downloads + * it again without deleting that process's pin. A pin that cannot be deleted is logged as a warning and stays until + * a later load. + */ + prune(): void { + const { pins } = this + if (pins === undefined || this.pruned || !this.installed()) return + this.pruned = true + const current = basename(this.directory) + void readdir(pins).then(async (names) => { + for (const name of names) { + if (name !== current && name.startsWith(PIN_PREFIX)) await rm(join(pins, name), { recursive: true, force: true }) + } + }).catch((error: unknown) => { + this.logger.warn(`${this.name}: could not delete the upstream skills this pin replaces`, error) }) } diff --git a/packages/connector/upstream-skills/tests/service.spec.ts b/packages/connector/upstream-skills/tests/service.spec.ts index e5ec3584d0..3855909d38 100644 --- a/packages/connector/upstream-skills/tests/service.spec.ts +++ b/packages/connector/upstream-skills/tests/service.spec.ts @@ -1,14 +1,22 @@ -/** `ctx.upstreamSkills` lists a plugin's entry skill over its upstream files: a configured directory, downloads, retries, withdrawal. */ -import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' +/** + * `ctx.upstreamSkills` lists a plugin's entry skill over its upstream files: a configured directory, downloads, retries, + * withdrawal, and a profile's own directory, where the pin in place replaces the earlier ones. + */ +import { mkdir, mkdtemp, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' +import type { ProfileContext } from '@deepseek-ai/dsh-app-boot' import SkillRegistry from '@deepseek-ai/dsh-skill' import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import UpstreamSkills, { type Config, type UpstreamSkillsHandle, type UpstreamSkillSet, type UpstreamSkillsState } from '../src/index.ts' import { KEPT, archivePath, pin, repository, serve, startHost, type ArchiveHost } from './harness.ts' const renameHook = vi.hoisted(() => ({ before: undefined as ((from: string, to: string) => Promise) | undefined })) +/** The one path whose removal fails with the given error, as a directory in use does on Windows. */ +const removeHook = vi.hoisted(() => ({ refused: undefined as { readonly path: string; readonly error: Error } | undefined })) +/** Every directory listed through `readdir`, by the Service or by a test, in call order. */ +const listHook = vi.hoisted(() => ({ listed: [] as string[] })) vi.mock('node:fs/promises', async (importOriginal) => { const actual = await importOriginal() return { @@ -19,6 +27,14 @@ vi.mock('node:fs/promises', async (importOriginal) => { await before?.(from, to) return actual.rename(from, to) }, + rm: async (...args: Parameters) => { + if (removeHook.refused?.path === args[0]) throw removeHook.refused.error + return actual.rm(...args) + }, + readdir: (path: string) => { + listHook.listed.push(path) + return actual.readdir(path) + }, } }) @@ -67,13 +83,18 @@ afterEach(async () => { vi.unstubAllEnvs() vi.unstubAllGlobals() renameHook.before = undefined + removeHook.refused = undefined + listHook.listed.length = 0 await ctx.fiber.dispose() await rm(home, { recursive: true, force: true }) }) const set = pin() +/** The directory name the pin is published under, and the name of a pin an earlier plugin version published. */ +const CURRENT = `skills-${set.sha256.slice(0, 16)}` +const EARLIER = 'skills-0123456789abcdef' const cache = () => join(home, 'cache', 'vendor') -const published = () => join(cache(), `skills-${set.sha256.slice(0, 16)}`) +const published = () => join(cache(), CURRENT) const warning = (message: unknown, error: unknown) => ({ message, error }) const logged = () => ctx.logger.buffer.filter(entry => entry.type === 'warn').map(entry => warning(entry.args[0], entry.args[1])) const warnings = (): unknown[] => logged().map(({ message }) => message) @@ -184,10 +205,19 @@ describe('register', () => { expect(await ctx.skills.list()).toEqual(listed(published())) for (const [path, content] of Object.entries(KEPT)) expect(await readFile(join(published(), path), 'utf8')).toBe(content) expect((await readdir(join(published(), 'skills', 'alpha'))).toSorted()).toEqual(['SKILL.md', 'references']) - expect(await readdir(cache())).toEqual([`skills-${set.sha256.slice(0, 16)}`]) + expect(await readdir(cache())).toEqual([CURRENT]) expect(host.requests).toEqual([archivePath(set)]) }) + it('keeps every pin of the shared directory, which no profile owns', async () => { + await mkdir(join(cache(), EARLIER), { recursive: true }) + host.routes[archivePath(set)] = serve(repository()) + const skills = register() + expect(await settled(skills)).toBe('installed') + expect(await ctx.skills.list()).toEqual(listed(published())) + expect((await readdir(cache())).toSorted()).toEqual([EARLIER, CURRENT].toSorted()) + }) + it('tries the next skills URL after one fails and logs the failed prefix', async () => { host.routes[archivePath(set, '/mirror')] = serve(repository()) await sources({ skillsUrls: [`${BASE}/missing`, `${BASE}/mirror/`] }) @@ -265,7 +295,7 @@ describe('register', () => { const skills = register() expect(await settled(skills)).toBe('installed') expect(await readdir(published())).toEqual(['other']) - expect(await readdir(cache())).toEqual([`skills-${set.sha256.slice(0, 16)}`]) + expect(await readdir(cache())).toEqual([CURRENT]) }) it('lists the entry when another process publishes the directory while this download fails', async () => { @@ -346,3 +376,108 @@ describe('register', () => { expect(await ctx.skills.list()).toEqual([]) }) }) + +describe('register in a profile', () => { + /** The Harness home of the profile, which differs from `$DSH_HOME` here. */ + const harness = () => join(home, 'harness') + /** The directory of the `web` profile for the plugin. */ + const pins = () => join(harness(), 'cache', 'vendor', 'web') + const entries = async (directory: string) => (await readdir(directory)).toSorted() + + beforeEach(() => { + const dir = join(harness(), 'profiles', 'web') + const profile: ProfileContext = { + name: 'web', dir, patchPath: join(dir, 'cordis.patch.yml'), installAnchor: dir, cwd: home, home: harness(), + startedBundles: [], overlayPaths: [], telemetryDisabledEnv: undefined, + } + ctx.provide('profileContext', profile) + }) + + it('publishes into the directory of the profile for the plugin, under the Harness home of the profile', async () => { + host.routes[archivePath(set)] = serve(repository()) + const skills = register() + expect(skills.directory).toBe(join(pins(), CURRENT)) + expect(await settled(skills)).toBe('installed') + expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) + for (const [path, content] of Object.entries(KEPT)) expect(await readFile(join(pins(), CURRENT, path), 'utf8')).toBe(content) + expect(await readdir(pins())).toEqual([CURRENT]) + expect(await readdir(home)).toEqual(['harness']) + }) + + it('replaces the earlier pins of that directory once the new pin is published, and deletes nothing else', async () => { + const staging = `.${CURRENT}-of-a-running-download` + const untouched = [join(pins(), staging), join(pins(), '..', 'desktop', EARLIER), join(cache(), EARLIER)] + for (const directory of [join(pins(), EARLIER), ...untouched]) await mkdir(directory, { recursive: true }) + host.routes[archivePath(set)] = gated(repository()) + const skills = register() + expect(skills.state).toBe('downloading') + expect(await entries(pins())).toEqual([staging, EARLIER].toSorted()) + release() + expect(await settled(skills)).toBe('installed') + await vi.waitFor(async () => { expect(await entries(pins())).toEqual([staging, CURRENT].toSorted()) }) + for (const directory of untouched) expect((await stat(directory)).isDirectory()).toBe(true) + expect(warnings()).toEqual([]) + }) + + it('replaces the earlier pins at load when the pin is already in place, without a download', async () => { + for (const name of [CURRENT, EARLIER]) await mkdir(join(pins(), name), { recursive: true }) + const skills = register() + expect(skills.state).toBe('installed') + await vi.waitFor(async () => { expect(await readdir(pins())).toEqual([CURRENT]) }) + expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) + expect(host.requests).toEqual([]) + }) + + it('deletes the other pins once: it downloads a pin another process deleted again and keeps that process\'s pin', async () => { + const other = 'skills-fedcba9876543210' + await mkdir(join(pins(), EARLIER), { recursive: true }) + host.routes[archivePath(set)] = serve(repository()) + const skills = register() + expect(await settled(skills)).toBe('installed') + await vi.waitFor(async () => { expect(await readdir(pins())).toEqual([CURRENT]) }) + + // Another process of the profile, running another plugin version, publishes its pin and deletes this one. + await mkdir(join(pins(), other)) + await rm(join(pins(), CURRENT), { recursive: true }) + expect(skills.state).toBe('failed') + const before = listHook.listed.length + skills.retry() + expect(await settled(skills)).toBe('installed') + + // The deletion starts by listing the directory, in the same turn in which the download settles. + expect(listHook.listed.slice(before)).not.toContain(pins()) + expect(await entries(pins())).toEqual([CURRENT, other].toSorted()) + expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) + expect(host.requests).toEqual([archivePath(set), archivePath(set)]) + }) + + it('keeps the earlier pin while the new one cannot be downloaded', async () => { + await mkdir(join(pins(), EARLIER), { recursive: true }) + host.routes[archivePath(set)] = (response) => { response.writeHead(500).end() } + const skills = register() + expect(await settled(skills)).toBe('failed') + expect(await readdir(pins())).toEqual([EARLIER]) + }) + + it('logs an earlier pin that cannot be deleted, keeps it, and still lists the entry', async () => { + for (const name of [CURRENT, EARLIER]) await mkdir(join(pins(), name), { recursive: true }) + const refused = Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }) + removeHook.refused = { path: join(pins(), EARLIER), error: refused } + register() + await vi.waitFor(() => { + expect(logged()).toEqual([warning('vendor: could not delete the upstream skills this pin replaces', refused)]) + }) + expect(await entries(pins())).toEqual([EARLIER, CURRENT].toSorted()) + expect(await ctx.skills.list()).toEqual(listed(join(pins(), CURRENT))) + }) + + it('leaves a configured skills directory and its siblings as they are', async () => { + const configured = join(pins(), CURRENT) + for (const name of [CURRENT, EARLIER]) await mkdir(join(pins(), name), { recursive: true }) + const skills = register(configured) + expect(skills.directory).toBe(configured) + expect(await ctx.skills.list()).toEqual(listed(configured)) + expect(await entries(pins())).toEqual([EARLIER, CURRENT].toSorted()) + expect(host.requests).toEqual([]) + }) +}) diff --git a/packages/connector/upstream-skills/tsconfig.json b/packages/connector/upstream-skills/tsconfig.json index 58e8ce6696..45161612bc 100644 --- a/packages/connector/upstream-skills/tsconfig.json +++ b/packages/connector/upstream-skills/tsconfig.json @@ -14,6 +14,9 @@ { "path": "../../../vendor/schemastery" }, + { + "path": "../../boot/app-boot" + }, { "path": "../../util/home-paths" }, diff --git a/packages/connector/wecom/README.i18n.yaml b/packages/connector/wecom/README.i18n.yaml new file mode 100644 index 0000000000..1859149b15 --- /dev/null +++ b/packages/connector/wecom/README.i18n.yaml @@ -0,0 +1,88 @@ +# 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/connector/wecom/README.md +/: + en: 61517a3b25e2a2c5 + zh: 55ef5e89541516e0 +/deepseek-ai-dsh-wecom: + en: 97ebb140059d2cd9 + zh: b9753254b9a084f3 +/deepseek-ai-dsh-wecom/summary: + en: 06358926dfdfecee + zh: 5ae37704e7983a03 +/deepseek-ai-dsh-wecom/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-wecom/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-wecom/use-this-package/install-into-a-profile: + en: 6227d6e43ec8c108 + zh: 48e0f252de253d14 +/deepseek-ai-dsh-wecom/use-this-package/what-you-get: + en: 7581623b2b257fe0 + zh: cdd670dfd6d0183d +/deepseek-ai-dsh-wecom/use-this-package/authorization-operations: + en: a5d3467ec57a5657 + zh: ea5a0e1c3c539046 +/deepseek-ai-dsh-wecom/use-this-package/configure: + en: dfbcda32182eb7eb + zh: 554086e7081a313a +/deepseek-ai-dsh-wecom/understand-the-implementation: + en: 2b6b63d9e4e2e41c + zh: 6268453811f2efcb +/deepseek-ai-dsh-wecom/further-exploration: + en: 7a8fda721faaf5ef + zh: b4233b8a77994ae6 +/deepseek-ai-dsh-wecom/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-wecom/model-experience/skill-catalog-entries: + en: 7265024b55daf9ef + zh: 3447e587c56a25d6 +/deepseek-ai-dsh-wecom/model-experience/skill-catalog-entries/what-the-model-sees: + en: 92eb47194f3c8cc3 + zh: b9cfda74948e4b1a +/deepseek-ai-dsh-wecom/model-experience/skill-catalog-entries/token-effect: + en: 5c0018a8ae3cd3d3 + zh: 341e13c2f26125be +/deepseek-ai-dsh-wecom/model-experience/skill-catalog-entries/kv-cache-effect: + en: ce9139edf3309f2b + zh: bca06594b3e557e5 +/deepseek-ai-dsh-wecom/model-experience/loaded-skill-body: + en: 8955ac196848e69f + zh: 54aa7db097eafd3c +/deepseek-ai-dsh-wecom/model-experience/loaded-skill-body/what-the-model-sees: + en: ff5d75fb84ce8130 + zh: 0f236bf0534755a9 +/deepseek-ai-dsh-wecom/model-experience/loaded-skill-body/token-effect: + en: 1ed287a86abbc585 + zh: 5d55a6fd61786866 +/deepseek-ai-dsh-wecom/model-experience/loaded-skill-body/kv-cache-effect: + en: 1f6b842a95e14ce4 + zh: 0d57cdec5e828828 +/deepseek-ai-dsh-wecom/model-experience/cli-path: + en: b5fed52af6c0d771 + zh: 25b7aa5297583030 +/deepseek-ai-dsh-wecom/model-experience/cli-path/what-the-model-sees: + en: 44f38c8383be971a + zh: 5975e1948617e18b +/deepseek-ai-dsh-wecom/model-experience/cli-path/what-the-model-sees/runtime-context-entry: + en: c91314832f78f460 + zh: aac156ea0b5b816a +/deepseek-ai-dsh-wecom/model-experience/cli-path/what-the-model-sees/runtime-context-entry-on-windows: + en: 54f899bbaf7ed198 + zh: 31256473a192427b +/deepseek-ai-dsh-wecom/model-experience/cli-path/token-effect: + en: 2caf581d193f3dba + zh: 3b5e94d4cc69ca3b +/deepseek-ai-dsh-wecom/model-experience/cli-path/kv-cache-effect: + en: 67398dd4e4b02db9 + zh: a873eacd006fa656 +/deepseek-ai-dsh-wecom/known-limitations-and-deferred-work: + en: 7a9e3ee8135294ee + zh: a016e5b728757c1f +/deepseek-ai-dsh-wecom/known-limitations-and-deferred-work/dev-note: + en: 71cc23fc507e649e + zh: 3dbd0498845467cc diff --git a/packages/connector/wecom/README.md b/packages/connector/wecom/README.md new file mode 100644 index 0000000000..dc3e048da8 --- /dev/null +++ b/packages/connector/wecom/README.md @@ -0,0 +1,178 @@ +--- +description: "Add the WeCom plugin to a profile: the official wecom-cli with its skills, and WeCom authorization on the Plugins page." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-wecom + +English | [中文](README.zh.md) + +## Summary + +The WeCom plugin lets conversations use WeCom through the official `wecom-cli`. It installs a pinned `@wecom/cli`, gives the model the absolute path of its `wecom-cli` executable in runtime context, and registers one `wecom` skill whose guides are the official WeCom skills, downloaded from the CLI's GitHub repository. It registers the authorization with the [connector account registry](../../client/ui-connector-account/README.md), so the Plugins page shows it and can check it, bind a bot through the CLI's QR-code page, or cancel. The CLI keeps the bot credentials in its default configuration, which the user's own terminal shares. Only macOS and Windows x64 are supported. + +## 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 + +### Install into a profile + +Install the plugin from the Web sidebar's **Plugins** page or with the CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-wecom +dsh plugin --profile web remove @deepseek-ai/dsh-wecom +``` + +`@wecom/cli` ships its native binary in a platform package such as `@wecom/cli-darwin-arm64`, which installs without a build script. When no platform package matches the computer, or the executable is missing, the `wecom` row fails to load with an error that names the missing package or path. + +### What you get + +After the plugin loads, one `wecom` skill joins the skill catalog. The agent loads it with the `skill` tool, opens the guide it needs, such as `wecomcli-doc` or `wecomcli-message`, with the file tools, and runs `wecom-cli` by that path through the ordinary Shell tools under the current sandbox and approval policy. When `wecom-cli auth show --status` reports no authorization, the agent asks the user to connect WeCom on the plugin page; it runs the CLI's own `auth init` only when the user asks to finish it in the conversation, and requests `sandbox_permissions` with a `justification` on the first attempt because the command writes outside the workspace. When a command returns `errcode` 853004 (`cli token expired`), the agent does not ask for a new authorization or pass on the server's upgrade advice: it reruns the command with `sandbox_permissions` and a `justification`, because in the file sandbox the CLI cannot save the token it just refreshed. + +The guides come from `skills/` of `WecomTeam/wecom-cli` at commit `4c74ff2`. The row downloads that commit's archive when it loads and keeps the verified files in `$DSH_HOME/cache/wecom/`; until they are in place, the catalog has no `wecom` skill and the plugin page reports the download. A failed download is retried by the page's check. + +Turning the plugin off in Plugin Manager withdraws the skills, the path from runtime context, and the authorization section. The CLI authorization and the downloaded guides stay in place. + + +### Authorization operations + +The Plugins page drives these operations through the connector account registry, which the Web app loads; a headless profile loads the plugin without it. The Host runs at most one operation at a time and owns it, so leaving the page does not cancel it. + +| Operation | Effect | +|---|---| +| `check` | Checks the authorization again; each browser that opens the Web app starts one when no operation runs | +| `connect` | Runs `auth init --noninteractive --no-browser`, waits for the user to scan the QR code, then checks that the CLI reports the bot authorized. The authorized section offers it again as changing the bot, after a confirmation, because the new binding replaces the one the terminal shares | +| Cancel | Cancels the connection while it waits for the scan and waits for its command to exit; other steps are ignored | + +A check runs `auth show`. The authorization reads `authorized` or `unauthorized` from the CLI's `Status` line, and the bound bot's id from its `Bot ID` line, which the section shows when the CLI prints one; any other output or a nonzero exit fails the check and keeps the previous state. Each link that `auth init` prints alone on a stdout line is offered only when it is an HTTPS address on `work.weixin.qq.com`. Results report succeeded, cancelled, or failed. Failures show the command and the observed exit code on the page and in the Host log; the CLI's output, which can carry the QR-code session, is omitted. `wecom-cli` has no command that revokes the authorization, so the plugin offers no disconnect. The process running DSH needs access to the CLI configuration; `DSH_HOME` does not relocate it. + +### Configure + +| Field | Default | Meaning | +|---|---|---| +| `binDir` | the installed `@wecom/cli--` package's `bin` | Absolute directory containing an executable `wecom-cli`, `wecom-cli.exe` on Windows | +| `skillsDir` | none | Directory holding the files of `skills/` at their repository paths; when set, the guides are not downloaded | + +An authorization check gets the `commandTimeoutMs` of the [`cli-account` row](../cli-account/README.md#use-this-package), 30 seconds by default. QR-code authorization waits up to 10 minutes for the user, and each command keeps at most 1 MiB of stdout; the CLI account Service fixes both limits. The guides are downloaded from the `skillsUrls` of the [`upstream-skills` row](../upstream-skills/README.md#use-this-package), each within its `skillsTimeoutMs`. + +The generated [config catalog](../../../docs/config-catalog.md#deepseek-aidsh-wecom) is the exhaustive source of supported fields. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +[`cordis.patch.yml`](cordis.patch.yml) inserts this package as the `wecom` row after the profile's other layers, and the Plugins page keys the authorization section by this package name. [`src/index.ts`](src/index.ts) is a function plugin. It checks that `binDir/wecom-cli` (`wecom-cli.exe` on Windows) is executable, registers the `wecom` skill with `ctx.upstreamSkills` under the pin in [`src/skills.ts`](src/skills.ts), and registers that path and the authorization with `ctx.cliAccounts`. The account view carries the download state, and each check restarts a failed download without waiting for it. [`src/directory.ts`](src/directory.ts) resolves the platform package that `@wecom/cli` installs as an optional dependency. The [CLI account Service](../cli-account/README.md) gives the model that path in runtime context, runs each command by the same path, runs one operation at a time, and reports a failed command by its exit code. [`src/account.ts`](src/account.ts) carries out each operation with the WeCom commands and reads the QR-code link from the output lines of `auth init`. [`src/presentation.ts`](src/presentation.ts) maps each view to the section the registry serves, in the text of [`src/locales.ts`](src/locales.ts). Disposal cancels the active operation, aborts running commands, and settles after their processes exit. + +[`skills/wecom/SKILL.md`](skills/wecom/SKILL.md) is the only skill this package carries: the DSH guidance, an index of the guides, and how to open them. Upstream publishes the guides only in its repository and not in the npm package, so the [upstream skills Service](../upstream-skills/README.md) downloads them; they are files under the skill's base directory, not separate skills. Where the DSH guidance and `wecomcli-shared` disagree, the entry tells the agent to follow the DSH guidance: it uses the plugin's `wecom-cli` instead of installing one, and sends authorization to the plugin page. References are ordinary files in each guide's directory. + +
+ +----- + + +## Further Exploration + +- [Connector packages](../README.md) — the group this application plugin belongs to. +- [CLI account Service](../cli-account/README.md) — command execution, the CLI path context, and account operations shared by CLI app plugins. +- [Upstream skills Service](../upstream-skills/README.md) — download, verification, and publication of the guides. +- [Skills](../../../docs/subsystems/skills.md) — catalog publication, loading, and precedence. +- [Connector account surfaces](../../client/ui-connector-account/README.md) — the registry and the Plugins page section that drive the authorization operations. + +----- + + +## Model Experience + +### Skill catalog entries + +#### What the model sees + +The skill catalog lists one `wecom` skill. Its Chinese description names the WeCom features it covers and tells the agent to load it, then read the matching guide, whenever the user mentions WeCom or those features or gives a `doc.weixin.qq.com` or `drive.weixin.qq.com` link. + +#### Token effect + +The entry stays in context while the plugin is loaded. Its name and description total about 160 characters. + +#### KV Cache effect + +The catalog is fixed for one plugin version. Loading or unloading the plugin changes the catalog, which is republished as a new message and leaves earlier context in place. + +### Loaded skill body + +#### What the model sees + +A `skill` tool result for `wecom` contains about 2,300 characters: the DSH guidance, an index that gives each of the 15 guides one sentence with the upstream routing rules, and how to open a guide. The DSH guidance tells the agent to run the plugin's `wecom-cli` by the absolute path from the current runtime context, to ask the user to connect on the plugin page before running `auth init --noninteractive` itself, to request `sandbox_permissions` for that command from its first attempt, and to rerun a command that returned `errcode` 853004 with `sandbox_permissions` instead of asking for a new authorization or passing on the server's upgrade advice, asking for a new authorization only when the rerun returns 853004 again; it takes precedence over `wecomcli-shared` where they disagree. Its resource base is the downloaded directory, `skillsDir` or `$DSH_HOME/cache/wecom/skills-`, so the agent opens `skills//SKILL.md` with the file tools rather than the `skill` tool, treats a skill the guides name as that guide, and resolves a guide's relative paths against the guide's own directory. + +#### Token effect + +Each load adds the entry body to the retained tool history. Guides and their reference files arrive as ordinary file-read output. + +#### KV Cache effect + +Loading appends a tool result and does not rewrite earlier context. + +### CLI path + +#### What the model sees + +While the row is loaded, the [CLI account Service](../cli-account/README.md#model-experience) adds one required runtime-context entry with the path of `wecom-cli` in `binDir`, which defaults to the `bin` directory of the platform package that `@wecom/cli` installs. The second line covers the guide scripts that call `wecom-cli` by name, such as `build_page.py`. + +##### Runtime-context entry + +```markdown +WeCom CLI: run `wecom-cli` by its absolute path "/wecom-cli"; the bare name may resolve to another installation or to none. +Scripts in the WeCom skill call `wecom-cli` by name; prefix only the commands that run them with PATH=":$PATH", and never export PATH or run `wecom-cli` by name yourself. +``` + +##### Runtime-context entry on Windows + +```markdown +WeCom CLI: run `wecom-cli` by its absolute path with the call operator, & '\wecom-cli.exe'; the bare name may resolve to another installation or to none. +Scripts in the WeCom skill call `wecom-cli` by name; start only the commands that run them with $env:PATH = ';' + $env:PATH, and never run `wecom-cli` by name yourself. +``` + +#### Token effect + +Two lines of about 280 characters plus the path and its directory in each runtime-context snapshot. + +#### KV Cache effect + +The system prompt does not change; loading or unloading the row, or a changed path, appends one runtime-context snapshot. + +## Known Limitations and Deferred Work + + + +- Only macOS and Windows x64 are supported; other platforms are unverified. `@wecom/cli` publishes no Windows arm64 package. +- Commands must run on this Host. When a composition runs them elsewhere, such as over SSH, the plugin still loads, and each command that runs `wecom-cli` fails because the path does not exist there. +- The plugin uses the CLI's default configuration. Authorizing from DSH affects the user's own terminal, and there is no DSH-private bot or bot picker. `wecom-cli` cannot revoke the authorization, so neither the page nor turning the plugin off removes it; the page can only replace the bound bot with another one. +- Connection reads the QR-code link from the plain-text output of `auth init --noninteractive --no-browser`; a CLI version that changes that output fails the connection with a retryable result. +- The guides follow upstream commit `4c74ff2`; updating them means a new pin from `scripts/upstream-skills-digest.ts`, after which the entry's index and DSH guidance must be checked against the new guides. +- The first load after a new pin needs access to GitHub or a configured mirror; until a download succeeds, the agent has no `wecom` skill. +- The downloaded guides stay in `$DSH_HOME/cache/wecom/` after the plugin is removed or pins another commit. +- In the file sandbox, `wecom-cli` reads the saved authorization without writing, so commands run there until the saved token expires. It then cannot save the refreshed token in its configuration directory outside the workspace, and the command returns `errcode` 853004 with the server's upgrade advice. Rerunning that command needs one single-command approval, after which commands run in the sandbox again until the next expiry. The page's check reads only local state and does not refresh the token. + + +### Dev Note + +
+Working context for maintainers — click to expand + +The guides keep upstream whitespace, including trailing spaces that mark Markdown line breaks, and no whitespace exemption covers them: a commit that adds upstream lines with trailing whitespace fails the pre-commit `git diff --cached --check`. Specs and the `wecom-skills` session snapshot use stand-in executables through `binDir`. + +
diff --git a/packages/connector/wecom/README.zh.md b/packages/connector/wecom/README.zh.md new file mode 100644 index 0000000000..60535732d1 --- /dev/null +++ b/packages/connector/wecom/README.zh.md @@ -0,0 +1,178 @@ +--- +description: "把企业微信插件加入 profile:官方 wecom-cli 及其技能,以及插件页上的企业微信授权。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-wecom + +[English](README.md) | 中文 + +## 概述 + +企业微信插件让对话通过官方 `wecom-cli` 使用企业微信。它安装固定版本的 `@wecom/cli`,在运行时上下文中把其 `wecom-cli` 可执行文件的绝对路径告诉模型,并注册一个 `wecom` skill,其子指南是官方企业微信技能,从该 CLI 的 GitHub 仓库下载。它把授权注册到 [连接器账号注册表](../../client/ui-connector-account/README.zh.md),插件页因此能显示授权,并检查授权、通过 CLI 的扫码页面绑定机器人,或取消操作。CLI 把机器人凭据保存在默认配置中,与用户自己的终端共用。仅支持 macOS 和 Windows x64。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +在 Web 侧栏的**插件**页面安装,或使用 CLI: + +```sh +dsh plugin --profile web add @deepseek-ai/dsh-wecom +dsh plugin --profile web remove @deepseek-ai/dsh-wecom +``` + +`@wecom/cli` 把原生程序放在 `@wecom/cli-darwin-arm64` 等平台包中,这些包安装时不运行构建脚本。没有与本机匹配的平台包或可执行文件缺失时,`wecom` 行会加载失败,并给出缺失的包名或路径。 + +### 获得的能力 + +插件加载后,一个 `wecom` skill 进入 skill 目录。agent 用 `skill` 工具加载它,用文件工具打开所需的子指南(例如 `wecomcli-doc` 或 `wecomcli-message`),并在当前沙箱与审批策略下通过普通 Shell 工具按这个路径运行 `wecom-cli`。`wecom-cli auth show --status` 报告未授权时,agent 会请用户到插件页连接企业微信;只有用户要求在对话中完成时,才运行 CLI 自带的 `auth init`,并且因为该命令会写入工作区之外,第一次尝试就带 `justification` 申请 `sandbox_permissions`。命令返回 `errcode` 853004(`cli token expired`)时,agent 不会请用户重新授权,也不会转述服务端的升级建议,而是带 `sandbox_permissions` 和 `justification` 重跑同一条命令,因为在文件沙箱下 CLI 保存不了刚换到的 token。 + +子指南来自 `WecomTeam/wecom-cli` 在提交 `4c74ff2` 时的 `skills/`。该行加载时下载这个提交的归档,并把校验后的文件保存在 `$DSH_HOME/cache/wecom/`;文件就位之前,skill 目录中没有 `wecom` skill,插件页会报告下载状态。下载失败时,由插件页的检查重试。 + +在 Plugin Manager 中关闭插件会撤下 skill、运行时上下文中的路径和授权区块,CLI 的授权和已下载的子指南保持不变。 + + +### 授权操作 + +插件页通过 连接器账号注册表发起这些操作,注册表由 Web 应用加载;headless profile 加载插件时没有它。Host 同一时间最多运行一个操作并持有它,因此离开页面不会取消操作。 + +| 操作 | 作用 | +|---|---| +| `check` | 重新检查授权;没有操作运行时,每个打开 Web 应用的浏览器会触发一次 | +| `connect` | 运行 `auth init --noninteractive --no-browser`,等待用户扫码,然后确认 CLI 报告机器人已授权。已授权的区块以“更换机器人”再次提供它,需先确认,因为新绑定会替换终端共用的那一个 | +| 取消 | 在等待扫码期间取消连接并等待其命令退出;其他步骤会被忽略 | + +检查运行 `auth show`。授权状态从 CLI 输出的 `Status` 行读作 `authorized` 或 `unauthorized`,CLI 打印 `Bot ID` 行时,从中读取已绑定机器人的 id 并显示在区块中;其他输出或非零退出码会使检查失败,并保留之前的状态。`auth init` 在 stdout 中单独一行打印的链接,只有是 `work.weixin.qq.com` 上的 HTTPS 地址时才会提供。结果分为成功、已取消和失败。失败时,页面和 Host 日志显示命令和观察到的退出码;CLI 的输出可能带有扫码会话,因此不保留。`wecom-cli` 没有撤销授权的命令,因此插件不提供断开连接。运行 DSH 的进程需要能访问 CLI 配置;`DSH_HOME` 不会迁移它。 + +### 配置 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `binDir` | 已安装 `@wecom/cli--` 包的 `bin` | 包含可执行 `wecom-cli`(Windows 上为 `wecom-cli.exe`)的绝对目录 | +| `skillsDir` | 无 | 按仓库路径存放 `skills/` 文件的目录;设置后不下载子指南 | + +授权检查使用 [`cli-account` 行](../cli-account/README.zh.md#use-this-package)的 `commandTimeoutMs`,默认 30 秒。扫码授权最多等待用户 10 分钟,每条命令最多保留 1 MiB 的 stdout;这两个上限由 CLI 账号 Service 固定。子指南从 [`upstream-skills` 行](../upstream-skills/README.zh.md#use-this-package)的 `skillsUrls` 下载,每个前缀的时限是该行的 `skillsTimeoutMs`。 + +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-wecom)是受支持字段的完整来源。 + +----- + + +## 理解实现 + +
+实现内部机制——点击展开 + +[`cordis.patch.yml`](cordis.patch.yml) 在 profile 其他层之后把本包作为 `wecom` 行插入,插件页以本包名作为授权区块的 key。[`src/index.ts`](src/index.ts) 是一个函数插件。它检查 `binDir/wecom-cli`(Windows 上为 `wecom-cli.exe`)是否可执行,按 [`src/skills.ts`](src/skills.ts) 中的固定信息把 `wecom` skill 注册到 `ctx.upstreamSkills`,并把这个路径和授权注册到 `ctx.cliAccounts`。账号视图携带下载状态,每次检查都会在不等待的情况下重新开始失败的下载。[`src/directory.ts`](src/directory.ts) 定位 `@wecom/cli` 作为可选依赖安装的平台包。[CLI 账号 Service](../cli-account/README.zh.md) 在运行时上下文中把这个路径告诉模型,按同一路径运行每条命令,一次执行一个操作,并以退出码报告失败的命令。[`src/account.ts`](src/account.ts) 用企业微信的命令完成每个操作,并从 `auth init` 的输出行中读取扫码链接。[`src/presentation.ts`](src/presentation.ts) 用 [`src/locales.ts`](src/locales.ts) 中的文案,把每个视图映射为注册表提供的区块。释放时取消进行中的操作,中止正在运行的命令,并在这些进程退出后完成。 + +[`skills/wecom/SKILL.md`](skills/wecom/SKILL.md) 是本包携带的唯一 skill:DSH 指引、子指南索引和打开方式。上游只在其仓库发布这些子指南,没有放进 npm 包,因此由[上游技能 Service](../upstream-skills/README.zh.md) 下载;它们是 skill 基础目录下的文件,不是独立的 skill。DSH 指引与 `wecomcli-shared` 不一致时,总入口要求 agent 以 DSH 指引为准:使用插件提供的 `wecom-cli`,不再自行安装,并把授权引导到插件页。引用文件是每个子指南目录中的普通文件。 + +
+ +----- + + +## 进一步探索 + +- [Connector 包](../README.zh.md)——这个应用插件所属的分组。 +- [CLI 账号 Service](../cli-account/README.zh.md)——CLI 应用插件共用的命令执行、CLI 路径上下文与账号操作。 +- [上游技能 Service](../upstream-skills/README.zh.md)——子指南的下载、校验与发布。 +- [Skill](../../../docs/subsystems/skills.zh.md)——目录发布、加载与优先级。 +- [连接器账号界面](../../client/ui-connector-account/README.zh.md)——发起授权操作的注册表和插件页区块。 + +----- + + +## 模型体验 + +### Skill 目录条目 + +#### 模型看到什么 + +skill 目录只列出一个 `wecom` skill。其中文描述列出它覆盖的企业微信功能,并要求 agent 在用户提到企业微信或这些功能、或给出 `doc.weixin.qq.com`、`drive.weixin.qq.com` 链接时加载它,再读取对应的子指南。 + +#### Token 影响 + +插件加载期间这一条目一直留在上下文中。其名称与描述合计约 160 个字符。 + +#### KV Cache 影响 + +同一插件版本的目录固定不变。加载或卸载插件会改变目录,目录作为新消息重新发布,不改动更早的上下文。 + +### 已加载的 skill 正文 + +#### 模型看到什么 + +`wecom` 的 `skill` 工具结果约 2,300 个字符:DSH 指引、为 15 个子指南各写一句话并保留上游分流规则的索引,以及打开子指南的方式。DSH 指引要求 agent 按当前运行时上下文给出的绝对路径运行插件提供的 `wecom-cli`,先请用户到插件页连接,再考虑自行运行 `auth init --noninteractive`,第一次运行该命令就申请 `sandbox_permissions`,命令返回 `errcode` 853004 时带 `sandbox_permissions` 重跑同一条命令,而不是请用户重新授权或转述服务端的升级建议,重跑后仍返回 853004 才请用户重新授权;与 `wecomcli-shared` 不一致时以它为准。其资源根目录是下载目录,即 `skillsDir` 或 `$DSH_HOME/cache/wecom/skills-<摘要>`,因此 agent 用文件工具而不是 `skill` 工具打开 `skills//SKILL.md`,把子指南按名字提到的技能当作对应子指南,并按子指南自己的目录解析其中的相对路径。 + +#### Token 影响 + +每次加载把总入口正文加入保留的工具历史。子指南及其引用文件作为普通的文件读取输出返回。 + +#### KV Cache 影响 + +加载会追加一条工具结果,不改写更早的上下文。 + +### CLI 路径 + +#### 模型看到什么 + +该行加载期间,[CLI 账号 Service](../cli-account/README.zh.md#model-experience) 添加一条必需的运行时上下文,给出 `binDir` 中 `wecom-cli` 的路径;`binDir` 默认是 `@wecom/cli` 安装的平台包的 `bin` 目录。第二行针对按名称调用 `wecom-cli` 的子指南脚本,例如 `build_page.py`。 + +##### 运行时上下文条目 + +```markdown +WeCom CLI: run `wecom-cli` by its absolute path "/wecom-cli"; the bare name may resolve to another installation or to none. +Scripts in the WeCom skill call `wecom-cli` by name; prefix only the commands that run them with PATH=":$PATH", and never export PATH or run `wecom-cli` by name yourself. +``` + +##### Windows 上的运行时上下文条目 + +```markdown +WeCom CLI: run `wecom-cli` by its absolute path with the call operator, & '\wecom-cli.exe'; the bare name may resolve to another installation or to none. +Scripts in the WeCom skill call `wecom-cli` by name; start only the commands that run them with $env:PATH = ';' + $env:PATH, and never run `wecom-cli` by name yourself. +``` + +#### Token 影响 + +每份运行时上下文快照中两行,约 280 个字符加上路径及其目录。 + +#### KV Cache 影响 + +系统提示词不变;加载或卸载该行、或路径变化时,追加一份运行时上下文快照。 + +## 已知限制与延期工作 + + + +- 仅支持 macOS 和 Windows x64;其他平台未经验证。`@wecom/cli` 没有发布 Windows arm64 平台包。 +- 命令必须在本 Host 上运行。组合把命令放到别处运行(例如通过 SSH)时,插件仍会加载,但每条运行 `wecom-cli` 的命令都会因为那里没有这个路径而失败。 +- 插件使用 CLI 的默认配置。在 DSH 中授权会影响用户自己的终端,没有 DSH 私有机器人或机器人选择器。`wecom-cli` 无法撤销授权,因此页面和关闭插件都不会移除它;页面只能把已绑定的机器人换成另一个。 +- 连接从 `auth init --noninteractive --no-browser` 的纯文本输出中读取扫码链接;CLI 版本改变该输出时,连接以可重试的结果失败。 +- 子指南跟随上游提交 `4c74ff2`;更新时要用 `scripts/upstream-skills-digest.ts` 生成新的固定信息,之后按新的子指南核对总入口的索引和 DSH 指引。 +- 换用新的固定提交后,首次加载需要能访问 GitHub 或配置的镜像;下载成功之前,agent 没有 `wecom` skill。 +- 插件卸载或改为固定其他提交后,已下载的子指南仍留在 `$DSH_HOME/cache/wecom/`。 +- 在文件沙箱下,`wecom-cli` 读取已保存的授权时不需要写入,所以在已保存的 token 过期之前命令可以直接运行。token 过期后,CLI 无法把刚换到的 token 保存到工作区之外的配置目录,命令会返回 `errcode` 853004 和服务端的升级建议。重跑这条命令需要一次单条命令审批,之后命令又可以在沙箱中运行,直到下一次过期。页面的检查只读取本地状态,不会刷新 token。 + + +### 开发备注 + +
+维护者工作上下文——点击展开 + +子指南保留上游的空白,包括表示 Markdown 换行的行尾空格,且没有任何空白豁免:新增带行尾空白的上游行的提交,会被 pre-commit 的 `git diff --cached --check` 拒绝。单测与 `wecom-skills` 会话快照通过 `binDir` 使用替身可执行文件。 + +
diff --git a/packages/connector/wecom/cordis.patch.yml b/packages/connector/wecom/cordis.patch.yml new file mode 100644 index 0000000000..7ff90fcc78 --- /dev/null +++ b/packages/connector/wecom/cordis.patch.yml @@ -0,0 +1,3 @@ +- insert: + - id: wecom + name: '@deepseek-ai/dsh-wecom' diff --git a/packages/connector/wecom/docs/DETAIL.md b/packages/connector/wecom/docs/DETAIL.md new file mode 100644 index 0000000000..a97e1841e3 --- /dev/null +++ b/packages/connector/wecom/docs/DETAIL.md @@ -0,0 +1 @@ +![The authorized WeCom section on the plugin page and a conversation that adds a WeCom to-do](preview.svg) diff --git a/packages/connector/wecom/docs/DETAIL.zh.md b/packages/connector/wecom/docs/DETAIL.zh.md new file mode 100644 index 0000000000..5557a498e3 --- /dev/null +++ b/packages/connector/wecom/docs/DETAIL.zh.md @@ -0,0 +1 @@ +![插件页上已授权的企业微信,以及在对话中添加企业微信待办](preview.zh.svg) diff --git a/packages/connector/wecom/docs/preview.svg b/packages/connector/wecom/docs/preview.svg new file mode 100644 index 0000000000..8ccbc85e44 --- /dev/null +++ b/packages/connector/wecom/docs/preview.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/wecom/docs/preview.zh.svg b/packages/connector/wecom/docs/preview.zh.svg new file mode 100644 index 0000000000..459da7fb5a --- /dev/null +++ b/packages/connector/wecom/docs/preview.zh.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/wecom/icon.svg b/packages/connector/wecom/icon.svg new file mode 100644 index 0000000000..25ada96d52 --- /dev/null +++ b/packages/connector/wecom/icon.svg @@ -0,0 +1 @@ + diff --git a/packages/connector/wecom/locale/de.json b/packages/connector/wecom/locale/de.json new file mode 100644 index 0000000000..d08c7e7140 --- /dev/null +++ b/packages/connector/wecom/locale/de.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "WeCom-Plugin", + "description": "Verwenden Sie Dokumente, Kalender, Besprechungen, Aufgaben und Nachrichten von WeCom in Unterhaltungen.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/en.json b/packages/connector/wecom/locale/en.json new file mode 100644 index 0000000000..7b24b2945a --- /dev/null +++ b/packages/connector/wecom/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "WeCom plugin", + "description": "Use WeCom docs, calendar, meetings, to-dos, and messages in conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/es.json b/packages/connector/wecom/locale/es.json new file mode 100644 index 0000000000..d2f8cd4a97 --- /dev/null +++ b/packages/connector/wecom/locale/es.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Complemento de WeCom", + "description": "Use documentos, calendario, reuniones, tareas pendientes y mensajes de WeCom en las conversaciones.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/fr.json b/packages/connector/wecom/locale/fr.json new file mode 100644 index 0000000000..f20d15dc1d --- /dev/null +++ b/packages/connector/wecom/locale/fr.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin WeCom", + "description": "Utilisez les documents, le calendrier, les réunions, les tâches et les messages de WeCom dans les conversations.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/ja.json b/packages/connector/wecom/locale/ja.json new file mode 100644 index 0000000000..a0e839dab4 --- /dev/null +++ b/packages/connector/wecom/locale/ja.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "WeCom プラグイン", + "description": "会話の中で WeCom のドキュメント、カレンダー、会議、ToDo、メッセージを使用します。", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/pt.json b/packages/connector/wecom/locale/pt.json new file mode 100644 index 0000000000..c1d07b4746 --- /dev/null +++ b/packages/connector/wecom/locale/pt.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Plugin do WeCom", + "description": "Use documentos, agenda, reuniões, tarefas e mensagens do WeCom nas conversas.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/ru.json b/packages/connector/wecom/locale/ru.json new file mode 100644 index 0000000000..d79f8f548a --- /dev/null +++ b/packages/connector/wecom/locale/ru.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "Плагин WeCom", + "description": "Используйте документы, календарь, встречи, задачи и сообщения WeCom в беседах.", + "detail": "docs/DETAIL.md" + } +} diff --git a/packages/connector/wecom/locale/zh.json b/packages/connector/wecom/locale/zh.json new file mode 100644 index 0000000000..b783bf31c4 --- /dev/null +++ b/packages/connector/wecom/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "企业微信插件", + "description": "在对话中使用企业微信的文档、日程、会议、待办和消息。", + "detail": "docs/DETAIL.zh.md" + } +} diff --git a/packages/connector/wecom/package.json b/packages/connector/wecom/package.json new file mode 100644 index 0000000000..812108cd10 --- /dev/null +++ b/packages/connector/wecom/package.json @@ -0,0 +1,64 @@ +{ + "name": "@deepseek-ai/dsh-wecom", + "description": "WeCom plugin: the official wecom-cli with its skills, and authorization from the Plugins page", + "version": "0.2.2-rc.5", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/connector/wecom" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json", + "./cordis.patch.yml": "./cordis.patch.yml" + }, + "files": [ + "icon.svg", + "locale/*.json", + "docs", + "lib/index.js", + "cordis.patch.yml", + "skills", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "dependencies": { + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@wecom/cli": "1.3.4" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-upstream-skills": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-cli-account": "workspace:*", + "@deepseek-ai/dsh-client-ui-connector-account": "workspace:*", + "@deepseek-ai/dsh-skill": "workspace:*", + "@deepseek-ai/dsh-subprocess": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-upstream-skills": "workspace:*" + } +} diff --git a/packages/connector/wecom/skills/wecom/SKILL.md b/packages/connector/wecom/skills/wecom/SKILL.md new file mode 100644 index 0000000000..81a14f5a6f --- /dev/null +++ b/packages/connector/wecom/skills/wecom/SKILL.md @@ -0,0 +1,40 @@ +--- +name: wecom +description: 企业微信插件:通过 wecom-cli 使用企业微信的通讯录、消息、日程、在线会议、待办、邮件、微盘、文档、在线表格、智能表格、智能文档和 PPT。用户提到企业微信或这些功能,或给出 doc.weixin.qq.com、drive.weixin.qq.com 链接时,先加载本技能,再按索引读取对应子指南。 +--- + +# 企业微信插件 + +## DSH 指引 + +- 在面向用户的回复中,把这项集成称为“企业微信插件”。`wecom-cli` 由企业微信插件安装,按当前 runtime context 给出的绝对路径运行,不要直接按名称运行。不要执行 `npm install -g @wecom/cli`,也不要用其他方式另装或升级 `wecom-cli`。 +- `wecom-cli` 的授权保存在这台电脑的默认配置目录,与用户自己终端里的 `wecom-cli` 共用。 +- 首次运行业务命令前,先读 `wecomcli-shared` 子指南并按它检查授权。本节与该子指南冲突时以本节为准:它 Step 1 的版本检查不需要安装或升级;它 Step 3 的初始化改为下一条。 +- 未授权时,先请用户在「插件」中打开企业微信插件页面,点击“连接企业微信”并用企业微信扫码授权;用户完成后重新检查授权。只有用户要求在本次对话中完成授权时,才执行 `wecom-cli auth init --noninteractive`:它会输出扫码链接和二维码,并最多等待 5 分钟扫码,把扫码链接告诉用户。它会把凭据写到工作区之外,保存被拒绝时这次扫码也会作废:第一次运行就把 Shell 工具的 `sandbox_permissions` 设为能写工作区之外的最窄模式,并填写 `justification`。 +- 其他 `wecom-cli` 命令在现有沙箱中运行;只有凭据、缓存或日志写入被拒绝时,才设置 `sandbox_permissions`。 +- 命令返回 `errcode` 853004,也就是 `cli token expired` 时,通常是 `wecom-cli` 换到了新 token,却写不进工作区之外的配置目录,于是返回了原错误:授权没有失效,也不需要升级。不要向用户转述返回里的 `help_message`,也不要请用户重新授权,设置 `sandbox_permissions` 和 `justification` 重跑同一条命令。重跑后仍返回 853004,才请用户在企业微信插件页面重新授权。 +- 不要索取或输出 Bot Secret、token 等凭据。 + +## 子指南索引 + +- `wecomcli-shared`:授权检查和所有子指南共用的输出约束(ID 类字段不外露);首次运行 `wecom-cli` 业务命令前先读。 +- `wecomcli-contact`:按姓名、拼音、英文名或别名搜索通讯录,查询 userid、部门和职务。 +- `wecomcli-message`:查询可以发消息的会话,向单聊或群聊发送文本、Markdown、图片、文件、语音或视频。 +- `wecomcli-calendar`:不含在线会议链接的日程、会议室预订和查忙闲;用户只说“开会”“约个会”时,先按本指南或 `wecomcli-meeting` 的消歧流程追问,不要直接创建。 +- `wecomcli-meeting`:含会议号或入会链接的在线会议的创建、查询、纪要、转写、更新和取消;消歧规则同上。 +- `wecomcli-todo`:待办的创建、完成、查询筛选和修改。 +- `wecomcli-email`:邮件的收发、搜索和详情;只有用户明确提到邮箱或邮件时,才用它发送日程或会议邀请。 +- `wecomcli-disk`:微盘(网盘、共享空间)中文件的列出、搜索、元信息、位置、上传、下载和重命名;在线文档的内容读写交给对应的文档子指南。 +- `wecomcli-media`:按 media_id 下载媒体文件,或上传本地文件换取 media_id;只搬运文件,不解析内容。 +- `wecomcli-doc-manage`:各类文档的搜索(含最近浏览)、改名、成员权限和加入规则。 +- `wecomcli-smartpage`:智能文档;用户只说“文档”“新建文档”“整理成文档”等未指定类型时使用,也负责把 .md 导入为文档。 +- `wecomcli-doc`:doc 文档;仅当用户明确说 doc、docx、word、在线文档或 office 文档,或给出 `doc.weixin.qq.com/doc/` 链接时使用。 +- `wecomcli-smartsheet`:智能表格的记录、字段、视图、图表和样式;用户没有明确说“在线表格”时默认使用。 +- `wecomcli-sheet`:在线表格;用户明确说“在线表格”或“excel 表格”、要导入 CSV 或 Excel,或给出 `doc.weixin.qq.com/sheet/` 链接时使用。 +- `wecomcli-pptx`:生成、编辑在线 PPT,或把本地 .ppt、.pptx 导入为在线文档;只读取本地 PPT 内容时改用 `wecomcli-media`。 + +## 打开子指南 + +- 子指南不是独立的 skill,不要用 `skill` 工具加载;用文件读取工具打开本技能目录下的 `skills/<名字>/SKILL.md`。 +- 子指南正文按名字提到的技能(例如“wecomcli-shared 技能”“改用 wecomcli-meeting 技能”)就是 `skills/<名字>/SKILL.md`,同样用文件读取工具打开。 +- 子指南中的相对路径(例如 `references/...`、`../wecomcli-calendar/...`)相对该子指南自己的目录 `skills/<名字>/`。 diff --git a/packages/connector/wecom/src/account.ts b/packages/connector/wecom/src/account.ts new file mode 100644 index 0000000000..023d18e080 --- /dev/null +++ b/packages/connector/wecom/src/account.ts @@ -0,0 +1,69 @@ +/** + * Check and QR-code binding of the wecom-cli bot that the user's terminal shares, as the operations `ctx.cliAccounts` + * runs; binding again replaces it. + */ + +import type { CliOperationControl } from '@deepseek-ai/dsh-cli-account/types' +import type { UpstreamSkillsHandle } from '@deepseek-ai/dsh-upstream-skills/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { WecomAccountState, WecomCommand, WecomOperationKind, WecomPhase } from './types.ts' + +const AUTHORIZATION_LINK = /^\s*(https:\/\/\S+)\s*$/u +/** `auth show` prints `Status: authorized` or `Status: unauthorized`, then `Bot ID: ` when a bound bot gives the authorization. */ +const STATUS_LINE = /^Status:[ \t]*(authorized|unauthorized)[ \t]*$/mu +const BOT_LINE = /^Bot ID:[ \t]*(\S+)[ \t]*$/mu + +type Control = CliOperationControl + +/** The upstream guides whose state the account carries and whose failed download each check restarts. */ +type Guides = Pick + +/* jscpd:ignore-start -- CLI app plugins with downloaded guides bind their operations to the guides alike. */ +/** + * Bind the WeCom account operations to the upstream guides. + * @param guides - the registered upstream guides. + * @returns the function that carries out one operation with wecom-cli and publishes the authorization each check + * observes; it throws when a command fails, prints an unknown status, or leaves no authorization after a binding. + */ +export function performWith(guides: Guides): (kind: WecomOperationKind, control: Control, signal: AbortSignal) => Promise { + return async (kind, control, signal) => { + switch (kind) { + case 'check': + await check(guides, control, signal) + return + case 'connect': return connect(guides, control, signal) + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(kind) + } + } +} +/* jscpd:ignore-end */ + +/** Bind a bot through the CLI's QR-code page, then confirm the CLI reports it authorized. */ +async function connect(guides: Guides, control: Control, signal: AbortSignal): Promise { + control.stage('authorizing') + const init = await control.run('auth-init', ['auth', 'init', '--noninteractive', '--no-browser'], signal, { + awaitsUser: true, + onLine: (stream, line) => { + const link = stream === 'stdout' ? AUTHORIZATION_LINK.exec(line) : null + if (link !== null) control.offer(link[1] as string) + }, + }) + if (init.exitCode !== 0) throw new Error(`wecom: auth init exited with ${String(init.exitCode)}`) + control.stage('checking') + if ((await check(guides, control, signal)).state !== 'authorized') throw new Error('wecom: auth init left no authorization') +} + +/** Restart a failed download of the guides without waiting for it, then read the authorization state, publish it, and return it. */ +async function check(guides: Guides, control: Control, signal: AbortSignal): Promise { + guides.retry() + const result = await control.run('auth-status', ['auth', 'show'], signal) + const state = STATUS_LINE.exec(result.stdout)?.[1] + if (result.exitCode !== 0 || (state !== 'authorized' && state !== 'unauthorized')) { + throw new Error(`wecom: auth show exited with ${String(result.exitCode)} or printed an unknown status`) + } + const botId = state === 'authorized' ? BOT_LINE.exec(result.stdout)?.[1] : undefined + const account: WecomAccountState = { state, ...botId === undefined ? {} : { botId }, skills: guides.state } + control.publish(account) + return account +} diff --git a/packages/connector/wecom/src/directory.ts b/packages/connector/wecom/src/directory.ts new file mode 100644 index 0000000000..3980a7e40c --- /dev/null +++ b/packages/connector/wecom/src/directory.ts @@ -0,0 +1,43 @@ +/** Managed wecom-cli location: the platform binary package that `@wecom/cli` installs. */ + +import { accessSync, constants } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' + +/** The name wecom-cli's guides and scripts run it by. */ +export const PROGRAM = 'wecom-cli' + +/** + * Name the executable file as the platform package installs it. + * @param platform - the Host platform. + * @returns `wecom-cli`, or `wecom-cli.exe` on Windows. + */ +export function executableFileName(platform: NodeJS.Platform): string { + return platform === 'win32' ? `${PROGRAM}.exe` : PROGRAM +} + +function platformDirectory(): string { + const platformPackage = `@wecom/cli-${process.platform}-${process.arch}` + try { + const require = createRequire(import.meta.resolve('@wecom/cli/package.json')) + return join(dirname(require.resolve(`${platformPackage}/package.json`)), 'bin') + } catch (error) { + throw new Error(`wecom: ${platformPackage} is not installed; @wecom/cli has no binary for this platform, or set binDir`, { cause: error }) + } +} + +/** + * Locate the managed executable. + * @param binDir - absolute override; defaults to the `bin` of the installed `@wecom/cli--` package. + * @returns the absolute path of the executable `wecom-cli`, `wecom-cli.exe` on Windows. + * @throws when the platform package is missing or the executable is not executable. + */ +export function resolveCliExecutable(binDir: string | undefined): string { + const program = join(binDir ?? platformDirectory(), executableFileName(process.platform)) + try { + accessSync(program, constants.X_OK) + } catch (error) { + throw new Error(`wecom: ${program} is not executable; reinstall the plugin or set binDir`, { cause: error }) + } + return program +} diff --git a/packages/connector/wecom/src/index.ts b/packages/connector/wecom/src/index.ts new file mode 100644 index 0000000000..75bb2dfec7 --- /dev/null +++ b/packages/connector/wecom/src/index.ts @@ -0,0 +1,66 @@ +/** + * WeCom plugin: registers the managed wecom-cli and its authorization with `ctx.cliAccounts`, which tells the model the + * CLI's absolute path and shows the authorization on the Plugins page, and registers the `wecom` entry skill with + * `ctx.upstreamSkills`, which downloads the upstream guides it indexes. The CLI's authorization is shared with the + * user's own terminal. + * @module @deepseek-ai/dsh-wecom + */ + +import type { Context } from '@deepseek-ai/cordis' +import z from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-cli-account' +import type {} from '@deepseek-ai/dsh-upstream-skills' +import { performWith } from './account.ts' +import { PROGRAM, resolveCliExecutable } from './directory.ts' +import { dictionaries, type WecomTextKey } from './locales.ts' +import { copy, operations, presentAccount, WECOM_PACKAGE } from './presentation.ts' +import { ENTRY, WECOM_SKILLS } from './skills.ts' +import type { WecomAccountState, WecomCommand, WecomOperationKind, WecomPhase } from './types.ts' + +/** Plugin name. */ +export const name = 'wecom' + +/* jscpd:ignore-start -- CLI app plugins with downloaded guides declare the same services, config, and registration. */ +/** Services the CLI's authorization and the entry skill register with. */ +export const inject = ['cliAccounts', 'upstreamSkills'] + +/** Where wecom-cli and the upstream guides are. */ +export interface Config { + /** Absolute directory holding the `wecom-cli` executable; defaults to the installed platform package of `@wecom/cli`. */ + binDir?: string + /** Absolute directory holding the upstream guides at their repository paths; when set, nothing is downloaded. */ + skillsDir?: string +} + +/** Validates {@link Config}. */ +export const Config: z = z.object({ + binDir: z.string().min(1), + skillsDir: z.string().min(1), +}) + +/** + * Register the entry skill, and the CLI with its authorization, whose view follows the guides' download. + * @param ctx - Context carrying the CLI account Service and the upstream skills Service. + * @param config - CLI location and the guides' directory. + * @throws when `wecom-cli` is not executable or `skillsDir` is not a directory. + */ +export function apply(ctx: Context, config: Config): void { + const executable = resolveCliExecutable(config.binDir) + const guides = ctx.upstreamSkills.register({ name, entry: ENTRY, set: WECOM_SKILLS, skillsDir: config.skillsDir }) + const account = ctx.cliAccounts.register({ + name, + packageName: WECOM_PACKAGE, + cli: { product: 'WeCom', program: PROGRAM, executable, scripts: true }, + account: { state: 'unchecked', skills: guides.state }, + check: 'check', + cancellable: ['authorizing'], + authorizationHosts: ['work.weixin.qq.com'], + perform: performWith(guides), + dictionaries, + operations, + copy, + present: presentAccount, + }) + ctx.effect(() => guides.watch((skills) => { account.publish({ ...account.snapshot().account, skills }) }), 'wecom: guides') +} +/* jscpd:ignore-end */ diff --git a/packages/connector/wecom/src/locales.ts b/packages/connector/wecom/src/locales.ts new file mode 100644 index 0000000000..625833cb44 --- /dev/null +++ b/packages/connector/wecom/src/locales.ts @@ -0,0 +1,279 @@ +/** The WeCom text the Plugins page shows; the browser resolves it in its active language. */ + +/** Chinese dictionary and key source. */ +export const zh = { + 'section.title': '企业微信授权', + 'status.checking': '正在检查授权', + 'status.disconnected': '未授权', + 'status.unavailable': '暂时无法读取授权状态', + 'status.connected': '已授权', + 'step.authorizing': '等待扫码授权', + 'step.connecting': '正在确认授权', + 'detail.disconnected': '用企业微信扫码绑定一个智能机器人。授权后,可以在对话中通过这个机器人使用企业微信的文档、日程、会议、待办和消息等功能。', + 'detail.unavailable': '没能读取 wecom-cli 的授权状态,可以稍后重试。', + 'detail.connected': '可以在对话中直接请 Agent 使用企业微信。', + 'detail.authorizing': '在打开的页面中用企业微信扫码并确认,完成后回到这里查看结果。页面没有打开时,点击“打开扫码页面”。', + 'skills.downloading': '正在从 GitHub 下载企业微信技能,下载完成后即可在对话中使用。', + 'skills.failed': '企业微信技能没能下载,Agent 暂时用不了企业微信的子指南。请确认这台电脑能访问 GitHub,然后重试。', + hint: '授权与这台电脑终端里的 wecom-cli 共用;关闭插件不会解除授权。', + failed: '操作未完成,请重试', + 'action.connect': '连接企业微信', + 'action.rebind': '更换机器人', + 'rebind.title': '更换机器人?', + 'rebind.body': '将重新扫码绑定一个智能机器人,替换这台电脑上 wecom-cli 当前绑定的机器人,终端里的 wecom-cli 也一起更换。', + 'bot.bound': '已绑定机器人:{id}', + 'action.open': '打开扫码页面', + 'action.cancel': '取消', + 'action.retry': '重试', + 'badge.connected': '已授权', + 'badge.disconnected': '未授权', + 'badge.connecting': '授权中', + 'badge.unavailable': '待确认', + 'activation.title': '连接企业微信', + 'activation.body': '企业微信插件已开启。扫码授权后,就可以在对话中使用它。', + 'notice.connected': '企业微信已授权', +} + +/** Every key of the WeCom text. */ +export type WecomTextKey = keyof typeof zh + +/** English dictionary. */ +export const en: Record = { + 'section.title': 'WeCom authorization', + 'status.checking': 'Checking authorization', + 'status.disconnected': 'Not authorized', + 'status.unavailable': 'Cannot read authorization right now', + 'status.connected': 'Authorized', + 'step.authorizing': 'Waiting for the QR code scan', + 'step.connecting': 'Confirming authorization', + 'detail.disconnected': 'Scan a QR code with WeCom to bind a smart bot. After that, you can use WeCom docs, calendar, meetings, to-dos, messages, and other features through this bot in conversations.', + 'detail.unavailable': 'The wecom-cli authorization could not be read. Try again later.', + 'detail.connected': 'Ask the agent to use WeCom directly in a conversation.', + 'detail.authorizing': 'Scan the QR code with WeCom on the page that opened and confirm, then come back here to see the result. If the page did not open, select Open QR code page.', + 'skills.downloading': 'Downloading the WeCom skills from GitHub. They become available in conversations when the download finishes.', + 'skills.failed': 'The WeCom skills could not be downloaded, so the agent cannot use the WeCom guides yet. Check that this computer can reach GitHub, then retry.', + hint: 'The authorization is shared with wecom-cli in this computer\'s terminal. Turning the plugin off does not revoke it.', + failed: 'The action did not finish. Try again.', + 'action.connect': 'Connect WeCom', + 'action.rebind': 'Change bot', + 'rebind.title': 'Change the bot?', + 'rebind.body': 'You will scan a QR code to bind another smart bot. It replaces the bot that wecom-cli on this computer is bound to, including the wecom-cli in your terminal.', + 'bot.bound': 'Bound bot: {id}', + 'action.open': 'Open QR code page', + 'action.cancel': 'Cancel', + 'action.retry': 'Retry', + 'badge.connected': 'Authorized', + 'badge.disconnected': 'Not authorized', + 'badge.connecting': 'Authorizing', + 'badge.unavailable': 'Unconfirmed', + 'activation.title': 'Connect WeCom', + 'activation.body': 'The WeCom plugin is on. Scan a QR code to authorize it, then use it in conversations.', + 'notice.connected': 'WeCom authorized', +} + +/** Japanese dictionary. */ +export const ja: Record = { + 'section.title': 'WeCom の認可', + 'status.checking': '認可を確認中', + 'status.disconnected': '未認可', + 'status.unavailable': '現在認可状態を読み取れません', + 'status.connected': '認可済み', + 'step.authorizing': 'QR コードのスキャン待ち', + 'step.connecting': '認可を確定中', + 'detail.disconnected': 'WeCom で QR コードをスキャンしてスマートボットを紐付けます。その後、会話の中でこのボットを通じて WeCom のドキュメント、カレンダー、会議、ToDo、メッセージなどの機能を使用できます。', + 'detail.unavailable': 'wecom-cli の認可状態を読み取れませんでした。しばらくしてから再試行してください。', + 'detail.connected': '会話の中でエージェントに WeCom の使用を直接依頼できます。', + 'detail.authorizing': '開いたページで WeCom を使って QR コードをスキャンして確定し、完了したらここに戻って結果を確認してください。ページが開かない場合は、「QR コードページを開く」を選択してください。', + 'skills.downloading': 'GitHub から WeCom のスキルをダウンロードしています。ダウンロードが完了すると、会話の中で使用できます。', + 'skills.failed': 'WeCom のスキルをダウンロードできなかったため、エージェントはまだ WeCom のガイドを使用できません。このコンピューターから GitHub にアクセスできることを確認してから、再試行してください。', + hint: '認可は、このコンピューターのターミナルにある wecom-cli と共有されます。プラグインをオフにしても認可は解除されません。', + failed: '操作が完了しませんでした。もう一度お試しください。', + 'action.connect': 'WeCom を接続', + 'action.rebind': 'ボットを変更', + 'rebind.title': 'ボットを変更しますか?', + 'rebind.body': 'QR コードを再度スキャンして別のスマートボットをバインドします。このコンピューター上の wecom-cli が現在バインドしているボットは、ターミナルの wecom-cli も含めて置き換えられます。', + 'bot.bound': 'バインド済みボット:{id}', + 'action.open': 'QR コードページを開く', + 'action.cancel': 'キャンセル', + 'action.retry': '再試行', + 'badge.connected': '認可済み', + 'badge.disconnected': '未認可', + 'badge.connecting': '認可中', + 'badge.unavailable': '未確認', + 'activation.title': 'WeCom を接続', + 'activation.body': 'WeCom プラグインがオンになりました。QR コードをスキャンして認可すると、会話の中で使用できます。', + 'notice.connected': 'WeCom を認可しました', +} + +/** Spanish dictionary. */ +export const es: Record = { + 'section.title': 'Autorización de WeCom', + 'status.checking': 'Comprobando la autorización', + 'status.disconnected': 'Sin autorizar', + 'status.unavailable': 'No se puede leer la autorización en este momento', + 'status.connected': 'Autorizado', + 'step.authorizing': 'Esperando el escaneo del código QR', + 'step.connecting': 'Confirmando la autorización', + 'detail.disconnected': 'Escanee un código QR con WeCom para vincular un bot inteligente. Después, podrá usar en las conversaciones, a través de este bot, los documentos, el calendario, las reuniones, las tareas pendientes, los mensajes y otras funciones de WeCom.', + 'detail.unavailable': 'No se pudo leer la autorización de wecom-cli. Inténtelo de nuevo más tarde.', + 'detail.connected': 'Pida al agente que use WeCom directamente en una conversación.', + 'detail.authorizing': 'Escanee el código QR con WeCom en la página que se abrió y confirme; luego vuelva aquí para ver el resultado. Si la página no se abrió, seleccione “Abrir página del código QR”.', + 'skills.downloading': 'Descargando las habilidades de WeCom desde GitHub. Estarán disponibles en las conversaciones cuando termine la descarga.', + 'skills.failed': 'No se pudieron descargar las habilidades de WeCom, por lo que el agente aún no puede usar las guías de WeCom. Compruebe que esta computadora puede acceder a GitHub y vuelva a intentarlo.', + hint: 'La autorización se comparte con wecom-cli en la terminal de esta computadora. Desactivar el complemento no la revoca.', + failed: 'La acción no se completó. Inténtelo de nuevo.', + 'action.connect': 'Conectar WeCom', + 'action.rebind': 'Cambiar bot', + 'rebind.title': '¿Cambiar el bot?', + 'rebind.body': 'Escaneará un código QR para vincular otro bot inteligente. Sustituye al bot al que está vinculado wecom-cli en este equipo, incluido el wecom-cli de su terminal.', + 'bot.bound': 'Bot vinculado: {id}', + 'action.open': 'Abrir página del código QR', + 'action.cancel': 'Cancelar', + 'action.retry': 'Reintentar', + 'badge.connected': 'Autorizado', + 'badge.disconnected': 'Sin autorizar', + 'badge.connecting': 'Autorizando', + 'badge.unavailable': 'Sin confirmar', + 'activation.title': 'Conectar WeCom', + 'activation.body': 'El complemento de WeCom está activado. Escanee un código QR para autorizarlo y luego úselo en las conversaciones.', + 'notice.connected': 'WeCom autorizado', +} + +/** French dictionary. */ +export const fr: Record = { + 'section.title': 'Autorisation WeCom', + 'status.checking': 'Vérification de l’autorisation', + 'status.disconnected': 'Non autorisé', + 'status.unavailable': 'Impossible de lire l’autorisation pour le moment', + 'status.connected': 'Autorisé', + 'step.authorizing': 'En attente du scan du code QR', + 'step.connecting': 'Confirmation de l’autorisation', + 'detail.disconnected': 'Scannez un code QR avec WeCom pour lier un bot intelligent. Vous pourrez ensuite utiliser dans les conversations, via ce bot, les documents, le calendrier, les réunions, les tâches, les messages et les autres fonctionnalités de WeCom.', + 'detail.unavailable': 'Impossible de lire l’autorisation de wecom-cli. Réessayez plus tard.', + 'detail.connected': 'Demandez à l’agent d’utiliser WeCom directement dans une conversation.', + 'detail.authorizing': 'Scannez le code QR avec WeCom sur la page qui s’est ouverte et confirmez, puis revenez ici pour voir le résultat. Si la page ne s’est pas ouverte, sélectionnez « Ouvrir la page du code QR ».', + 'skills.downloading': 'Téléchargement des compétences WeCom depuis GitHub. Elles seront disponibles dans les conversations une fois le téléchargement terminé.', + 'skills.failed': 'Les compétences WeCom n’ont pas pu être téléchargées : l’agent ne peut donc pas encore utiliser les guides WeCom. Vérifiez que cet ordinateur peut accéder à GitHub, puis réessayez.', + hint: 'L’autorisation est partagée avec wecom-cli dans le terminal de cet ordinateur. Désactiver le plugin ne la révoque pas.', + failed: 'L’action n’a pas abouti. Réessayez.', + 'action.connect': 'Connecter WeCom', + 'action.rebind': 'Changer de bot', + 'rebind.title': 'Changer de bot ?', + 'rebind.body': 'Vous scannerez un QR code pour lier un autre bot intelligent. Il remplace le bot auquel wecom-cli est lié sur cet ordinateur, y compris le wecom-cli de votre terminal.', + 'bot.bound': 'Bot lié : {id}', + 'action.open': 'Ouvrir la page du code QR', + 'action.cancel': 'Annuler', + 'action.retry': 'Réessayer', + 'badge.connected': 'Autorisé', + 'badge.disconnected': 'Non autorisé', + 'badge.connecting': 'Autorisation en cours', + 'badge.unavailable': 'Non confirmé', + 'activation.title': 'Connecter WeCom', + 'activation.body': 'Le plugin WeCom est activé. Scannez un code QR pour l’autoriser, puis utilisez-le dans les conversations.', + 'notice.connected': 'WeCom autorisé', +} + +/** German dictionary. */ +export const de: Record = { + 'section.title': 'WeCom-Autorisierung', + 'status.checking': 'Autorisierung wird geprüft', + 'status.disconnected': 'Nicht autorisiert', + 'status.unavailable': 'Autorisierung kann gerade nicht gelesen werden', + 'status.connected': 'Autorisiert', + 'step.authorizing': 'Warten auf das Scannen des QR-Codes', + 'step.connecting': 'Autorisierung wird bestätigt', + 'detail.disconnected': 'Scannen Sie mit WeCom einen QR-Code, um einen smarten Bot zu verknüpfen. Danach können Sie über diesen Bot Dokumente, Kalender, Besprechungen, Aufgaben, Nachrichten und weitere Funktionen von WeCom in Unterhaltungen verwenden.', + 'detail.unavailable': 'Die Autorisierung von wecom-cli konnte nicht gelesen werden. Versuchen Sie es später erneut.', + 'detail.connected': 'Bitten Sie den Agenten, WeCom direkt in einer Unterhaltung zu verwenden.', + 'detail.authorizing': 'Scannen Sie auf der geöffneten Seite den QR-Code mit WeCom, bestätigen Sie und kehren Sie dann hierher zurück, um das Ergebnis zu sehen. Falls sich die Seite nicht geöffnet hat, wählen Sie „QR-Code-Seite öffnen“.', + 'skills.downloading': 'Die Fertigkeiten von WeCom werden von GitHub heruntergeladen. Sie stehen in Unterhaltungen zur Verfügung, sobald der Download abgeschlossen ist.', + 'skills.failed': 'Die Fertigkeiten von WeCom konnten nicht heruntergeladen werden, daher kann der Agent die WeCom-Anleitungen noch nicht verwenden. Prüfen Sie, ob dieser Computer GitHub erreichen kann, und versuchen Sie es dann erneut.', + hint: 'Die Autorisierung wird mit wecom-cli im Terminal dieses Computers geteilt. Wenn Sie das Plugin deaktivieren, wird sie nicht widerrufen.', + failed: 'Die Aktion wurde nicht abgeschlossen. Versuchen Sie es erneut.', + 'action.connect': 'WeCom verbinden', + 'action.rebind': 'Bot wechseln', + 'rebind.title': 'Bot wechseln?', + 'rebind.body': 'Sie scannen einen QR-Code, um einen anderen Smart-Bot zu binden. Er ersetzt den Bot, an den wecom-cli auf diesem Computer gebunden ist, einschließlich des wecom-cli in Ihrem Terminal.', + 'bot.bound': 'Gebundener Bot: {id}', + 'action.open': 'QR-Code-Seite öffnen', + 'action.cancel': 'Abbrechen', + 'action.retry': 'Erneut versuchen', + 'badge.connected': 'Autorisiert', + 'badge.disconnected': 'Nicht autorisiert', + 'badge.connecting': 'Wird autorisiert', + 'badge.unavailable': 'Unbestätigt', + 'activation.title': 'WeCom verbinden', + 'activation.body': 'Das WeCom-Plugin ist aktiviert. Scannen Sie einen QR-Code, um es zu autorisieren, und verwenden Sie es dann in Unterhaltungen.', + 'notice.connected': 'WeCom autorisiert', +} + +/** Russian dictionary. */ +export const ru: Record = { + 'section.title': 'Авторизация WeCom', + 'status.checking': 'Проверка авторизации', + 'status.disconnected': 'Не авторизовано', + 'status.unavailable': 'Сейчас не удаётся прочитать состояние авторизации', + 'status.connected': 'Авторизовано', + 'step.authorizing': 'Ожидание сканирования QR-кода', + 'step.connecting': 'Подтверждение авторизации', + 'detail.disconnected': 'Отсканируйте QR-код в WeCom, чтобы привязать умного бота. После этого в беседах через этого бота можно будет использовать документы, календарь, встречи, задачи, сообщения и другие функции WeCom.', + 'detail.unavailable': 'Не удалось прочитать авторизацию wecom-cli. Повторите попытку позже.', + 'detail.connected': 'Попросите агента использовать WeCom прямо в беседе.', + 'detail.authorizing': 'Отсканируйте QR-код в WeCom на открывшейся странице и подтвердите, затем вернитесь сюда, чтобы увидеть результат. Если страница не открылась, нажмите «Открыть страницу с QR-кодом».', + 'skills.downloading': 'Навыки WeCom загружаются с GitHub. Они станут доступны в беседах, когда загрузка завершится.', + 'skills.failed': 'Не удалось загрузить навыки WeCom, поэтому агент пока не может использовать руководства WeCom. Убедитесь, что этот компьютер может подключиться к GitHub, затем повторите попытку.', + hint: 'Авторизация общая с wecom-cli в терминале этого компьютера. Отключение плагина её не отменяет.', + failed: 'Действие не завершено. Повторите попытку.', + 'action.connect': 'Подключить WeCom', + 'action.rebind': 'Сменить бота', + 'rebind.title': 'Сменить бота?', + 'rebind.body': 'Вы отсканируете QR-код, чтобы привязать другого умного бота. Он заменит бота, к которому привязан wecom-cli на этом компьютере, включая wecom-cli в вашем терминале.', + 'bot.bound': 'Привязанный бот: {id}', + 'action.open': 'Открыть страницу с QR-кодом', + 'action.cancel': 'Отмена', + 'action.retry': 'Повторить', + 'badge.connected': 'Авторизовано', + 'badge.disconnected': 'Не авторизовано', + 'badge.connecting': 'Авторизация', + 'badge.unavailable': 'Не подтверждено', + 'activation.title': 'Подключить WeCom', + 'activation.body': 'Плагин WeCom включён. Отсканируйте QR-код, чтобы авторизовать его, и используйте его в беседах.', + 'notice.connected': 'WeCom авторизован', +} + +/** Portuguese dictionary. */ +export const pt: Record = { + 'section.title': 'Autorização do WeCom', + 'status.checking': 'Verificando a autorização', + 'status.disconnected': 'Não autorizado', + 'status.unavailable': 'Não é possível ler a autorização no momento', + 'status.connected': 'Autorizado', + 'step.authorizing': 'Aguardando a leitura do código QR', + 'step.connecting': 'Confirmando a autorização', + 'detail.disconnected': 'Leia um código QR com o WeCom para vincular um bot inteligente. Depois disso, você poderá usar nas conversas, por meio desse bot, os documentos, a agenda, as reuniões, as tarefas, as mensagens e outros recursos do WeCom.', + 'detail.unavailable': 'Não foi possível ler a autorização do wecom-cli. Tente novamente mais tarde.', + 'detail.connected': 'Peça ao agente que use o WeCom diretamente em uma conversa.', + 'detail.authorizing': 'Leia o código QR com o WeCom na página que foi aberta e confirme; depois volte aqui para ver o resultado. Se a página não abriu, selecione “Abrir página do código QR”.', + 'skills.downloading': 'Baixando as habilidades do WeCom do GitHub. Elas ficarão disponíveis nas conversas quando o download terminar.', + 'skills.failed': 'Não foi possível baixar as habilidades do WeCom, então o agente ainda não pode usar os guias do WeCom. Verifique se este computador consegue acessar o GitHub e tente novamente.', + hint: 'A autorização é compartilhada com o wecom-cli no terminal deste computador. Desativar o plugin não a revoga.', + failed: 'A ação não foi concluída. Tente novamente.', + 'action.connect': 'Conectar WeCom', + 'action.rebind': 'Trocar bot', + 'rebind.title': 'Trocar o bot?', + 'rebind.body': 'Você vai escanear um QR code para vincular outro bot inteligente. Ele substitui o bot ao qual o wecom-cli está vinculado neste computador, incluindo o wecom-cli do seu terminal.', + 'bot.bound': 'Bot vinculado: {id}', + 'action.open': 'Abrir página do código QR', + 'action.cancel': 'Cancelar', + 'action.retry': 'Tentar novamente', + 'badge.connected': 'Autorizado', + 'badge.disconnected': 'Não autorizado', + 'badge.connecting': 'Autorizando', + 'badge.unavailable': 'Não confirmado', + 'activation.title': 'Conectar WeCom', + 'activation.body': 'O plugin do WeCom está ativado. Leia um código QR para autorizá-lo e depois use-o nas conversas.', + 'notice.connected': 'WeCom autorizado', +} + +/** The dictionary of every shipped language. */ +export const dictionaries = { zh, en, ja, es, fr, de, ru, pt } diff --git a/packages/connector/wecom/src/presentation.ts b/packages/connector/wecom/src/presentation.ts new file mode 100644 index 0000000000..86b1bc2d03 --- /dev/null +++ b/packages/connector/wecom/src/presentation.ts @@ -0,0 +1,116 @@ +/** The WeCom authorization section the Plugins page shows for each Host view. */ +import type { CliAccountText } from '@deepseek-ai/dsh-cli-account/types' +import type { + ConnectorAccountButton, ConnectorAccountCopy, ConnectorAccountDisplay, ConnectorAccountFailure, ConnectorAccountNote, + ConnectorAccountOperation, +} from '@deepseek-ai/dsh-client-ui-connector-account/types' +import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' +import { assertNever } from '@deepseek-ai/dsh-util-values' +import type { WecomTextKey } from './locales.ts' +import type { WecomOperationKind, WecomState } from './types.ts' + +type Text = CliAccountText + +/** The npm package whose bundle page carries the authorization section. */ +export const WECOM_PACKAGE = '@deepseek-ai/dsh-wecom' + +/* jscpd:ignore-start -- CLI app plugins declare page operations, copy, and commands alike, each with its own text. */ +/** + * List the operations the section's buttons start; binding a bot reports a notice in the browser that started it. + * @param text - writes a key of the WeCom text in every shipped language. + * @returns the operations with their notices. + */ +export function operations(text: Text): readonly ConnectorAccountOperation[] { + return [ + { kind: 'check' }, + { kind: 'connect', notice: text('notice.connected') }, + ] +} + +/** + * Write the section's title and hint, and the prompt after the bundle is switched on while unauthorized. + * @param text - writes a key of the WeCom text in every shipped language. + * @returns the section's fixed text. + */ +export function copy(text: Text): ConnectorAccountCopy { + return { + title: text('section.title'), + hint: text('hint'), + activation: { title: text('activation.title'), body: text('activation.body'), connect: text('action.connect') }, + } +} + +const CHECK = { kind: 'start', operation: 'check' } as const +const CONNECT = { kind: 'start', operation: 'connect' } as const +/* jscpd:ignore-end */ + +/* jscpd:ignore-start -- CLI app plugins whose guides download report the same states, each in its own text. */ +/** The row that reports guides that are not in place yet; a failed download offers a check, which restarts it. */ +function skillsNotes(skills: UpstreamSkillsState, text: Text): ConnectorAccountNote[] { + switch (skills) { + case 'installed': return [] + case 'downloading': return [{ text: text('skills.downloading') }] + case 'failed': return [{ text: text('skills.failed'), button: { label: text('action.retry'), command: CHECK } }] + /* v8 ignore next -- closed skills state union */ + default: return assertNever(skills) + } +} +/* jscpd:ignore-end */ + +/** The bound bot's QR-code page and the operation's cancel, while an authorization runs. */ +function connectingButtons(operation: NonNullable, text: Text): ConnectorAccountButton[] { + const buttons: ConnectorAccountButton[] = [] + if (operation.authorizationUrl !== undefined) buttons.push({ label: text('action.open'), command: { kind: 'open' }, variant: 'primary' }) + if (operation.cancellable) buttons.push({ label: text('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }) + return buttons +} + +/** + * The authorization section for one Host view. + * @param view - the authorization, the operation in progress, and the last result. + * @param text - writes a key of the WeCom text in every shipped language. + * @returns the phase, status, tag, buttons, detail, bound-bot and guide download rows, and failure guidance. + */ +export function presentAccount(view: WecomState, text: Text): ConnectorAccountDisplay { + const notes = skillsNotes(view.account.skills, text) + const { operation } = view + if (operation?.kind === 'check') return { phase: 'checking', status: text('status.checking'), buttons: [], notes } + if (operation !== undefined) { + return { + phase: 'connecting', status: text(operation.phase === 'authorizing' ? 'step.authorizing' : 'step.connecting'), + badge: text('badge.connecting'), buttons: connectingButtons(operation, text), notes, + ...operation.authorizationUrl === undefined ? {} : { detail: text('detail.authorizing') }, + } + } + const failed = view.result?.outcome === 'failed' + // The Service adds the failed command and its exit code. + const failure: { failure?: ConnectorAccountFailure } = failed ? { failure: { text: text('failed') } } : {} + switch (view.account.state) { + case 'unchecked': + if (!failed) return { phase: 'checking', status: text('status.checking'), buttons: [], notes } + return { + phase: 'unavailable', status: text('status.unavailable'), badge: text('badge.unavailable'), + buttons: [{ label: text('action.retry'), command: CHECK }], detail: text('detail.unavailable'), notes, ...failure, + } + case 'unauthorized': + return { + phase: 'disconnected', status: text('status.disconnected'), badge: text('badge.disconnected'), + buttons: [{ label: text('action.connect'), command: CONNECT, variant: 'primary' }], connect: CONNECT, + detail: text('detail.disconnected'), notes, ...failure, + } + case 'authorized': + return { + phase: 'connected', status: text('status.connected'), badge: text('badge.connected'), + // Binding again replaces the bot in the CLI's configuration, which the terminal shares, so it asks first. + buttons: [{ + label: text('action.rebind'), command: CONNECT, + confirm: { title: text('rebind.title'), body: text('rebind.body'), label: text('action.rebind') }, + }], + detail: text('detail.connected'), + notes: [...view.account.botId === undefined ? [] : [{ text: text('bot.bound', { id: view.account.botId }) }], ...notes], + ...failure, + } + /* v8 ignore next -- closed account state union */ + default: return assertNever(view.account.state) + } +} diff --git a/packages/connector/wecom/src/skills.ts b/packages/connector/wecom/src/skills.ts new file mode 100644 index 0000000000..91491eb4f6 --- /dev/null +++ b/packages/connector/wecom/src/skills.ts @@ -0,0 +1,18 @@ +/** The packaged `wecom` entry skill and the upstream guides it indexes. */ + +import { fileURLToPath } from 'node:url' +import type { UpstreamSkillSet } from '@deepseek-ai/dsh-upstream-skills' + +/** The packaged entry, whose index names each guide by its repository path `skills//SKILL.md`. */ +export const ENTRY = fileURLToPath(new URL('../skills/wecom/SKILL.md', import.meta.url)) + +/** Every skill of the official WeCom CLI repository, at the commit the entry's index and guidance were verified with. */ +export const WECOM_SKILLS: UpstreamSkillSet = { + repository: 'WecomTeam/wecom-cli', + commit: '4c74ff28838d8fba267eaab5179d9d56f9ca61ae', + directory: 'skills', + exclude: [], + license: 'LICENSE', + bytes: 1_754_686, + sha256: 'c75045cc5297d5886c8a7ff01c993a782e50cbd4aa6f6559394b695157d52e10', +} diff --git a/packages/connector/wecom/src/types.ts b/packages/connector/wecom/src/types.ts new file mode 100644 index 0000000000..39bea76947 --- /dev/null +++ b/packages/connector/wecom/src/types.ts @@ -0,0 +1,25 @@ +/** Credential-free WeCom authorization and operation views the Plugins page presenter reads. */ + +import type { CliAccountView } from '@deepseek-ai/dsh-cli-account/types' +import type { UpstreamSkillsState } from '@deepseek-ai/dsh-upstream-skills/types' + +/** The CLI's authorization as the latest `auth show` reported it, and where the upstream guides stand. */ +export interface WecomAccountState { + readonly state: 'unchecked' | 'unauthorized' | 'authorized' + /** The bound bot's id, when the CLI reports one with an authorized state. */ + readonly botId?: string + /** Whether the guides the `wecom` skill indexes are in place, downloading, or unavailable until a check retries them. */ + readonly skills: UpstreamSkillsState +} + +/** The operations the Plugins page starts. */ +export type WecomOperationKind = 'check' | 'connect' + +/** The WeCom step of an operation, besides the Service's `checking` and `cancelling`. */ +export type WecomPhase = 'authorizing' + +/** The wecom-cli commands an operation runs; a failed operation reports its last one with that command's exit code. */ +export type WecomCommand = 'auth-init' | 'auth-status' + +/** The complete WeCom view the presenter reads after each change. */ +export type WecomState = CliAccountView diff --git a/packages/connector/wecom/tests/account.spec.ts b/packages/connector/wecom/tests/account.spec.ts new file mode 100644 index 0000000000..e7f74ae04d --- /dev/null +++ b/packages/connector/wecom/tests/account.spec.ts @@ -0,0 +1,230 @@ +/** Authorization operations over a scripted wecom-cli: checks, QR-code connection, cancellation, and the Plugins page wiring. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import type { ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { executableFileName } from '../src/directory.ts' +import * as Wecom from '../src/index.ts' +import type { WecomOperationKind, WecomState } from '../src/types.ts' +import { createHost, type CliReply, type ScriptedProcess, type ScriptedSubprocess, type WecomPage } from './harness.ts' + +const STATUS = 'auth show' +const INIT = 'auth init --noninteractive --no-browser' +const QR_LINK = 'https://work.weixin.qq.com/ai/qc/gen?source=wecom-cli&scode=fixture-scode' +const AUTHORIZED: CliReply = { stdout: 'Status: authorized\nBot ID: bot-1\n' } +const UNAUTHORIZED: CliReply = { stdout: 'Status: unauthorized\n' } + +type Script = (process: ScriptedProcess) => void + +let ctx: Context +let subprocess: ScriptedSubprocess +let binDir: string +let skillsDir: string +/** The account the plugin registered, as the Plugins page registry drives it. */ +let account: WecomPage['source'] +let script: Record + +/** Start a Host and load the plugin on it; without `skillsDir` the plugin downloads the guides. */ +async function load(config: Pick | 'configured' = 'configured'): Promise { + const host = await createHost() + ;({ ctx, subprocess, binDir, skillsDir } = host) + subprocess.respond = (process) => { + const handler = script[process.spec.argv.slice(1).join(' ')] + if (handler === undefined) process.reply({ exitCode: 1, stderr: `unexpected: ${process.spec.argv.join(' ')}` }) + else if (Array.isArray(handler)) process.reply(handler.length > 1 ? handler.shift()! : handler[0]!) + else handler(process) + } + await ctx.plugin(Wecom, { binDir, ...config === 'configured' ? { skillsDir } : config }) + account = host.pages[0]!.source +} + +beforeEach(() => { + script = {} +}) + +afterEach(async () => { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + vi.unstubAllGlobals() + await rm(binDir, { recursive: true, force: true }) + await rm(skillsDir, { recursive: true, force: true }) +}) + +/** Start an operation as a page button does; the CLI account Service starts it before returning. */ +const start = (kind: WecomOperationKind): ConnectorOperationId => { + const id = account.start(kind) + if (typeof id !== 'string') throw new Error('the operation did not start at once') + return id +} +const commands = () => subprocess.processes.map(process => process.spec.argv.slice(1).join(' ')) +const errors = (): unknown[] => ctx.logger.buffer.filter(message => message.type === 'error').map((message): unknown => message.args) +const settled = async (id: ConnectorOperationId): Promise => { + await vi.waitFor(() => { expect(account.snapshot().result?.id).toBe(id) }) + return account.snapshot() +} + +describe('WeCom account operations', () => { + beforeEach(() => load()) + + it.each<[string, CliReply, WecomState['account']]>([ + ['an authorized bot', AUTHORIZED, { state: 'authorized', botId: 'bot-1', skills: 'installed' }], + ['an authorized bot whose id the CLI omits', { stdout: 'Status: authorized\n' }, { state: 'authorized', skills: 'installed' }], + ['no authorization', UNAUTHORIZED, { state: 'unauthorized', skills: 'installed' }], + ])('checks %s', async (_name, reply, expected) => { + script[STATUS] = [reply] + const id = start('check') + expect(account.snapshot().operation).toEqual({ id, kind: 'check', phase: 'checking', cancellable: false }) + expect(await settled(id)).toEqual({ account: expected, result: { id, kind: 'check', outcome: 'succeeded' } }) + }) + + it.each<[string, CliReply]>([ + ['a failed status command', { exitCode: 1, stderr: 'config unreadable' }], + ['an unknown status', { stdout: 'expired\n' }], + ])('keeps the previous state and reports only the command and exit code on %s', async (_name, reply) => { + script[STATUS] = [reply] + const result = await settled(start('check')) + expect(result).toEqual({ + account: { state: 'unchecked', skills: 'installed' }, + result: { id: result.result?.id, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: reply.exitCode ?? 0 } }, + }) + expect(errors()).toEqual([['wecom: account operation failed: %o', { + id: result.result?.id, kind: 'check', phase: 'checking', command: 'auth-status', exitCode: reply.exitCode ?? 0, + }]]) + }) + + it('connects through the QR-code page, offers only trusted links, and confirms the authorization', async () => { + script[STATUS] = [AUTHORIZED] + const init = Promise.withResolvers() + script[INIT] = (process) => { init.resolve(process) } + + const offered: string[] = [] + const stop = account.observe(() => { + const url = account.snapshot().operation?.authorizationUrl + if (url !== undefined && offered.at(-1) !== url) offered.push(url) + }) + const id = start('connect') + expect(account.snapshot().operation).toEqual({ id, kind: 'connect', phase: 'authorizing', cancellable: true }) + const authorizing = await init.promise + authorizing.write('stderr', 'https://work.weixin.qq.com/ai/qc/gen?source=stderr\n') + authorizing.write('stdout', 'Scan the QR code with WeCom:\n http://work.weixin.qq.com/insecure\nhttps://evil.example/qr\n') + authorizing.write('stdout', `${QR_LINK}\n`) + await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: QR_LINK }) }) + authorizing.reply({ stdout: 'Authorized\n' }) + + expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1', skills: 'installed' }, result: { id, kind: 'connect', outcome: 'succeeded' } }) + stop() + expect(offered).toEqual([QR_LINK]) + expect(commands()).toEqual([INIT, STATUS]) + expect(errors()).toEqual([]) + }) + + it.each<[string, Record, NonNullable['failure']]>([ + ['a failed QR-code authorization', { [INIT]: [{ exitCode: 2, stdout: `${QR_LINK}\nscode=secret` }] }, { command: 'auth-init', exitCode: 2 }], + ['an authorization that left no bot', { [INIT]: [{}], [STATUS]: [UNAUTHORIZED] }, { command: 'auth-status', exitCode: 0 }], + ])('fails on %s without exposing CLI output', async (_name, replies, failure) => { + Object.assign(script, replies) + const result = await settled(start('connect')) + expect(result.result).toMatchObject({ kind: 'connect', outcome: 'failed', failure }) + expect(JSON.stringify({ result, errors: errors() })).not.toContain('scode') + }) + + it('cancels only while waiting for the scan and withdraws the link', async () => { + script[INIT] = (process) => { process.write('stdout', `${QR_LINK}\n`) } + const id = start('connect') + await vi.waitFor(() => { expect(account.snapshot().operation?.authorizationUrl).toBe(QR_LINK) }) + await account.cancel('other' as ConnectorOperationId) + expect(account.snapshot().operation?.phase).toBe('authorizing') + + const cancelling = account.cancel(id) + expect(account.snapshot().operation).toEqual({ id, kind: 'connect', phase: 'cancelling', cancellable: false }) + await cancelling + expect(account.snapshot()).toEqual({ account: { state: 'unchecked', skills: 'installed' }, result: { id, kind: 'connect', outcome: 'cancelled' } }) + expect(subprocess.processes[0]?.terminated).toBe(true) + expect(errors()).toEqual([]) + }) + + it('ignores cancellation while it confirms the authorization', async () => { + script[INIT] = [{}] + const status = Promise.withResolvers() + script[STATUS] = (process) => { status.resolve(process) } + const id = start('connect') + const checking = await status.promise + expect(account.snapshot().operation).toEqual({ id, kind: 'connect', phase: 'checking', cancellable: false }) + await account.cancel(id) + checking.reply(AUTHORIZED) + expect((await settled(id)).result).toEqual({ id, kind: 'connect', outcome: 'succeeded' }) + }) +}) + +describe('WeCom guides the plugin downloads', () => { + let home: string + /** Answers each request for the guides' archive. */ + let archive: () => Promise + + beforeEach(async () => { + home = await mkdtemp(join(tmpdir(), 'dsh-wecom-home-')) + vi.stubEnv('DSH_HOME', home) + vi.stubGlobal('fetch', () => archive()) + }) + + afterEach(() => rm(home, { recursive: true, force: true })) + + it('restarts a failed download of the guides on each check without waiting for it, and reports the state it leaves', async () => { + archive = () => Promise.reject(new Error('offline')) + await load({}) + await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }) + + archive = () => new Promise(() => {}) + script[STATUS] = [AUTHORIZED] + const id = start('check') + expect(account.snapshot().account).toEqual({ state: 'unchecked', skills: 'downloading' }) + expect(await settled(id)).toEqual({ account: { state: 'authorized', botId: 'bot-1', skills: 'downloading' }, result: { id, kind: 'check', outcome: 'succeeded' } }) + }) + + it('reports a new state of the guides with the current authorization', async () => { + const download = Promise.withResolvers() + archive = () => download.promise + await load({}) + script[STATUS] = [AUTHORIZED] + expect((await settled(start('check'))).account).toEqual({ state: 'authorized', botId: 'bot-1', skills: 'downloading' }) + + download.reject(new Error('offline')) + + await vi.waitFor(() => { expect(account.snapshot().account).toEqual({ state: 'authorized', botId: 'bot-1', skills: 'failed' }) }) + }) +}) + +describe('WeCom on the Plugins page', () => { + beforeEach(() => load()) + + const finished = async (id: ConnectorOperationId): Promise => (await settled(id)).result + + it('checks on refresh, then starts checks and connections one at a time and cancels one waiting for the scan', async () => { + script[STATUS] = [UNAUTHORIZED] + account.refresh() + const check = account.snapshot().operation + expect(account.snapshot()).toMatchObject({ account: { state: 'unchecked', skills: 'installed' }, operation: { kind: 'check' } }) + expect(await finished(check!.id)).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + expect(account.snapshot().account).toEqual({ state: 'unauthorized', skills: 'installed' }) + expect(subprocess.lookups[0]?.command).toBe(join(binDir, executableFileName(process.platform))) + expect(await finished(start('check'))).toMatchObject({ kind: 'check', outcome: 'succeeded' }) + + script[INIT] = () => {} + const connecting = start('connect') + expect(() => start('check')).toThrow('another account operation is in progress') + await vi.waitFor(() => { expect(commands().at(-1)).toBe(INIT) }) + await account.cancel(connecting) + expect(await finished(connecting)).toMatchObject({ kind: 'connect', outcome: 'cancelled' }) + expect(subprocess.processes.at(-1)?.terminated).toBe(true) + }) + + it('stops authorization work on disposal', async () => { + script[STATUS] = () => {} + account.refresh() + await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) + await ctx.fiber.dispose() + expect(subprocess.processes[0]?.terminated).toBe(true) + }) +}) diff --git a/packages/connector/wecom/tests/directory.spec.ts b/packages/connector/wecom/tests/directory.spec.ts new file mode 100644 index 0000000000..0d0b7c382e --- /dev/null +++ b/packages/connector/wecom/tests/directory.spec.ts @@ -0,0 +1,44 @@ +import { constants } from 'node:fs' +import { createRequire } from 'node:module' +import { dirname, join } from 'node:path' +import { beforeEach, expect, it, onTestFinished, vi } from 'vitest' +import { executableFileName, resolveCliExecutable } from '../src/directory.ts' + +const FILE = process.platform === 'win32' ? 'wecom-cli.exe' : 'wecom-cli' + +const fs = vi.hoisted(() => ({ accessSync: vi.fn() })) +vi.mock('node:fs', async importOriginal => ({ ...await importOriginal(), accessSync: fs.accessSync })) + +const PLATFORM_PACKAGE = `@wecom/cli-${process.platform}-${process.arch}` +const PACKAGE_BIN = join( + dirname(createRequire(import.meta.resolve('@wecom/cli/package.json')).resolve(`${PLATFORM_PACKAGE}/package.json`)), 'bin', +) + +beforeEach(() => { + fs.accessSync.mockReset() +}) + +it('names the executable file with the .exe extension on Windows only', () => { + expect(executableFileName('win32')).toBe('wecom-cli.exe') + expect(executableFileName('darwin')).toBe('wecom-cli') +}) + +it('defaults to the executable in the bin directory of the platform package that @wecom/cli installs', () => { + expect(resolveCliExecutable(undefined)).toBe(join(PACKAGE_BIN, FILE)) + expect(fs.accessSync).toHaveBeenCalledWith(join(PACKAGE_BIN, FILE), constants.X_OK) +}) + +it('names the platform package @wecom/cli does not provide', () => { + const arch = Object.getOwnPropertyDescriptor(process, 'arch')! + Object.defineProperty(process, 'arch', { ...arch, value: 'fixture-arch' }) + onTestFinished(() => { Object.defineProperty(process, 'arch', arch) }) + expect(() => resolveCliExecutable(undefined)) + .toThrow(`wecom: @wecom/cli-${process.platform}-fixture-arch is not installed; @wecom/cli has no binary for this platform, or set binDir`) +}) + +it('accepts a configured directory and names the missing executable with the remedy', () => { + expect(resolveCliExecutable('/opt/wecom/bin')).toBe(join('/opt/wecom/bin', FILE)) + fs.accessSync.mockImplementation(() => { throw new Error('EACCES') }) + expect(() => resolveCliExecutable(PACKAGE_BIN)) + .toThrow(`wecom: ${join(PACKAGE_BIN, FILE)} is not executable; reinstall the plugin or set binDir`) +}) diff --git a/packages/connector/wecom/tests/harness.ts b/packages/connector/wecom/tests/harness.ts new file mode 100644 index 0000000000..ed266b40f0 --- /dev/null +++ b/packages/connector/wecom/tests/harness.ts @@ -0,0 +1,164 @@ +/** + * A Host for WeCom plugin specs: scripted wecom-cli processes, a temporary bin directory and guides directory, and a + * recording Plugins page registry. + */ + +import { chmod, mkdtemp, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { PassThrough } from 'node:stream' +import { Context } from '@deepseek-ai/cordis' +import CliAccounts from '@deepseek-ai/dsh-cli-account' +import type { ConnectorAccountRegistration } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import SkillRegistry from '@deepseek-ai/dsh-skill' +import { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess' +import type { + SubprocessCollectedOutputs, + SubprocessHandle, + SubprocessOutcome, + SubprocessSpawnSpec, + SubprocessTerminalEnvironment, +} from '@deepseek-ai/dsh-subprocess' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import UpstreamSkills, { type Config as UpstreamSkillsConfig } from '@deepseek-ai/dsh-upstream-skills' +import { executableFileName } from '../src/directory.ts' +import type { WecomState } from '../src/types.ts' + +/** Output and exit facts one scripted command reports. */ +export interface CliReply { + stdout?: string + stderr?: string + exitCode?: number | null + signal?: NodeJS.Signals | null +} + +/** A piped process whose managed range exits on termination. */ +export class ScriptedProcess implements SubprocessHandle { + readonly stdin = undefined + readonly stdout = new PassThrough() + readonly stderr = new PassThrough() + readonly control = undefined + readonly collected: SubprocessCollectedOutputs = {} + readonly done: Promise + terminated = false + private readonly outcome = Promise.withResolvers() + private readonly exit = Promise.withResolvers() + + constructor(readonly spec: SubprocessSpawnSpec) { + this.done = this.outcome.promise + spec.signal?.addEventListener('abort', () => { this.terminate() }, { once: true }) + } + + /** Write output while the command keeps running. */ + write(stream: 'stdout' | 'stderr', text: string): void { + this[stream].write(text) + } + + /** Finish the command with the given output; the managed range stays alive until termination. */ + reply(reply: CliReply): void { + if (reply.stdout !== undefined) this.stdout.write(reply.stdout) + if (reply.stderr !== undefined) this.stderr.write(reply.stderr) + this.close() + this.outcome.resolve({ exitCode: reply.exitCode === undefined ? 0 : reply.exitCode, signal: reply.signal ?? null }) + } + + terminate(): void { + this.terminated = true + this.close() + this.outcome.resolve({ exitCode: null, signal: 'SIGTERM' }) + this.exit.resolve(true) + } + + private close(): void { + if (!this.stdout.writableEnded) this.stdout.end() + if (!this.stderr.writableEnded) this.stderr.end() + } + + waitForExit(): Promise { + return this.exit.promise + } +} + +/** Host subprocess runtime whose lookups and spawns are recorded and answered by `respond`. */ +export class ScriptedSubprocess extends SubprocessRuntime { + readonly lookups: Array<{ command: string; env: Readonly> | undefined }> = [] + readonly processes: ScriptedProcess[] = [] + lookup: (signal?: AbortSignal) => Promise = () => Promise.resolve('/fixture/bin/wecom-cli') + respond: (process: ScriptedProcess) => void | Promise = (process) => { process.reply({ stdout: '{}' }) } + + override resolveExecutable(command: string, env?: Readonly>, signal?: AbortSignal): Promise { + this.lookups.push({ command, env }) + return this.lookup(signal) + } + + override terminalEnvironment(): Promise { + return Promise.resolve({ platform: 'posix' }) + } + + override spawn(spec: SubprocessSpawnSpec): ScriptedProcess { + spec.signal?.throwIfAborted() + const process = new ScriptedProcess(spec) + this.processes.push(process) + queueMicrotask(() => { void this.respond(process) }) + return process + } + + override spawnTerminal(): Promise { + throw new Error('wecom-cli commands never allocate a terminal') + } +} + +/** + * Create a temporary directory holding an executable `wecom-cli` placeholder, `wecom-cli.exe` on Windows. + * @returns the absolute bin directory. + */ +export async function createBinDir(): Promise { + const directory = await mkdtemp(join(tmpdir(), 'dsh-wecom-bin-')) + await writeFile(join(directory, executableFileName(process.platform)), '') + await chmod(join(directory, executableFileName(process.platform)), 0o755) + return directory +} + +/** What the WeCom plugin registers for the Plugins page. */ +export type WecomPage = ConnectorAccountRegistration + +/** The services the WeCom plugin runs on, before the plugin itself loads. */ +export interface WecomHost { + readonly ctx: Context + readonly subprocess: ScriptedSubprocess + /** The `binDir` to load the plugin with. */ + readonly binDir: string + /** An empty directory to load the plugin with as `skillsDir`, so that it downloads nothing. */ + readonly skillsDir: string + /** Every account registered for the Plugins page, in order; the registry keeps them after withdrawal. */ + readonly pages: WecomPage[] + /** How many of those accounts were withdrawn. */ + withdrawn: number +} + +/** + * Start a Host with the skill registry, a scripted subprocess runtime, the system prompt, a Plugins page registry that + * records registrations, the CLI account Service with a 5-second command deadline, and the upstream skills Service. + * @param skills - where the upstream skills Service downloads from; defaults to the Service's own defaults. + * @returns the Host; the caller loads the WeCom plugin with `binDir`, disposes `ctx.fiber`, and removes `binDir` and + * `skillsDir`. + */ +export async function createHost(skills: Partial = {}): Promise { + const ctx = new Context() + await ctx.plugin(SkillRegistry) + await ctx.plugin(ScriptedSubprocess) + await ctx.plugin(SystemPrompt) + const host: WecomHost = { + ctx, subprocess: ctx.subprocess as ScriptedSubprocess, binDir: await createBinDir(), + skillsDir: await mkdtemp(join(tmpdir(), 'dsh-wecom-skills-')), pages: [], withdrawn: 0, + } + ctx.provide('connectorAccounts', { + register: (page: WecomPage) => { + host.pages.push(page) + return () => { host.withdrawn += 1 } + }, + }) + await ctx.plugin(CliAccounts, { commandTimeoutMs: 5_000 }) + await ctx.plugin(UpstreamSkills, skills) + return host +} diff --git a/packages/connector/wecom/tests/plugin.spec.ts b/packages/connector/wecom/tests/plugin.spec.ts new file mode 100644 index 0000000000..b958e87041 --- /dev/null +++ b/packages/connector/wecom/tests/plugin.spec.ts @@ -0,0 +1,99 @@ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import type { Context } from '@deepseek-ai/cordis' +import { renderContextSections } from '@deepseek-ai/dsh-system-prompt' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cliPathContextText } from '@deepseek-ai/dsh-cli-account/src/context.ts' +import { executableFileName } from '../src/directory.ts' +import * as Wecom from '../src/index.ts' +import { WECOM_PACKAGE } from '../src/presentation.ts' +import { createHost, type WecomHost } from './harness.ts' + +describe('Config', () => { + it('takes the CLI directory and the guides directory, which are optional and never empty', () => { + expect(Wecom.Config({})).toEqual({}) + expect(Wecom.Config({ binDir: '/opt/wecom/bin', skillsDir: '/opt/wecom/skills' })).toEqual({ binDir: '/opt/wecom/bin', skillsDir: '/opt/wecom/skills' }) + expect(() => Wecom.Config({ binDir: '' })).toThrow() + expect(() => Wecom.Config({ skillsDir: '' })).toThrow() + }) +}) + +describe('WeCom plugin', () => { + let host: WecomHost + let ctx: Context + let binDir: string + let skillsDir: string + + /** Start the Host the plugin loads on; the upstream skills Service downloads from `skills`. */ + async function start(skills?: Parameters[0]): Promise { + host = await createHost(skills) + ;({ ctx, binDir, skillsDir } = host) + } + + afterEach(async () => { + await ctx.fiber.dispose() + vi.unstubAllEnvs() + await rm(binDir, { recursive: true, force: true }) + await rm(skillsDir, { recursive: true, force: true }) + }) + + const runtimeContext = async () => renderContextSections(await ctx.systemPrompt.assemble()) + + it('publishes one wecom entry skill over the configured guides, with a body that carries the DSH guidance', async () => { + await start() + await ctx.plugin(Wecom, { binDir, skillsDir }) + + const catalog = await ctx.skills.list() + expect(catalog.map(skill => `${skill.provider}/${skill.source}/${skill.name}`)).toEqual(['wecom/bundled/wecom']) + + const entry = await ctx.skills.get('wecom') + expect(entry?.content).toContain('`wecom-cli` 由企业微信插件安装,按当前 runtime context 给出的绝对路径运行,不要直接按名称运行') + expect(entry?.resourceBase).toEqual({ kind: 'directory', path: skillsDir }) + expect(await ctx.skills.get('wecomcli-shared')).toBeUndefined() + }) + + it('reports the guides as downloading and then failed when no skills URL answers, and lists no skill', async () => { + const home = await mkdtemp(join(tmpdir(), 'dsh-wecom-home-')) + vi.stubEnv('DSH_HOME', home) + try { + await start({ skillsUrls: ['https://127.0.0.1:9'], skillsTimeoutMs: 5_000 }) + await ctx.plugin(Wecom, { binDir }) + const account = host.pages[0]!.source + expect(account.snapshot().account.skills).toBe('downloading') + await vi.waitFor(() => { expect(account.snapshot().account.skills).toBe('failed') }, { timeout: 10_000 }) + expect(await ctx.skills.list()).toEqual([]) + } finally { + await rm(home, { recursive: true, force: true }) + } + }) + + it('gives the executable path and the script PATH prefix in runtime context, and withdraws them and the skills on disposal', async () => { + await start() + const fiber = await ctx.plugin(Wecom, { binDir, skillsDir }) + expect(await runtimeContext()).toEqual([{ + name: 'wecom:cli', + text: cliPathContextText({ + product: 'WeCom', program: 'wecom-cli', executable: join(binDir, executableFileName(process.platform)), scripts: true, + }, process.platform), + }]) + expect(await ctx.skills.list()).not.toEqual([]) + + await fiber.dispose() + + expect(await runtimeContext()).toEqual([]) + expect(await ctx.skills.list()).toEqual([]) + }) + + it('shows the authorization on the Plugins page while the registry runs, and withdraws it with the plugin', async () => { + await start() + const fiber = await ctx.plugin(Wecom, { binDir, skillsDir }) + expect(host.pages).toHaveLength(1) + expect(host.pages[0]).toMatchObject({ key: WECOM_PACKAGE, packageName: WECOM_PACKAGE }) + expect(host.pages[0]!.source.snapshot().account).toEqual({ state: 'unchecked', skills: 'installed' }) + + await fiber.dispose() + + expect(host.withdrawn).toBe(1) + }) +}) diff --git a/packages/connector/wecom/tests/presentation.spec.ts b/packages/connector/wecom/tests/presentation.spec.ts new file mode 100644 index 0000000000..fa421addf4 --- /dev/null +++ b/packages/connector/wecom/tests/presentation.spec.ts @@ -0,0 +1,117 @@ +/** The WeCom section offers each state's next step, the guide download rows, and failure guidance, in every shipped language. */ +import type { LocalizedText } from '@deepseek-ai/dsh-package-manifest' +import type { ConnectorAccountDisplay, ConnectorOperationId } from '@deepseek-ai/dsh-client-ui-connector-account/types' +import { rm } from 'node:fs/promises' +import { afterAll, beforeAll, expect, it } from 'vitest' +import * as Wecom from '../src/index.ts' +import { en, zh, type WecomTextKey } from '../src/locales.ts' +import type { WecomState } from '../src/types.ts' +import { createHost, type WecomHost, type WecomPage } from './harness.ts' + +const OP = 'op' as ConnectorOperationId +const QR = 'https://work.weixin.qq.com/qr' +const CHECK = { kind: 'start', operation: 'check' } as const +const CONNECT = { kind: 'start', operation: 'connect' } as const + +/** The key's text as the Chinese and English browsers resolve it. */ +const say = (key: WecomTextKey): Partial> => ({ zh: zh[key], en: en[key] }) +const zhOf = (text: LocalizedText | undefined): string | undefined => typeof text === 'object' ? text.zh : text +const labels = (display: ConnectorAccountDisplay): (string | undefined)[] => display.buttons.map(button => zhOf(button.label)) + +let host: WecomHost +/** What the plugin registered for the Plugins page, with the failure details the CLI account Service adds. */ +let page: WecomPage + +beforeAll(async () => { + host = await createHost() + await host.ctx.plugin(Wecom, { binDir: host.binDir, skillsDir: host.skillsDir }) + page = host.pages[0]! +}) + +afterAll(async () => { + await host.ctx.fiber.dispose() + await rm(host.binDir, { recursive: true, force: true }) + await rm(host.skillsDir, { recursive: true, force: true }) +}) + +const presentAccount = (view: WecomState): ConnectorAccountDisplay => page.present(view) + +const unauthorized = { state: 'unauthorized', skills: 'installed' } as const + +it('offers the next step for each state', () => { + let shown = presentAccount({ account: unauthorized }) + expect(shown).toMatchObject({ + phase: 'disconnected', status: say('status.disconnected'), badge: say('badge.disconnected'), + detail: say('detail.disconnected'), connect: CONNECT, notes: [], + }) + expect(shown.buttons).toMatchObject([{ label: say('action.connect'), command: CONNECT, variant: 'primary' }]) + + shown = presentAccount({ account: unauthorized, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true } }) + expect(shown).toMatchObject({ phase: 'connecting', status: say('step.authorizing'), badge: say('badge.connecting') }) + expect(shown.detail).toBeUndefined() + expect(shown.buttons).toMatchObject([{ label: say('action.cancel'), command: { kind: 'cancel' }, variant: 'ghost' }]) + + shown = presentAccount({ + account: unauthorized, operation: { id: OP, kind: 'connect', phase: 'authorizing', cancellable: true, authorizationUrl: QR }, + }) + expect(shown.detail).toMatchObject(say('detail.authorizing')) + expect(shown.buttons.map(button => button.command)).toEqual([{ kind: 'open' }, { kind: 'cancel' }]) + expect(labels(shown)).toEqual([zh['action.open'], zh['action.cancel']]) + + shown = presentAccount({ account: unauthorized, operation: { id: OP, kind: 'connect', phase: 'checking', cancellable: false } }) + expect(shown).toMatchObject({ status: say('step.connecting'), buttons: [] }) + + shown = presentAccount({ account: { state: 'authorized', botId: 'bot-1', skills: 'installed' } }) + expect(shown).toMatchObject({ phase: 'connected', status: say('status.connected'), badge: say('badge.connected'), detail: say('detail.connected') }) + expect(shown.buttons).toMatchObject([{ + label: say('action.rebind'), command: CONNECT, + confirm: { title: say('rebind.title'), body: say('rebind.body'), label: say('action.rebind') }, + }]) + expect(shown.notes).toMatchObject([{ text: { zh: '已绑定机器人:bot-1', en: 'Bound bot: bot-1' } }]) + expect(presentAccount({ account: { state: 'authorized', skills: 'installed' } }).notes).toEqual([]) + + for (const view of [ + { account: { state: 'authorized', skills: 'installed' }, operation: { id: OP, kind: 'check', phase: 'checking', cancellable: false } }, + { account: { state: 'unchecked', skills: 'installed' } }, + ] as const satisfies readonly WecomState[]) { + shown = presentAccount(view) + expect(shown).toMatchObject({ phase: 'checking', status: say('status.checking'), buttons: [] }) + expect(shown.badge).toBeUndefined() + } +}) + +it('reports a failed connection with its diagnostic items, and no failure for a cancelled one', () => { + let shown = presentAccount({ account: unauthorized, result: { id: OP, kind: 'connect', outcome: 'failed', failure: { command: 'auth-init', exitCode: 2 } } }) + expect(shown.failure).toMatchObject({ text: say('failed'), details: ['auth-init', 'exit 2'] }) + expect(labels(shown)).toEqual([zh['action.connect']]) + shown = presentAccount({ account: unauthorized, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect(shown.failure).toMatchObject({ text: say('failed') }) + expect(shown.failure).not.toHaveProperty('details') + shown = presentAccount({ account: { state: 'authorized', skills: 'installed' }, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + expect(shown.failure).toBeDefined() + expect(presentAccount({ account: unauthorized, result: { id: OP, kind: 'connect', outcome: 'cancelled' } }).failure).toBeUndefined() +}) + +it('retries an unreadable authorization by checking again', () => { + const shown = presentAccount({ + account: { state: 'unchecked', skills: 'installed' }, result: { id: OP, kind: 'check', outcome: 'failed', failure: { command: 'auth-status', exitCode: 1 } }, + }) + expect(shown).toMatchObject({ phase: 'unavailable', status: say('status.unavailable'), badge: say('badge.unavailable'), detail: say('detail.unavailable') }) + expect(shown.buttons).toMatchObject([{ label: say('action.retry'), command: CHECK }]) + expect(shown.failure?.details).toEqual(['auth-status', 'exit 1']) +}) + +it('reports guides that are downloading, and retries a failed download by checking again', () => { + expect(presentAccount({ account: { state: 'authorized', skills: 'downloading' } }).notes).toMatchObject([{ text: say('skills.downloading') }]) + const [note] = presentAccount({ account: { state: 'authorized', skills: 'failed' } }).notes + expect(note).toMatchObject({ text: say('skills.failed'), button: { label: say('action.retry'), command: CHECK } }) +}) + +it('names the section, its activation prompt, and the notice a connection reports', () => { + expect(page.copy).toMatchObject({ + title: say('section.title'), hint: say('hint'), + activation: { title: say('activation.title'), body: say('activation.body'), connect: say('action.connect') }, + }) + expect(page.operations).toMatchObject([{ kind: 'check' }, { kind: 'connect', notice: say('notice.connected') }]) + expect(page.operations[0]).not.toHaveProperty('notice') +}) diff --git a/packages/connector/wecom/tests/skills.spec.ts b/packages/connector/wecom/tests/skills.spec.ts new file mode 100644 index 0000000000..2195aef6f4 --- /dev/null +++ b/packages/connector/wecom/tests/skills.spec.ts @@ -0,0 +1,42 @@ +/** The bundled entry skill: its index names exactly the pinned upstream guides, and it reaches the model below the pruner threshold. */ +import { readdirSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { renderSkillContent } from '@deepseek-ai/dsh-skill' +import { expect, it } from 'vitest' + +const entry = fileURLToPath(new URL('../skills/wecom/', import.meta.url)) + +/** The `skills//SKILL.md` directories of the pinned commit, as `scripts/upstream-skills-digest.ts` lists them. */ +const PINNED_GUIDES = [ + 'wecomcli-calendar', 'wecomcli-contact', 'wecomcli-disk', 'wecomcli-doc', 'wecomcli-doc-manage', 'wecomcli-email', 'wecomcli-media', + 'wecomcli-meeting', 'wecomcli-message', 'wecomcli-pptx', 'wecomcli-shared', 'wecomcli-sheet', 'wecomcli-smartpage', 'wecomcli-smartsheet', + 'wecomcli-todo', +] + +/** + * `packages/bundle/web-app/presets/standard.patch.yml` prunes a tool result only above `thresholdChars: 8192` + * code points; a skill result below it reaches the model intact. + */ +const PRUNER_THRESHOLD_CHARS = 8192 + +/** The body the `skill` tool returns: the file without its YAML frontmatter. */ +function body(): string { + const text = readFileSync(join(entry, 'SKILL.md'), 'utf8') + const end = text.indexOf('\n---\n', 4) + return text.slice(end + '\n---\n'.length) +} + +it('ships only the wecom entry at the bundled skill root', () => { + expect(readdirSync(fileURLToPath(new URL('../skills/', import.meta.url)))).toEqual(['wecom']) +}) + +it('renders the entry below the pruner threshold', () => { + const rendered = renderSkillContent({ name: 'wecom', provider: 'wecom', resourceBase: { kind: 'directory', path: entry }, content: body() }) + expect(Array.from(rendered).length).toBeLessThan(PRUNER_THRESHOLD_CHARS) +}) + +it('indexes every guide of the pinned commit exactly once', () => { + const indexed = [...body().matchAll(/^- `(wecomcli-[a-z-]+)`:/gmu)].map(match => match[1] ?? '') + expect(indexed.toSorted()).toEqual(PINNED_GUIDES.toSorted()) +}) diff --git a/packages/connector/wecom/tsconfig.json b/packages/connector/wecom/tsconfig.json new file mode 100644 index 0000000000..be98936daf --- /dev/null +++ b/packages/connector/wecom/tsconfig.json @@ -0,0 +1,30 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../upstream-skills" + }, + { + "path": "../../util/values" + }, + { + "path": "../cli-account" + }, + { + "path": "../../client/ui-connector-account/tsconfig.host.json" + } + ] +} diff --git a/packages/context/agent-instructions/package.json b/packages/context/agent-instructions/package.json index d0fad047ad..dc536690be 100644 --- a/packages/context/agent-instructions/package.json +++ b/packages/context/agent-instructions/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-instructions", "description": "Workspace context loader for AGENTS.md/CLAUDE.md instruction files", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/file-reference-local/package.json b/packages/context/file-reference-local/package.json index 07b2ff779d..13623dfd24 100644 --- a/packages/context/file-reference-local/package.json +++ b/packages/context/file-reference-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference-local", "description": "Local-filesystem ctx.fileReferences provider with bounded fuzzy indexes", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/file-reference/package.json b/packages/context/file-reference/package.json index ce29fedbc5..1c0f50b6d4 100644 --- a/packages/context/file-reference/package.json +++ b/packages/context/file-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-file-reference", "description": "File-reference discovery contract and shared @file grammar", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/harness-dev-context/package.json b/packages/context/harness-dev-context/package.json index e446bcd9d0..7c733823a5 100644 --- a/packages/context/harness-dev-context/package.json +++ b/packages/context/harness-dev-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-harness-dev-context", "description": "Model context naming the DeepSeek Harness checkout and Web GUI URL without letting either change the system prompt", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/session-reference/package.json b/packages/context/session-reference/package.json index bd48533e9a..a724537bf9 100644 --- a/packages/context/session-reference/package.json +++ b/packages/context/session-reference/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session-reference", "description": "Cross-session snapshot references and durable untrusted model context (ctx.sessionReferenceResolver)", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/time-context/README.i18n.yaml b/packages/context/time-context/README.i18n.yaml index 1f6517a961..8b796cecde 100644 --- a/packages/context/time-context/README.i18n.yaml +++ b/packages/context/time-context/README.i18n.yaml @@ -24,8 +24,8 @@ en: e6ac1f330c18c69c zh: 9e969a5b377ba62a /deepseek-ai-dsh-time-context/use-this-package/choosing-the-zone: - en: 7eed0d784ad7381b - zh: 47a849df0ce80105 + en: 80a0f2b83654aa47 + zh: a0708ed67a47966a /deepseek-ai-dsh-time-context/understand-the-implementation: en: 2d21fa2aad5a729d zh: cfbfada0eb647435 @@ -33,8 +33,8 @@ en: 48381ad4596a177a zh: be025dba74956fc8 /deepseek-ai-dsh-time-context/understand-the-implementation/source-map: - en: 269d7aa1f64c4278 - zh: 086018a60cc3a351 + en: bda31c286dfd6ea5 + zh: c2f6e79a73a10e28 /deepseek-ai-dsh-time-context/understand-the-implementation/main-flow: en: 9ec32c75627991bb zh: 7ee417dda0aa90a4 diff --git a/packages/context/time-context/README.md b/packages/context/time-context/README.md index 225d8e05b5..4221bb8c92 100644 --- a/packages/context/time-context/README.md +++ b/packages/context/time-context/README.md @@ -50,7 +50,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a ### Choosing the zone -When the open turn contains exactly one Host-validated browser zone, the timestamp is formatted in that request-local zone. With missing or mixed browser-zone records, the configured `timeZone` formats the display; omitting it resolves the Node process zone once at plugin load, and every explicit fallback is validated through `Intl.DateTimeFormat`. The resolved instruction tells the model to interpret unqualified dates and times in the chosen zone, and to ask the user to clarify when those records are mixed or unavailable. +A request-local zone is the canonical `clientTimeZone` that a writer records on a user message: the Web Host records the validated browser zone, and the SDK runtime records the prompt's explicit zone or its sampled process zone. Request preparation still refuses a noncanonical value. When the open turn contains exactly one such zone, the timestamp is formatted in that request-local zone. With missing or mixed browser-zone records, the configured `timeZone` formats the display; omitting it resolves the Node process zone once at plugin load, and every explicit fallback is validated through `Intl.DateTimeFormat`. The resolved instruction tells the model to interpret unqualified dates and times in the chosen zone, and to ask the user to clarify when those records are mixed or unavailable. ----- @@ -71,7 +71,7 @@ The plugin prepends an `agent/pre-step` listener that delegates first and append | File | Role | |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: pre-step listener, due scheduling, reading composition | -| [`src/request-zone.ts`](src/request-zone.ts) | Browser-zone policy derivation from open-turn `user-rpc` sources | +| [`src/request-zone.ts`](src/request-zone.ts) | Browser-zone policy derivation from open-turn user sources that carry `clientTimeZone` | | [`src/timestamp.ts`](src/timestamp.ts) | `Intl.DateTimeFormat` creation and timestamp formatting | ### Main flow diff --git a/packages/context/time-context/README.zh.md b/packages/context/time-context/README.zh.md index 09afe4cd03..11bd48db85 100644 --- a/packages/context/time-context/README.zh.md +++ b/packages/context/time-context/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" ### 选择时区 -当当前开放轮次只包含一个经 Host 校验的浏览器时区时,时间戳按该请求本地时区格式化。浏览器来源信息缺失或混杂时,配置的 `timeZone` 格式化显示;省略它则在插件加载时解析一次 Node 进程时区,每个显式回退值都经 `Intl.DateTimeFormat` 校验。解析后的指令告诉模型按所选时区解释未限定的日期与时间;来源信息混杂或不可用时,则要求用户澄清。 +请求本地时区是写入方记录在用户消息上的规范化 `clientTimeZone`:Web Host 记录经校验的浏览器时区,SDK 运行时记录该 prompt 显式传入的时区或采样到的进程时区。请求准备阶段仍拒绝非规范值。当当前开放轮次只包含一个这样的时区时,时间戳按该请求本地时区格式化。浏览器来源信息缺失或混杂时,配置的 `timeZone` 格式化显示;省略它则在插件加载时解析一次 Node 进程时区,每个显式回退值都经 `Intl.DateTimeFormat` 校验。解析后的指令告诉模型按所选时区解释未限定的日期与时间;来源信息混杂或不可用时,则要求用户澄清。 ----- @@ -71,7 +71,7 @@ kind: "package-reference" | 文件 | 职责 | |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:pre-step 监听器、到期调度、读数组合 | -| [`src/request-zone.ts`](src/request-zone.ts) | 从开放轮次 `user-rpc` 来源派生浏览器时区策略 | +| [`src/request-zone.ts`](src/request-zone.ts) | 从开放轮次中带 `clientTimeZone` 的用户来源派生浏览器时区策略 | | [`src/timestamp.ts`](src/timestamp.ts) | `Intl.DateTimeFormat` 创建与时间戳格式化 | ### 主要流程 diff --git a/packages/context/time-context/package.json b/packages/context/time-context/package.json index 50354c1629..97ce0c5524 100644 --- a/packages/context/time-context/package.json +++ b/packages/context/time-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-time-context", "description": "Durable per-step context with the current time and elapsed time", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/context/time-context/src/request-zone.ts b/packages/context/time-context/src/request-zone.ts index b59072b7d5..aa02cec59c 100644 --- a/packages/context/time-context/src/request-zone.ts +++ b/packages/context/time-context/src/request-zone.ts @@ -1,4 +1,4 @@ -/** Browser-zone facts from committed or proposed user-rpc messages and model-facing policy text. */ +/** Browser-zone facts from committed or proposed user messages and model-facing policy text. */ import { canonicalizeTimeZone } from '@deepseek-ai/dsh-util-time' import type { UserMessage } from '@deepseek-ai/dsh-llm' @@ -11,15 +11,14 @@ export type BrowserTimeZoneContext = | { readonly kind: 'missing' } /** - * Read the raw zone reported by a user-rpc source; validation belongs to request preparation. - * @param message - user message; only user sources with a string rpcId and clientTimeZone contribute. - * @returns the reported zone, or undefined when no user-rpc zone was reported. + * Read the raw zone reported by a user source; validation belongs to request preparation. + * Writers canonicalize the zone before commit, and request preparation still refuses a noncanonical value. + * @param message - user message; only user sources with a string clientTimeZone contribute. + * @returns the reported zone, or undefined when no user zone was reported. */ export function reportedBrowserTimeZone(message: UserMessage): string | undefined { const source = message.source return source.kind === 'user' - && 'rpcId' in source - && typeof source.rpcId === 'string' && 'clientTimeZone' in source && typeof source.clientTimeZone === 'string' ? source.clientTimeZone @@ -56,7 +55,7 @@ function browserTimeZone(value: string): string { * @param messages - proposed messages, or entered plus proposed messages selected by the legacy reader. * @param enteredTimeZones - reported zones from committed messages, before the proposed messages. * @returns Sorted, duplicate-free browser-zone facts. - * @throws TypeError when a user-rpc source carries an invalid or noncanonical zone. + * @throws TypeError when a user source carries an invalid or noncanonical zone. */ export function deriveBrowserTimeZoneContext( messages: readonly UserMessage[], diff --git a/packages/context/time-context/tests/request-zone.spec.ts b/packages/context/time-context/tests/request-zone.spec.ts index 2ef4ecd919..c9a1451805 100644 --- a/packages/context/time-context/tests/request-zone.spec.ts +++ b/packages/context/time-context/tests/request-zone.spec.ts @@ -5,6 +5,7 @@ import type { ContextFormed } from '@deepseek-ai/dsh-llm' import { deriveBrowserTimeZoneContext, renderBrowserTimeZoneContext, + reportedBrowserTimeZone, } from '../src/request-zone.ts' declare module '@deepseek-ai/dsh-llm' { @@ -21,7 +22,7 @@ function browserMessage(timeZone: string): UserMessage { } describe('browser request-zone context', () => { - it('derives missing, unique, and sorted mixed zones from user-rpc messages only', () => { + it('derives missing, unique, and sorted mixed zones from user messages only', () => { const plugin = createUserMessage({ content: [{ type: 'text', text: 'plugin' }], source: { kind: 'test' }, @@ -40,6 +41,22 @@ describe('browser request-zone context', () => { }) }) + it('reads a string clientTimeZone from any user source, with or without an rpcId', () => { + const user = (source: object): UserMessage => createUserMessage({ + content: [{ type: 'text', text: 'zone' }], + source: source as never, + }) + expect(reportedBrowserTimeZone(user({ kind: 'user', rpcId: 'rpc', clientTimeZone: 'Asia/Shanghai' }))).toBe('Asia/Shanghai') + expect(reportedBrowserTimeZone(user({ kind: 'user', clientTimeZone: 'Europe/London' }))).toBe('Europe/London') + expect(reportedBrowserTimeZone(user({ kind: 'user', rpcId: 'rpc' }))).toBeUndefined() + expect(reportedBrowserTimeZone(user({ kind: 'user' }))).toBeUndefined() + expect(reportedBrowserTimeZone(user({ kind: 'retry', rpcId: 'rpc', clientTimeZone: 'Asia/Shanghai' }))).toBeUndefined() + expect(deriveBrowserTimeZoneContext([ + user({ kind: 'user', clientTimeZone: 'Europe/London' }), + browserMessage('Europe/London'), + ])).toEqual({ kind: 'resolved', timeZone: 'Europe/London' }) + }) + it('validates every browser zone before classifying a mixed turn', () => { expect(() => deriveBrowserTimeZoneContext([ browserMessage('+08:00'), diff --git a/packages/context/time-context/tests/time-context.spec.ts b/packages/context/time-context/tests/time-context.spec.ts index d6526fbd36..bf4d823767 100644 --- a/packages/context/time-context/tests/time-context.spec.ts +++ b/packages/context/time-context/tests/time-context.spec.ts @@ -196,6 +196,23 @@ describe('durable step context', () => { expect(event.surfaceOp).toBe('append') }) + it('reads a zone from a user source without an rpcId through the committed-turn projection', async () => { + const { ctx } = await mount() + const session = Session.create(brandString('rpc-free-zone')) + session.append('turn/start', { turn: 1 }) + session.append('user/message', createUserMessage({ + content: [{ type: 'text', text: 'turn 1' }], + source: { kind: 'user', clientTimeZone: 'Asia/Shanghai' } as never, + }), { surfaceOp: 'append' }) + + await fire(ctx, sessionAgent(session), 1, 1) + + expect(contextTexts(session)[0]).toContain( + '+08:00[Asia/Shanghai]\n' + + 'Browser time zone for this request: Asia/Shanghai. Interpret otherwise-unqualified dates and times in this zone.\n', + ) + }) + it('reports an unavailable first-step baseline when no model-visible message precedes it', async () => { const { ctx } = await mount() const session = Session.create(brandString('unavailable')) diff --git a/packages/context/tmux-context/package.json b/packages/context/tmux-context/package.json index ae1c9dbec8..c6c772d4ef 100644 --- a/packages/context/tmux-context/package.json +++ b/packages/context/tmux-context/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tmux-context", "description": "Opt-in durable per-step context with this agent's tmux pane and window location", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-default-model/package.json b/packages/core/agent-default-model/package.json index 50e78caad2..d9c70f048c 100644 --- a/packages/core/agent-default-model/package.json +++ b/packages/core/agent-default-model/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-default-model", "description": "Default model selection shared by Agent entry points", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-loop/package.json b/packages/core/agent-loop/package.json index bcb81beda6..c8704d0aa1 100644 --- a/packages/core/agent-loop/package.json +++ b/packages/core/agent-loop/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-loop", "description": "The concrete agent loop plugin for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent-tool-presentation/package.json b/packages/core/agent-tool-presentation/package.json index 2d0cce8f05..236ce153c4 100644 --- a/packages/core/agent-tool-presentation/package.json +++ b/packages/core/agent-tool-presentation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent-tool-presentation", "description": "Deprecated tool presentation selector; use dsh-tool-executor-native or dsh-tool-executor-ptc directly", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/agent/package.json b/packages/core/agent/package.json index a0df88f0c4..836b81fa0e 100644 --- a/packages/core/agent/package.json +++ b/packages/core/agent/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-agent", "description": "Agent interface, registry, initiator scope, and event vocabulary for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/scope/package.json b/packages/core/scope/package.json index a82a928ba3..728e5df0e7 100644 --- a/packages/core/scope/package.json +++ b/packages/core/scope/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-scope", "description": "Scoped-context registration primitive (scope tags, scope-filtered event dispatch) for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/session/package.json b/packages/core/session/package.json index 961941c7b0..32e4664fd4 100644 --- a/packages/core/session/package.json +++ b/packages/core/session/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-session", "description": "Event-sourced session store for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/system-prompt/package.json b/packages/core/system-prompt/package.json index e0094be11f..e7e5bf8113 100644 --- a/packages/core/system-prompt/package.json +++ b/packages/core/system-prompt/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-system-prompt", "description": "System prompt assembly registry for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/tool-executor-native/package.json b/packages/core/tool-executor-native/package.json index d6c20c907a..d83a2f7da6 100644 --- a/packages/core/tool-executor-native/package.json +++ b/packages/core/tool-executor-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-executor-native", "description": "Native tool execution plugin", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/tool-executor-ptc/package.json b/packages/core/tool-executor-ptc/package.json index 319229fb27..2e61d8394c 100644 --- a/packages/core/tool-executor-ptc/package.json +++ b/packages/core/tool-executor-ptc/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-executor-ptc", "description": "PTC program execution, tool bindings, and generated SDK prompts", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/core/tools/package.json b/packages/core/tools/package.json index b001355b2d..c42787d516 100644 --- a/packages/core/tools/package.json +++ b/packages/core/tools/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tools", "description": "Tool registry and execution pipeline for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/authorization/package.json b/packages/credentials/authorization/package.json index f40c02b5c9..8fdd1cf5ad 100644 --- a/packages/credentials/authorization/package.json +++ b/packages/credentials/authorization/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-authorization", "description": "Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/credentials-local/package.json b/packages/credentials/credentials-local/package.json index e82c940e16..9cbc50a767 100644 --- a/packages/credentials/credentials-local/package.json +++ b/packages/credentials/credentials-local/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials-local", "description": "File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/credentials/credentials/package.json b/packages/credentials/credentials/package.json index 7393793df6..8ca8159f4c 100644 --- a/packages/credentials/credentials/package.json +++ b/packages/credentials/credentials/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-credentials", "description": "Abstract credential seam (ctx.credentials): settings carry references to secrets, providers own the values", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/deliverable-file-references/package.json b/packages/deliverables/deliverable-file-references/package.json index 44588ba0a6..650211c34f 100644 --- a/packages/deliverables/deliverable-file-references/package.json +++ b/packages/deliverables/deliverable-file-references/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-deliverable-file-references", "description": "Shared model guidance for file links and deliverables across DeepSeek Harness hosts", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/tool-present/package.json b/packages/deliverables/tool-present/package.json index 04d50ed386..4e6636e4f3 100644 --- a/packages/deliverables/tool-present/package.json +++ b/packages/deliverables/tool-present/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-present", "description": "Explicit workspace file delivery declarations for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/deliverables/workspace-changes/README.i18n.yaml b/packages/deliverables/workspace-changes/README.i18n.yaml index b3cbe0d1af..a2ebeb5523 100644 --- a/packages/deliverables/workspace-changes/README.i18n.yaml +++ b/packages/deliverables/workspace-changes/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-workspace-changes/use-this-package: - en: 0ab7680d831598aa - zh: 2594f3c8c99cef24 + en: 27239874e99bc94d + zh: 93b437cc02de2064 /deepseek-ai-dsh-workspace-changes/understand-the-implementation: en: 9bfc66bea548bda2 zh: 7023c42cdb44569b @@ -30,8 +30,8 @@ en: e7ba08477bf22c4e zh: f365439c69beb722 /deepseek-ai-dsh-workspace-changes/known-limitations-and-deferred-work: - en: c7091685e5065a40 - zh: 1e9b85962ea04187 + en: c85c049e6cffa43a + zh: c2ed10788326ad57 /deepseek-ai-dsh-workspace-changes/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/deliverables/workspace-changes/README.md b/packages/deliverables/workspace-changes/README.md index 6cad61cf3d..71adbb4738 100644 --- a/packages/deliverables/workspace-changes/README.md +++ b/packages/deliverables/workspace-changes/README.md @@ -43,9 +43,9 @@ The shipped Web bundle mounts this plugin. Mount it in any composition with the This plugin requires the `subprocess` and `fs` services. Every Session with a working directory and no subagent origin is recorded; subagent Sessions are not. Snapshots are written through a private index into a temporary object directory owned by the Session, with the repository's own object store attached as a read-only alternate; the repository's index, objects, work tree, and refs stay untouched, and the user's earlier uncommitted changes never enter a summary. Session disposal removes the directory. Nested repositories and submodules inside the working directory are recorded as gitlinks, so their internal changes do not appear. A working directory outside any git repository takes no snapshots. Without git — or, on macOS, with only the developer-tools stub at `/usr/bin/git` — no repository is located either, and the plugin logs that once. Either way the summary lists the file-tool edits alone, as described next, with the working directory as the workspace; shell edits are absent. -After a `write`, `edit`, or mutating `str_replace_editor` call resolves its target and obtains its mutation guard, the recorder copies that exact file before the mutation into the Session's temporary directory, once per path per turn, and copies it again at turn end; the copies are named by the SHA-1 of their bytes, so identical content is stored once. This needs no git. Repository discovery and display paths retain the original project; file captures follow the operation's resolved target even after the Session changes directories. Paths the snapshots cover keep their git counts; the copies serve the other paths — files matching an ignore pattern, files outside the repository, and every file-tool edit when there is no snapshot — with counts from a line comparison of the two copies, so repeated edits to one file count once and a shell edit after a file-tool edit is included. A path whose content is unchanged at turn end is not listed. A copy larger than `maxFileBytes` is not stored: the file is listed with `oversized` and no counts, and a path whose both sides are that large is listed too, since unread content is never known to be unchanged. A path whose only difference is a missing final newline compares as unchanged, while git still counts that line. Files under `/tmp` or the platform temporary directory are excluded unless they lie inside the repository. Changes made only through shell commands outside the snapshot coverage are not recorded. +After a `write`, `edit`, or mutating `str_replace_editor` call resolves its target and obtains its mutation guard, the recorder copies that exact file before the mutation into the Session's temporary directory, once per path per turn, and copies it again at turn end; the copies are named by the SHA-1 of their bytes, so identical content is stored once. This needs no git. Repository discovery and display paths follow the working directory the turn started in; file captures follow the operation's resolved target even after the Session changes directories. Paths the snapshots cover keep their git counts; the copies serve the other paths — files matching an ignore pattern, files outside the repository, and every file-tool edit when there is no snapshot — with counts from a line comparison of the two copies, so repeated edits to one file count once and a shell edit after a file-tool edit is included. A path whose content is unchanged at turn end is not listed. A copy larger than `maxFileBytes` is not stored: the file is listed with `oversized` and no counts, and a path whose both sides are that large is listed too, since unread content is never known to be unchanged. A path whose only difference is a missing final newline compares as unchanged, while git still counts that line. Files under `/tmp` or the platform temporary directory are excluded unless they lie inside the repository. Changes made only through shell commands outside the snapshot coverage are not recorded. -Each file carries a durable `path` — relative to the working directory inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the working directory, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the working directory's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns. +The recorder follows each Host move of the Session's directory: a turn that starts after a Session entered a worktree is snapshotted in that checkout and lists paths relative to it, and a turn already open keeps the directory it started in. Each file carries a durable `path` — relative to the working directory inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the working directory, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the working directory's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns. The intent listeners capture every add, update, delete, and move target of `apply_patch` after policy admission and before provider mutation; a move captures both ends. Review compares each path against its first baseline and lists net changes, including the completed effects of a stopped patch. @@ -93,7 +93,7 @@ Nothing here enters a model request, so provider cache reuse is unaffected. - A working directory outside any git repository lists file-tool edits only, so shell edits are missing from its card; a shadow repository under the Harness home is deferred until its exclude rules can replace a missing `.gitignore` reliably. - Outside snapshot coverage only paths a file tool names are captured: a file only a shell command changes there is absent, and a file both changed before its first file-tool call is compared from that call onward. - Every file-tool edit copies its whole file once per turn, up to `maxFileBytes`, even for paths the snapshots also cover; the copies go with the Session's temporary directory. -- A comparison serves the listed file's complete text to the client, including ignored files, repository files above the working directory, and files outside the workspace; the summary route serves only paths and counts. A deployment that must keep such content on the Host composes this plugin out. +- A comparison serves the listed file's complete text to the client, including ignored files, repository files above the working directory, and files outside the workspace; the summary route serves only paths, counts, and the directory the turn started in. A deployment that must keep such content on the Host composes this plugin out. - A comparison that degrades to whole-file replacement carries every line of both sides, up to twice `maxFileBytes`. - Windows paths keep native separators in `path`; `display` is always slash-separated. diff --git a/packages/deliverables/workspace-changes/README.zh.md b/packages/deliverables/workspace-changes/README.zh.md index a36f75dea4..d53234109d 100644 --- a/packages/deliverables/workspace-changes/README.zh.md +++ b/packages/deliverables/workspace-changes/README.zh.md @@ -43,9 +43,9 @@ kind: "package-reference" 本插件需要 `subprocess` 与 `fs` 服务。有工作目录且不是子代理来源的 Session 都会被记录;子代理 Session 不记录。快照通过私有 index 写入 Session 自己拥有的临时对象目录,仓库自己的对象库以只读 alternate 的方式挂接;仓库的 index、对象、工作树和 ref 保持不变,用户此前未提交的改动也不会进入摘要。Session 释放时删除该目录。工作目录内的嵌套仓库和 submodule 记录为 gitlink,其内部改动不会出现。不在任何 git 仓库内的工作目录不做快照。没有 git 时——或者 macOS 上只有 `/usr/bin/git` 的开发者工具桩程序时——同样定位不到仓库,插件记录一次日志。两种情况下摘要都只列下文所述的文件工具编辑,并以工作目录作为工作区;shell 的改动不会出现。 -在 `write`、`edit`、`apply_patch` 或有修改作用的 `str_replace_editor` 调用解析目标并取得修改防护之后,记录器在实际修改前把该文件复制到 Session 的临时目录,每轮每个路径只复制第一次,轮次结束时再复制一次;副本按其字节的 SHA-1 命名,相同内容只存一份。这一步不需要 git。仓库定位与显示路径保留原始项目;即使 Session 切换目录,文件捕获仍跟随该操作已解析的目标。快照覆盖到的路径保留 git 的行数;其余路径由副本提供,也就是匹配忽略模式的文件、仓库之外的文件,以及没有快照时的每一次文件工具编辑,行数来自两份副本的逐行对比,因此同一文件的重复编辑只计一次,文件工具编辑之后的 shell 改动也包含在内。轮次结束时内容没有变化的路径不会列出。超过 `maxFileBytes` 的副本不会保存:该文件列出时带 `oversized`,没有行数;两侧都这么大的路径同样列出,因为没读过的内容永远不能认定为没有改动。只差一个末尾换行的路径对比为两侧相同,而 git 仍会把那一行计入行数。`/tmp` 与平台临时目录下的文件被排除,除非它们位于仓库内。快照覆盖范围之外只通过 shell 命令做出的改动不会被记录。 +在 `write`、`edit`、`apply_patch` 或有修改作用的 `str_replace_editor` 调用解析目标并取得修改防护之后,记录器在实际修改前把该文件复制到 Session 的临时目录,每轮每个路径只复制第一次,轮次结束时再复制一次;副本按其字节的 SHA-1 命名,相同内容只存一份。这一步不需要 git。仓库定位与显示路径跟随该轮开始时的工作目录;即使 Session 切换目录,文件捕获仍跟随该操作已解析的目标。快照覆盖到的路径保留 git 的行数;其余路径由副本提供,也就是匹配忽略模式的文件、仓库之外的文件,以及没有快照时的每一次文件工具编辑,行数来自两份副本的逐行对比,因此同一文件的重复编辑只计一次,文件工具编辑之后的 shell 改动也包含在内。轮次结束时内容没有变化的路径不会列出。超过 `maxFileBytes` 的副本不会保存:该文件列出时带 `oversized`,没有行数;两侧都这么大的路径同样列出,因为没读过的内容永远不能认定为没有改动。只差一个末尾换行的路径对比为两侧相同,而 git 仍会把那一行计入行数。`/tmp` 与平台临时目录下的文件被排除,除非它们位于仓库内。快照覆盖范围之外只通过 shell 命令做出的改动不会被记录。 -每个文件携带持久的 `path`——位于工作目录内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作目录之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作目录自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。 +记录器跟随 Host 对 Session 目录的每次移动:Session 进入 worktree 之后开始的 turn 在该检出目录中拍快照,并以它为基准列出相对路径;已经开始的 turn 保留它开始时的目录。每个文件携带持久的 `path`——位于工作目录内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作目录之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作目录自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。 intent 监听器在策略准入后、提供方修改前捕获 `apply_patch` 的每个新增、更新、删除和移动目标;移动捕获两端。Review 将每个路径与首次基线比较并列出净变化,包括中止补丁已经完成的效果。 @@ -93,7 +93,7 @@ git 通过 `subprocess` 能力运行,使用净化后的环境、`GIT_CONFIG_CO - 不在任何 git 仓库内的工作目录只列文件工具的编辑,卡片里因此没有 shell 改动;Harness home 下的影子仓库暂缓,直到其排除规则能可靠地代替缺失的 `.gitignore`。 - 快照覆盖范围之外只捕获文件工具点名的路径:那里只被 shell 命令改动的文件不会出现,在首次文件工具调用之前被两者都改过的文件从该调用起开始对比。 - 每次文件工具编辑都会把整个文件复制一次,每轮每个路径一次,上限 `maxFileBytes`,即使快照也覆盖该路径;副本随 Session 的临时目录一起删除。 -- 对比会把所列文件的完整文本送到客户端,包括被忽略的文件、工作目录之上的仓库文件和工作区外的文件;摘要路由只送路径和行数。必须把这类内容留在 Host 上的部署应把本插件组合出去。 +- 对比会把所列文件的完整文本送到客户端,包括被忽略的文件、工作目录之上的仓库文件和工作区外的文件;摘要路由只送路径、行数和该轮开始时所在的目录。必须把这类内容留在 Host 上的部署应把本插件组合出去。 - 退化为整文件替换的对比携带两侧的全部行,最多两倍 `maxFileBytes`。 - Windows 路径在 `path` 中保留原生分隔符;`display` 始终用斜杠分隔。 diff --git a/packages/deliverables/workspace-changes/package.json b/packages/deliverables/workspace-changes/package.json index a4398c7220..92af12b57c 100644 --- a/packages/deliverables/workspace-changes/package.json +++ b/packages/deliverables/workspace-changes/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-workspace-changes", "description": "Per-turn workspace file changes recorded from git working-tree snapshots and whole-file captures, with per-file comparisons, for the DeepSeek Harness", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -43,10 +43,11 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-fs": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { "@deepseek-ai/dsh-brand": "workspace:*", @@ -54,21 +55,21 @@ "@deepseek-ai/cordis-plugin-include": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-subprocess-local": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-fs": "workspace:*", - "@deepseek-ai/dsh-fs-local": "workspace:*", - "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", - "@deepseek-ai/dsh-agent-loop": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-fs": "workspace:*", - "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tool-str-replace-editor": "workspace:*", - "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-tool-testkit": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/deliverables/workspace-changes/src/index.ts b/packages/deliverables/workspace-changes/src/index.ts index 1448153ef9..c5e833b0e3 100644 --- a/packages/deliverables/workspace-changes/src/index.ts +++ b/packages/deliverables/workspace-changes/src/index.ts @@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-agent' import type { Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/dsh-tools' +import type {} from '@deepseek-ai/dsh-working-directory' import type { FsTarget } from '@deepseek-ai/dsh-fs' import { GitRunner } from './git.ts' import { TurnRecorder } from './recorder.ts' @@ -56,6 +57,7 @@ export const Config: z = z.object({ diffTimeoutMs: z.number().default(100), }) +/** The original directory of a summarized Session: a top-level Session with a recorded directory. */ function eligible(session: Session): string | undefined { const { cwd, origin, delegationDepth } = session.header return origin === 'subagent' || (delegationDepth ?? 0) > 0 ? undefined : cwd @@ -129,10 +131,11 @@ export function apply(ctx: Context, config: Config): void { }) return runner } - const recorderFor = (session: Session, cwd: string): TurnRecorder => { + const recorderFor = (session: Session, original: string): TurnRecorder => { let recorder = recorders.get(session) if (recorder === undefined) { - recorder = new TurnRecorder(session, cwd, { + // The Session's directory now; `workspace-root/change` events report later moves. + recorder = new TurnRecorder(session, ctx.get('workingDirectory')?.get(session) ?? original, { git: gitRunner(), tempRoot: tmpdir(), maxFiles: config.maxFiles, maxFileBytes: config.maxFileBytes, diffTimeoutMs: config.diffTimeoutMs, warn: (message) => { ctx.logger.warn(message) }, @@ -144,11 +147,12 @@ export function apply(ctx: Context, config: Config): void { } ctx.on('session/event', (session, event) => { if (event.type === 'turn/start') { - const cwd = eligible(session) - if (cwd !== undefined) recorderFor(session, cwd).start(event.data.turn) + const original = eligible(session) + if (original !== undefined) recorderFor(session, original).start(event.data.turn) return } - if (event.type === 'tool/result') recorders.get(session)?.observe(event) + if (event.type === 'workspace-root/change') recorders.get(session)?.moveTo(event.data.cwd) + else if (event.type === 'tool/result') recorders.get(session)?.observe(event) else if (event.type === 'turn/end') recorders.get(session)?.end(event.data.turn) }) ctx.on('session/disposed', (session) => { void forget(session) }) diff --git a/packages/deliverables/workspace-changes/src/recorder.ts b/packages/deliverables/workspace-changes/src/recorder.ts index d0abb9e7ad..faa390d446 100644 --- a/packages/deliverables/workspace-changes/src/recorder.ts +++ b/packages/deliverables/workspace-changes/src/recorder.ts @@ -27,9 +27,9 @@ export interface RecorderEnvironment { warn: (message: string) => void } -/** Canonical paths every comparison and display uses, resolved once per Session. */ +/** Canonical paths every comparison and display uses, resolved when a turn opens. */ interface Paths { - /** Canonical original project directory for repository discovery and display paths. */ + /** Canonical Session directory for repository discovery and display paths. */ cwd: string /** Canonical home directory abbreviated as `~` in display paths. */ home: string @@ -69,6 +69,10 @@ interface TurnRecord { /** Everything one turn accumulates; a new turn gets a new object so queued work for an older turn keeps its own. */ interface TurnState { readonly turn: number + /** The Session directory the turn started in, as the directory service spells it. */ + readonly cwd: string + /** Canonical paths of that directory, resolved by the turn's baseline; undefined until then. */ + paths: Paths | undefined /** * The turn-start snapshot once it exists. `null` means no repository or no git, so the turn summarizes file-tool * captures only; `'failed'` means the repository exists but its snapshot failed, so the turn records nothing. @@ -83,8 +87,10 @@ interface TurnState { recordedAfterSeq: number } -function freshState(turn: number): TurnState { - return { turn, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1 } +function freshState(turn: number, cwd: string): TurnState { + return { + turn, cwd, paths: undefined, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1, + } } /** A listed file with the sources of its two sides. */ @@ -102,16 +108,19 @@ const OVERSIZED = Symbol('oversized') * with the summaries. Tool execution waits for pending work so a snapshot or * capture never races a mutation. A working directory outside any repository, * or a Host without git, gets no snapshot; its summary lists the files the file - * tools changed. + * tools changed. {@link moveTo} tells the recorder that the Session works in + * another directory: turns that start afterwards are snapshotted there and + * list paths relative to it, while the open turn keeps the directory it + * started in. */ export class TurnRecorder { private chain: Promise = Promise.resolve() /** The open turn; before the first `turn/start` it is an empty placeholder no event can match. */ - private state = freshState(0) - /** Canonical paths, resolved by the first turn. */ - private paths: Paths | undefined - /** The located repository, reused across turns once found; null keeps retrying each turn. */ - private repository: Repository | null = null + private state = freshState(0, '') + /** Host facts shared by every turn, resolved by the first. */ + private host: Pick | undefined + /** Located repositories by canonical Session directory, reused across turns; an absent entry keeps retrying each turn. */ + private readonly repositories = new Map() /** Temporary directory holding this Session's snapshot objects, scratch indexes, and captured copies. */ private scratch: Promise | undefined /** Records by the sequence of the event that announced them. */ @@ -120,21 +129,33 @@ export class TurnRecorder { constructor( private readonly session: Session, - private readonly cwd: string, + private cwd: string, private readonly env: RecorderEnvironment, ) {} + /** + * Record that the Session works in another directory from now on. Turns that + * start afterwards use it; the open turn keeps the directory it started in, + * where its baseline snapshot was taken. + * @param cwd - the Session's directory after the move. + */ + moveTo(cwd: string): void { + this.cwd = cwd + } + /** * Open a turn with fresh per-turn state and queue its baseline snapshot. * @param turn - the turn number from `turn/start`. */ start(turn: number): void { - const state = freshState(turn) + const cwd = this.cwd + const state = freshState(turn, cwd) this.state = state void this.enqueue(async (signal) => { try { - this.paths ??= { cwd: await realpath(this.cwd), home: await canonicalPath(homedir()), temporaryRoots: await temporaryRoots() } - const repository = await this.locate(this.paths.cwd, signal) + this.host ??= { home: await canonicalPath(homedir()), temporaryRoots: await temporaryRoots() } + state.paths = { cwd: await realpath(cwd), ...this.host } + const repository = await this.locate(state.paths.cwd, signal) if (repository === null) return const tree = await snapshotTree(repository.git, repository.workspace, signal) state.baseline = { ...repository, tree } @@ -155,8 +176,7 @@ export class TurnRecorder { capture(path: string): void { const state = this.state void this.enqueue(async () => { - const paths = this.paths - if (paths === undefined) return + if (state.paths === undefined) return const absolute = await canonicalPath(path) if (state.captures.has(absolute)) return const capture = await captureFile(absolute, join(await this.scratchDir(), 'captures'), this.env.maxFileBytes) @@ -271,15 +291,17 @@ export class TurnRecorder { return this.scratch } - /** The repository enclosing the working directory, located once; null keeps retrying each turn. */ + /** The repository enclosing one Session directory, located once per directory; null keeps retrying each turn. */ private async locate(cwd: string, signal: AbortSignal): Promise { - if (this.repository !== null) return this.repository + const located = this.repositories.get(cwd) + if (located !== undefined) return located const git = await this.env.git if (git === null) return null const workspace = await locateGitWorkspace(git, cwd, () => this.scratchDir(), signal) if (workspace === null) return null - this.repository = { git, workspace } - return this.repository + const repository = { git, workspace } + this.repositories.set(cwd, repository) + return repository } /** One side's text, null for an absent file, or {@link OVERSIZED} for a snapshot side beyond the byte cap. */ @@ -298,7 +320,7 @@ export class TurnRecorder { } private async record(state: TurnState, signal: AbortSignal): Promise { - const paths = this.paths + const { paths } = state const { baseline } = state if (paths === undefined || baseline === 'failed' || state.lastToolResultSeq < 0) return state.attemptedAfterSeq = state.lastToolResultSeq @@ -353,7 +375,7 @@ export class TurnRecorder { this.records.set(event.seq, { summary: { turn: state.turn, - cwd: this.cwd, + cwd: state.cwd, files: kept.map(entry => entry.file), total: sorted.length, added: sorted.reduce((sum, entry) => sum + entry.file.added, 0), diff --git a/packages/deliverables/workspace-changes/src/types.ts b/packages/deliverables/workspace-changes/src/types.ts index 8e48381480..f5429fa3b8 100644 --- a/packages/deliverables/workspace-changes/src/types.ts +++ b/packages/deliverables/workspace-changes/src/types.ts @@ -25,7 +25,7 @@ export interface WorkspaceChangedFile { export interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ + /** The Session working directory `path` values are relative to, as it stood when the turn started. */ cwd: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] diff --git a/packages/deliverables/workspace-changes/tests/current-directory.spec.ts b/packages/deliverables/workspace-changes/tests/current-directory.spec.ts index 766e191e33..0b4a64d046 100644 --- a/packages/deliverables/workspace-changes/tests/current-directory.spec.ts +++ b/packages/deliverables/workspace-changes/tests/current-directory.spec.ts @@ -63,7 +63,8 @@ it.each(['write', 'edit', 'str_replace_editor'] as const)('captures the resolved const announcement = events.findLast(event => event.type === 'workspace/changes') expect(announcement).toBeDefined() const summary = ctx.workspaceChanges.summary(agent.id, announcement!.seq) - expect(summary).toMatchObject({ cwd: origin, total: 1, files: [{ path: 'current/witness.txt', added: 1, deleted: 1 }] }) + // The turn started in `current`; its summary keeps that directory after the move back. + expect(summary).toMatchObject({ cwd: current, total: 1, files: [{ path: 'witness.txt', added: 1, deleted: 1 }] }) expect(summary!.snapshot).toBeUndefined() expect(await ctx.workspaceChanges.diff(agent.id, announcement!.seq, 0, new AbortController().signal)).toMatchObject({ kind: 'text', hunks: [{ lines: ['-before', '+after'] }] }) }) diff --git a/packages/deliverables/workspace-changes/tests/worktree.spec.ts b/packages/deliverables/workspace-changes/tests/worktree.spec.ts new file mode 100644 index 0000000000..f6f268f090 --- /dev/null +++ b/packages/deliverables/workspace-changes/tests/worktree.spec.ts @@ -0,0 +1,92 @@ +/** Turns recorded in the checkout the Session works in: a worktree entered through the working-directory service. */ +import { mkdir, realpath, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { unsupportedInbox, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit' +import LocalFileSystem from '@deepseek-ai/dsh-fs-local' +import SessionStore, { type SessionId } from '@deepseek-ai/dsh-session' +import { brandString } from '@deepseek-ai/dsh-brand' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory' +import * as WorkspaceChanges from '../src/index.ts' +import { changes, endTurn, git, mutate, scratchDir, settle, startTurn, toolCall } from './support.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + for (const cleanup of cleanups.reverse()) await cleanup() + cleanups.length = 0 +}) + +function agentFor(ctx: Context, session: Session): Agent { + const scope = ctx.plugin(() => {}) + return { + id: session.id, session, options: {}, status: 'idle', ctx: scope.ctx, model: unsupportedModel(), + inbox: unsupportedInbox(), + send() {}, followup() {}, steer() {}, inject() {}, cancel() {}, + whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal), + } +} + +it('snapshots the worktree the Session entered, lists paths relative to it, and leaves the original checkout out', async () => { + // Production headers record canonical paths; anchors compare as recorded, so the fixture does too. + const main = await realpath(await scratchDir('dsh-workspace-changes-worktree-', cleanups)) + git(main, 'init', '-q', '-b', 'main') + await writeFile(join(main, 'a.txt'), 'main\n') + git(main, 'add', '-A') + git(main, 'commit', '-q', '-m', 'init') + await mkdir(join(main, '.agents', 'worktrees'), { recursive: true }) + await writeFile(join(main, '.agents', 'worktrees', '.gitignore'), '*\n') + const worktree = join(main, '.agents', 'worktrees', 'x') + git(main, 'worktree', 'add', '-q', '-b', 'x', worktree) + + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(LocalSubprocessRuntime) + await ctx.plugin(LocalFileSystem, { cwd: main }) + await ctx.plugin(WorkingDirectoryService, {}) + await ctx.plugin(WorkspaceChanges, {} as WorkspaceChanges.Config) + const session = ctx.sessions.create(brandString('worktree-turns'), { meta: { cwd: main } }) + const agent = agentFor(ctx, session) + await ctx.workingDirectory.set(agent, worktree) + + // A shell-only edit inside the worktree is a change of the worktree's repository. + startTurn(session, 1) + await settle(ctx, session) + await writeFile(join(worktree, 'a.txt'), 'edited in the worktree\n') + // Someone else edits the original checkout meanwhile; it is not this turn's work. + await writeFile(join(main, 'a.txt'), 'edited in the original checkout\n') + toolCall(session, 1, 'bash', { command: 'edit' }) + endTurn(session, 1) + await settle(ctx, session) + + // A file-tool edit lists its path relative to the worktree, not to the original project. + startTurn(session, 2) + await settle(ctx, session) + await mutate(ctx, session, 2, 'write', {}, join(worktree, 'b.txt'), () => writeFile(join(worktree, 'b.txt'), 'new\n')) + endTurn(session, 2) + await settle(ctx, session) + + // Back in the original project, the next turn is snapshotted there again. + await ctx.workingDirectory.set(agent, main) + startTurn(session, 3) + await settle(ctx, session) + await writeFile(join(main, 'a.txt'), 'edited again in the original checkout\n') + toolCall(session, 3, 'bash', { command: 'edit' }) + endTurn(session, 3) + await settle(ctx, session) + + const snapshot = { before: expect.stringMatching(/^[0-9a-f]+$/) as string, after: expect.stringMatching(/^[0-9a-f]+$/) as string } + expect(changes(ctx, session)).toEqual([ + { turn: 1, cwd: worktree, total: 1, added: 1, deleted: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 1 }], snapshot }, + { turn: 2, cwd: worktree, total: 1, added: 1, deleted: 0, files: [{ path: 'b.txt', display: 'b.txt', added: 1, deleted: 0 }], snapshot }, + { turn: 3, cwd: main, total: 1, added: 1, deleted: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 1 }], snapshot }, + ]) +}) diff --git a/packages/deliverables/workspace-changes/tsconfig.json b/packages/deliverables/workspace-changes/tsconfig.json index 3daa220c27..dc2a76c38e 100644 --- a/packages/deliverables/workspace-changes/tsconfig.json +++ b/packages/deliverables/workspace-changes/tsconfig.json @@ -31,6 +31,9 @@ }, { "path": "../../fs/fs" + }, + { + "path": "../../session/working-directory" } ] } diff --git a/packages/document/office-kit/package.json b/packages/document/office-kit/package.json index 21cf2e0f18..bbc3c042ed 100644 --- a/packages/document/office-kit/package.json +++ b/packages/document/office-kit/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-office-kit", "description": "Shared Office rendering, conversion, and recalculation with bounded queues and caching", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/document/tool-office/package.json b/packages/document/tool-office/package.json index 45f99afb70..5e91903fd0 100644 --- a/packages/document/tool-office/package.json +++ b/packages/document/tool-office/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-tool-office", "description": "Model-facing Office tools for rendering, converting, and recalculating documents", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/action-cards/package.json b/packages/experimental/action-cards/package.json index 78c1e64803..ddca598ebf 100644 --- a/packages/experimental/action-cards/package.json +++ b/packages/experimental/action-cards/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-action-cards", "description": "Optional action cards below answers: card state, user actions and status notices", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/api-speech-to-text/package.json b/packages/experimental/api-speech-to-text/package.json index 66b2e27013..252b96a911 100644 --- a/packages/experimental/api-speech-to-text/package.json +++ b/packages/experimental/api-speech-to-text/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-api-speech-to-text", "description": "Authenticated experimental speech transcription for browser clients", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/auto-review/package.json b/packages/experimental/auto-review/package.json index d40198cf3d..d1878ae3cc 100644 --- a/packages/experimental/auto-review/package.json +++ b/packages/experimental/auto-review/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-auto-review", "description": "Per-tool LLM authorization review for the DeepSeek Harness Auto permission preset", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "icon": "./icon.svg", "repository": { "type": "git", diff --git a/packages/experimental/badge-skill-bundle/package.json b/packages/experimental/badge-skill-bundle/package.json index 12fad42469..9184246d10 100644 --- a/packages/experimental/badge-skill-bundle/package.json +++ b/packages/experimental/badge-skill-bundle/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-badge-skill-bundle", "description": "Let agents add a “powered by dsh” badge to documents, pull requests, and other outputs.", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "icon": "./icon.svg", "publishConfig": { "access": "public" diff --git a/packages/experimental/browser-use-chrome-devtools-mcp/package.json b/packages/experimental/browser-use-chrome-devtools-mcp/package.json index 18d3d82f5f..8849aec89a 100644 --- a/packages/experimental/browser-use-chrome-devtools-mcp/package.json +++ b/packages/experimental/browser-use-chrome-devtools-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp", "description": "Experimental per-Session Chromium browser tools through chrome-devtools-mcp", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-playwright-mcp/package.json b/packages/experimental/browser-use-playwright-mcp/package.json index 768ba1ab12..592f79713e 100644 --- a/packages/experimental/browser-use-playwright-mcp/package.json +++ b/packages/experimental/browser-use-playwright-mcp/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-playwright-mcp", "description": "Experimental per-Session Chromium browser tools through @playwright/mcp", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-runtime/package.json b/packages/experimental/browser-use-runtime/package.json index 4e4a15d63a..343657318d 100644 --- a/packages/experimental/browser-use-runtime/package.json +++ b/packages/experimental/browser-use-runtime/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-runtime", "description": "Session-owned browser resource lifecycles and MCP integration for experimental providers", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/browser-use-stagehand-native/package.json b/packages/experimental/browser-use-stagehand-native/package.json index 6bc3873e3d..082ea3b417 100644 --- a/packages/experimental/browser-use-stagehand-native/package.json +++ b/packages/experimental/browser-use-stagehand-native/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-browser-use-stagehand-native", "description": "Experimental Stagehand browser tools with separately configured native models", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/claude-code-mods/package.json b/packages/experimental/claude-code-mods/package.json index 584807fa62..2f5bfec247 100644 --- a/packages/experimental/claude-code-mods/package.json +++ b/packages/experimental/claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-claude-code-mods", "description": "Experimental bridge: load Claude Code mods (hooks modules) and run their hook chains on DeepSeek Harness extension points", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-action-cards/package.json b/packages/experimental/client-ui-action-cards/package.json index 3feca0a7fd..0a128479e7 100644 --- a/packages/experimental/client-ui-action-cards/package.json +++ b/packages/experimental/client-ui-action-cards/package.json @@ -1,5 +1,5 @@ { - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-claude-code-mods/package.json b/packages/experimental/client-ui-claude-code-mods/package.json index 164799af32..94b6843e16 100644 --- a/packages/experimental/client-ui-claude-code-mods/package.json +++ b/packages/experimental/client-ui-claude-code-mods/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-claude-code-mods", "description": "Web band above the prompt for Claude Code mods: draws each session's mod tree and sends button presses back to the bridge", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-cot-translation/package.json b/packages/experimental/client-ui-cot-translation/package.json index b9ebee750e..4699546de5 100644 --- a/packages/experimental/client-ui-cot-translation/package.json +++ b/packages/experimental/client-ui-cot-translation/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-cot-translation", "description": "Optional machine translation of expanded reasoning, preserving original Session text", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-creation-recommendations/package.json b/packages/experimental/client-ui-creation-recommendations/package.json index a2743de15c..da9b665fe1 100644 --- a/packages/experimental/client-ui-creation-recommendations/package.json +++ b/packages/experimental/client-ui-creation-recommendations/package.json @@ -1,5 +1,5 @@ { - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 8c7ce42b15..b5185916ec 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 2c853cfbae8b7cfd - zh: 82148507cefd6d17 + en: b09c31932092f0a0 + zh: b16598d5f50baab6 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 4778e1dca2c6ff47 - zh: a8589b3e950a8ca1 + en: 5876ab4a46ee5e65 + zh: b5ea47ac9665530e /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: 795766e162ebf4df - zh: 893de3302798330a + en: fc49ba3011e952f9 + zh: e7e3a3a94f67833b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: - en: 2bc25a99e17789c4 - zh: 4bec723fbf249d28 + en: c1b5bfb0e5a1801e + zh: 2bbe1a2845aa5d20 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 49fd22a6073c1680 - zh: a2ca41e361799b19 + en: 739fee52b50d04d1 + zh: 6550f24b8fd52791 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 930f903ad5..236072f2c5 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -33,6 +33,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Archive cleanup** — archiving a Session lets the [worktree service](../worktree/README.md) reclaim the clean, unreferenced worktree it created, whether through the New Session option or the model's `enter_worktree` tool, while retaining the branch and its commits. A scheduled cleanup uses the archive notice “Archived; the worktree will be cleaned up”; one that ends retained returns to the ordinary notice, and one that fails replaces it with a warning while the Session stays archived. Undo cancels deletion before admission or waits for an admitted deletion; a removed checkout uses the existing Restore worktree flow. The bundle's worktree row on the Plugins page offers Keep worktrees when archiving: once saved, archiving keeps every worktree and shows the ordinary archive notice; the switch is read at each archive, so it does not affect a cleanup already scheduled. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its steps: fetching a remote base branch, creating the branch, and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again, on the chosen name or a new generated one, and Continue without a worktree withdraws the request so the message goes on in the current checkout. A failed fetch also offers Use the last fetched version, which starts from the remote branch as last fetched. When the chosen branch or its directory already exists, Rename opens the naming dialog, whose Retry saves the new name and tries again. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the Session panel's checkout row, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the checkout row's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the checkout row shows a warning glyph. +- **Code review page** — the Code review row in the left navigation counts the open change requests that ask the signed-in user for a review and opens a page with three lists: Review requested, Created by me, and Involving me, each most recently updated first across every host a provider lists them on, read only while the page or the count shows. While a list is read, skeleton rows laid out as the chosen view stand in for its items. A list item names the repository when the lists span more than one, the author, the update time, the issues it closes, and at most one hint, such as You requested changes · Requested again or a team request; the search box filters the lists by title, number, repository, and author under the [client search rule](../../client/AGENTS.md#search-and-filter) and opens a pasted change request link with Enter. The view menu, laid out like the Session list's, switches between the Detailed view and a Compact view of one line per change request, whose title scrolls into view on hover and whose hover card lists the details, reads one repository, and leaves out team requests. The repository submenu keeps offering every repository the lists named while they were read in all, with the chosen one marked, so another repository is one choice away. The detail shows the state, repository and number, labels on one line that fold into +N, the title, author, times, and branches, the ready-for-review or merge action, and a More menu; Summary shows the description beside a status column of blocks: the merge state with the branch update, the failed, running, and cancelled checks with the rerun of the failed ones, each reviewer with their outcome and the review request, and the changed lines with the linked issues, where the checks and reviewers blocks fold after five lines and list everything on request, and a finished change request shows how it ended, its changed lines, and its reviewers, Changes shows the changes view with review threads, viewed files, and review submission, where Add to chat and Quote in chat put a comment or thread into the change request's conversation draft and count it on the Chat tab, and Chat starts a conversation in a blank Session of the Workspace whose folder has the repository's name, quoting the change request and offering three prompts, and binds the change request at the first message; New conversation starts another, and Open in main view shows it in the main view. Below 880 px of page width one column shows; signing in, rate limits, and unrecognized links show where they apply. - **Session panel** — the Environment section of the Session panel gains the checkout and local changes rows after the project row, and the connection row at its end while the panel stream is lost, and a Change requests section follows it. The panel has no refresh control: when it opens and when the window regains focus, it inspects the checkout again, checks sign-in, and polls every change request, at most once every 10 seconds per Session, so changes made outside the Session appear on return. A yellow dot on the panel toggle in the Session header marks an open change request with failed checks, requested changes, or conflicts, also while the panel is hidden. - **Checkout row** — names the checked-out branch, or Not on a branch with the abbreviated commit on a detached HEAD, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip, shown after 500ms of hover, adds the path with the Host home shortened to `~`, and a branch name the row clips crawls into view while the pointer rests on the row. The row and its More button open the directory menu of the checkout root. For a removed worktree it shows a warning glyph and offers Restore. When Git cannot be read, the row says so, and its info button shows the failure after 500ms of hover, at once on keyboard focus, or on a press; outside a Git checkout there is no row. - **Connection row** — when the Session's panel stream ends, also before it delivered a first state, a status row at the end of the Environment section says the status stopped updating and that the Git and change request details may be out of date; Retry opens the stream again and the row goes away. @@ -49,9 +50,9 @@ The checks row initially shows the polling preview. While it is incomplete, the The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, and `maxAnnotationsPerFile` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCachedReviewBytes`, `reviewRefreshMs`, `maxCommits`, `testPaths`, `interfacePaths`, `lensTimeoutMs`, `maxLensReadBytes`, `maxCachedLensBytes`, `maxAnnotationsPerFile`, `reviewListIntervalMs`, `reviewCountIntervalMs`, `reviewMaxBackoffMs`, and `reviewPageSize` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). -All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree, which stays at least as wide as the lens above it needs to show the layer names whole. Files and folders reserve the same disclosure column so each child is indented from its parent. The tree already shows each directory, so only a renamed file names both paths, in a tooltip after 500ms of hover; a name its row clips crawls into view while the pointer rests on the row. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the split button adds the comment to the user's pending review on the code host, starting one when there is none; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately and is absent while the user has a pending review. Agent references and published comments remain beside their code. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. Decisions the code host does not let the user record are unavailable, such as Approve and Request changes on the user's own pull request on GitHub; when only Comment remains, the dialog says so. The view's copy names the code host and its word for a change request, such as GitHub and PR, after the change request's provider. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. +All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree, which stays at least as wide as the lens above it needs to show the layer names whole. Files and folders reserve the same disclosure column so each child is indented from its parent. The tree already shows each directory, so only a renamed file names both paths, in a tooltip after 500ms of hover; a name its row clips crawls into view while the pointer rests on the row. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. Several editors can stay open at once, and choosing the range of an open one focuses it again. In two columns, each comment sits under its own side of the row, so a left and a right comment share that row side by side, each continuing its line’s background. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. Once the review threads are read and the user may review, the split button adds the comment to the user's pending review on the code host, starting one when there is none; the comment then shows as a thread tagged Pending, which only the user sees until the review is submitted. Its menu publishes a single comment immediately and is absent while the user has a pending review. Agent references and published comments remain beside their code as cards that name their lines and state; Remove in a card's menu takes the card out of the view, leaves the main composer and the code host unchanged, and shows a notice that offers Undo. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. With a pending review, it submits that review, keeping a submission whose outcome is unknown blocked until the user checks GitHub, as a direct submission is, and Discard review deletes the review and its comments after a confirmation; without one, it publishes the summary as one review. Decisions the code host does not let the user record are unavailable, such as Approve and Request changes on the user's own pull request on GitHub; when only Comment remains, the dialog says so. The view's copy names the code host and its word for a change request, such as GitHub and PR, after the change request's provider. Added and deleted files show only their populated line-number column. The summary, decision, and records of Agent references and published comments are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears them, and reopening starts an empty summary. The pending review, published GitHub comments, and references already added to the main composer are unaffected. Comment drafts an earlier version kept in this browser stay beside their code tagged Browser draft and can be edited, deleted after a confirmation, or added to the pending review; they keep Submit review disabled while a pending review exists, and without one Submit review publishes them with the summary. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. ----- @@ -63,14 +64,14 @@ All files opens a searchable directory tree with the selected file scrolled to i `ForgePanelController` keeps one `SessionPanel` per followed Session and disposes it when the last follower leaves. A panel starts with the Session's working directory and bindings, re-inspects after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and publishes a new `ForgePanelState` only when the state differs from the published one, so a reinspection that finds the same checkout reaches no follower. Each change request keeps the latest snapshot a poll returned while later polls fail. A failed parallel Git read cancels and joins its siblings. Inspections run one at a time with one trailing rerun, and a result for a directory the Session has since left is dropped. The code host comes from the remotes in order: the upstream's remote, then `origin`, then the rest. When an inspection finds an upstream branch on a remote a provider recognizes, the panel asks `ctx.forgeSession.discoverBranch` to bind that branch's open change requests, once per remote and branch until a refresh. A sign-in probe runs when the recognized host changes and on refresh, within `readinessTimeoutMs`; a refresh settles once the inspection and the probe it started have ended, and poll results arrive later. -Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes//HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when both directories lie inside the canonical workspace root of the Session's sandbox policy. +Inspection runs `rev-parse --show-toplevel`, `rev-parse --path-format=absolute --git-common-dir`, `rev-parse --path-format=absolute --git-dir`, `symbolic-ref --quiet HEAD`, which names the checked-out branch when it is under `refs/heads/`, `rev-parse --short HEAD`, `rev-parse --abbrev-ref @{upstream}`, and `remote -v`; `worktreeBases` runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, takes each remote's default branch from its `refs/remotes//HEAD`, leaves out other symbolic refs and the branches of unconfigured remotes, and keeps at most `maxBranches` local branches and `maxBranches` branches per remote whose names contain the query, with remotes in the code host order below; `requestWorktree` with a name checks it against Git's branch-name rules and runs `show-ref` in the checkout; `diffBases` finds the default fork point as `localDiff` does below, runs `for-each-ref --sort=-committerdate` over `refs/heads/` and `refs/remotes/` within `maxDiffBytes`, leaves out symbolic refs such as `origin/HEAD`, and keeps at most `maxBranches` branches of each kind whose names contain the query. Inspection then sizes the `branch` scope for the local changes row: it finds the fork point, runs `diff --numstat -z -M` against it with the same helper and submodule restrictions as `localDiff` below, and lists untracked files. Every command uses the Session's resolved sandbox mode: `read-only` and `workspace-write` require confinement, while `danger-full-access` runs without a sandbox backend. Commands disable optional index writes, hooks, the filesystem monitor, prompts, and lazy object fetches, remove inherited Git selectors and secret-bearing variables, and use their own `gitTimeoutMs` deadline and `maxOutputBytes` limit per stream. The top-level, Git, and common Git directories Git prints are resolved through `ctx.fs` into the canonical process paths that the working-directory service records; a checkout whose Git directory differs from the common one is a linked worktree. The worktree option is usable under the `danger-full-access` sandbox mode, never under `read-only`, and under `workspace-write` only when the checkout lies inside the canonical workspace root of the Session's sandbox policy and the common Git directory lies inside that root or one of the policy's additional writable directories. A worktree request is a `plugin:client-ui-forge/worktree` record, folded by the `forgeWorktree` projection: requests and withdrawals apply until the first `turn/start` or creation, and the first creation of an open request, read from the worktree service's `plugin:worktree/created` record or from the `created` record earlier panels wrote, applies until the first `step/start`. The projection also records the Session's directory from its header and each `workspace-root/change`; its client view, which the Session summary carries, is the created worktree while that directory is the worktree or lies below it, else null. A request names its base by the full name of a local or remote-tracking branch, as earlier panels' short local names still resolve, and may name its branch. `requestWorktree` refuses with `forgePanel/session-started` after a turn started or the worktree was created, with `forgePanel/worktrees-unavailable` without a `worktrees` service, with `forgePanel/invalid-branch` for an empty base, with `forgePanel/invalid-name` for a branch name Git refuses, and with `forgePanel/branch-exists` for a branch name the checkout already uses; `cancelWorktree` refuses only with the first and needs no `worktrees` service; both forget a failed attempt. When a message enters the next-turn queue of a Session whose request is open, an `agent/inbox/inserted` listener starts maintenance of the Session's Agent before the delivery wakes it, so the Agent latches the wake and starts the message's turn once that hold ends. A message queued for the next step, such as a notice another plugin injects, opens no turn and starts no hold. The hold makes one attempt on the requested branch name, or on a new generated one, asking the worktree service to fetch a remote-tracking base branch first; it publishes the running stage in the panel state with `held` set and `waiting` as `creation`, and records `created` with the source repository root. After a failed attempt, whose branch, base, fetch, failed step, reason, and whether the branch or directory existed stay in the panel state as `failure`, or after `stopCreation`, the hold waits: `retryWorktree` makes another attempt, without the fetch when its `fetch` argument is false, refused with `forgePanel/not-waiting` while none waits or one runs; `requestWorktree` with another name changes the next attempt; and withdrawing the request lets the message go on in the current checkout. Each next-turn message that enters while the Agent is idle and the Session works in its created worktree starts a hold that checks whether the worktree is missing; while it is, the hold waits with `waiting` as `restoration`, and `restoreWorktree` or `continueInProject` runs inside it and then lets the message go on; a check that cannot answer lets the message go at once. The Agent's cancellation and the Remote's stop end a hold, and a message that enters while the Agent runs a turn or other maintenance gets none. The worktree service queues the working-directory notice, which the first step claims. An `agent/pre-step` listener creates the worktree at step 1 of a Session whose request is still open, which covers a message no hold took; it moves the notice into the proposed messages, and a failure ends the turn with the request kept. `restoreWorktree` and `continueInProject` run as maintenance of their own while no message waits; `restoreWorktree` publishes its running step as `restoration`, and clears `missing` in the same state that ends it. `track` rejects a URL no provider recognizes with `forgePanel/unrecognized-url`. `markReady` and `merge` act only on a visible binding of the Session that a provider serves, else they refuse with `forgePanel/not-bound`; `merge` passes the head commit the card showed, and a moved head refuses with `forgePanel/stale-head`, while any other refusal is `forgePanel/action-failed` with the host's reason. Restoration records `restoring` before mutation and `restored` only after success. Projection version 3 retains incomplete restoration across reloads. Directory existence alone cannot release a waiting message: the checkout root and shared Git directory must match the recorded worktree. Plugin unload cancels and joins all creation, restoration, and waiting tasks before releasing panel readers and the projection. -Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. +Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. Commands in the source repository run under the Session's policy bounded by that repository, since the Session's own root is the missing directory. `localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes row hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, a patch together with its `.gitattributes`, where a failed patch read cancels the attributes read and both reads end before the result, the patch's failure passing on before the attributes failure, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestReview` acts on the same visible bindings, refuses a head other than the latest status's with `forgePanel/stale-head` before reading, and reads the provider's `readReview`, mapping `stale` to `forgePanel/stale-head`, `unsupported` to `forgePanel/review-unsupported`, and other failures to `forgePanel/review-failed`. It keeps one read per change request, keyed by head commit and update time, drops the least recently read once the kept reads exceed `maxCachedReviewBytes` as JSON, and reads again once a kept read is `reviewRefreshMs` old or the reader refreshes the view, since resolving a GitHub thread leaves the update time unchanged. Each `forge/review-changed` drops the read kept for its change request and raises `reviewRevision` on the panel entries that bind it, so an open view reads the threads and the viewed marks again after another plugin's write. `registerLens` keeps lenses by identity, and `extensions` streams their identities with `maxAnnotationsPerFile`. `changesLens` reads the files as `localDiff` or `changeRequestDiff` does, refuses files whose `lensVersion` differs from the request with `forgePanel/lens-stale`, and runs `classify` with a signal that aborts on cancellation, withdrawal, or `lensTimeoutMs`, counting the UTF-8 bytes `text` returns against `maxLensReadBytes`. Old sides come from `git show` at the fork point, the first chosen commit's parent, the index, or HEAD for local changes, and through `fileText` at the chosen commits' parent or at the provider's `mergeBase` of `baseSha` and the head for a change request. Results are kept by files, lens, and lens version up to `maxCachedLensBytes` as JSON; a failure maps to `forgePanel/lens-failed`, and a withdrawn lens to `forgePanel/lens-missing`. @@ -78,7 +79,7 @@ Each inspection also decides whether the worktree is missing: the Session's dire `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so it runs the automatic refresh on mount and on window `focus` and `visibilitychange`, throttled per Session by the shared panel store. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the Session panel entries, the New Session option, and the creation card; it opens with the first subscriber, after a `forgePanel` Session reference has opened the Session's history, so the Host resumes the Session once rather than beside that opening, holds that reference until the stream ends, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The change requests section is the `change-requests` entry of `conversation.session.panel.section` at order 100 with its count in `conversation.session.panel.section.actions`; the checkout, local changes, and connection rows are `conversation.session.panel.environment.row` entries at orders 20, 30, and 40, after the project row, and the attention mark is a `conversation.session.panel.indicator` entry. The checkout row shortens paths with the Host home from the Remote's Host facts, read again after each transport reset; it is mounted whenever the panel shows, so it runs the automatic refresh on mount and on window `focus` and `visibilitychange`, throttled per Session by the shared panel store; a refresh asked for before the first panel state arrives runs once that state arrives, because the Host refreshes only a panel it follows. The toast lives in a `shell.overlay` entry so it outlives the panel. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and passes each file section values that keep their identity across its renders, including the tab's visibility, so a render redraws only the sections whose values changed and a visibility change redraws every section. An expanded file draws its lines, highlighted with the shared code highlighter in the same render, once its section first comes within 1200px of the scrollport or a jump to one of its review threads targets it, keeps them drawn after that, and until then holds a 22px row per drawn line; a chip title shows its name with the changes icon. Once a file's whole new side is known, read for an expansion or, for local changes, read once per comparison when the file draws, each side of each run of drawn rows is highlighted again in idle time after up to 120 lines of the file before it, the old side rebuilt from the new side and the hunks; the new colors apply in one update after every run is done, and wait while the reader drags or holds a text selection in the file. A change request's files are not read for this, since each read is a request to the code host. | Source | Responsibility | |---|---| @@ -92,6 +93,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/diff.ts`](src/diff.ts) | Patch parsing, untracked files as additions, and numstat records | | [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, branch commits, new-side text, and the `branch` scope summary | | [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | +| [`src/viewer-lists.ts`](src/viewer-lists.ts) | The review page's lists and count, read per repository scope while a reader shows them | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | | [`src/client/ChangeRequestsSection.tsx`](src/client/ChangeRequestsSection.tsx) | Change requests section, its sign-in row, and its title control | @@ -101,6 +103,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/client/AttentionIndicator.tsx`](src/client/AttentionIndicator.tsx) | Attention mark on the Session panel toggle | | [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | Checks, review, merge, and linked issue rows with their menus | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | +| [`src/client/review-page/`](src/client/review-page/) | Code review page: its registration, navigation count, lists, detail with the status column, and chat | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view | | [`src/client/section-reach.ts`](src/client/section-reach.ts) | When file sections draw their lines | @@ -139,11 +142,11 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t ## Model Experience -Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. Add to input on a review thread contributes a frozen `## Review Thread N` quote with File, Side, Lines, the commit those lines number, State, Source, the recorded diff hunk, and every comment's author, time, and body quoted line by line. The review page's chat quotes the change request's number, title, and URL in the draft of a blank Session, and the model reads them only in the message the user sends; the binding it records at that message adds what bound change requests contribute through the [Session bindings](../forge-session/README.md). #### KV Cache effect -None for a new worktree, as its notice belongs to the first request of the Session, before any cached prefix exists. A notice after Continue in the project and the message Create change request sends, and submitted review quotes are appended after the cached prefix. +None for a new worktree, as its notice belongs to the first request of the Session, before any cached prefix exists. A notice after Continue in the project and the message Create change request sends, and submitted review quotes are appended after the cached prefix; a review page conversation is a new Session, so its first request has no cached prefix. ## Known Limitations and Deferred Work @@ -157,7 +160,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Messages during a turn** — a message that enters while the Agent runs a turn or other maintenance gets no hold: a requested worktree is then created at the first step, where a failure ends the turn without the message, and a removed worktree is not checked, so the working-directory service moves the Session back to the project directory. - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. -- **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. +- **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree, unless the sandbox policy grants its Git directory: under workspace-write that directory lies outside the writable root, so neither the new branch nor later commits could be written. A grant registered while the panel shows takes effect at the next inspection. Windows processes ignore such grants, so there the option is offered and creation fails. Commits inside a created worktree need the grant too, as the [worktree service](../worktree/README.md#known-limitations-and-deferred-work) describes. - **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. @@ -169,7 +172,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Extensions** — a lens runs only once it is chosen, and its result applies to the files the view showed when it asked; reading the old side of a whole change request needs a provider that names merge bases. Line annotations stay out of the thread list, the unresolved counts, and thread navigation. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. -- **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. +- **Review page** — only the GitHub provider lists change requests and reads descriptions, so the lists hold GitHub hosts, each provider's configured hosts together; a GitLab merge request opened from a pasted link shows its status, changes, and chat, with a read failure in place of its description. Choosing among hosts and accounts waits for a second provider that lists change requests. The changes tab shows no plugin lenses, annotations, toolbar, file-menu, or comment-form entries, whose extension points name a Session, and its quotes go to the chat's draft instead of the Session's input. The chat starts in the Workspace's shared blank Session, which New Session also shows, and does not check that the Workspace is a checkout of the repository; the change request to bind waits in Host memory until the first message, so a Host restart forgets it. Pending review comments last while the page shows their change request. ### Dev Note diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 8f75e3262f..db3cb23eac 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -33,6 +33,7 @@ kind: "package-reference" - **归档清理**——归档一个会话后,由[工作树服务](../worktree/README.zh.md)回收它创建的干净且无人引用的工作树,无论来自新会话选项还是模型的 `enter_worktree` 工具,分支及其提交保留。清理排队后,归档提示为“已归档,工作树将被清理”;最终保留时恢复为普通归档提示,失败时替换为警告而会话仍保持归档。撤销归档会取消尚未获准的删除,或等待已获准的删除结束;已移除的工作树使用现有的“恢复工作树”流程。插件页上该套件的 worktree 行提供“归档时不删除工作树”开关:保存后,归档会保留所有工作树并显示普通归档提示;开关在每次归档时读取,不影响已排队的清理。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支及其步骤:获取远程基准分支、创建分支、检出文件;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”再试一次,使用指定的名称或新的自动名称;“不使用工作树”撤回请求,消息在当前检出中继续发送。获取失败时还提供“使用上次获取的版本”,从上次获取的远程分支开始。指定的分支或其目录已存在时,“更改名称”打开命名对话框,其中的“重试”保存新名称并再试一次。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(会话面板检出行中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,检出行中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间检出行显示警示图标。 +- **代码评审页**——左侧导航的“代码评审”一行显示请登录用户评审的未关闭变更请求数,点开是包含“待我评审”“我创建的”“与我有关”三个列表的页面;每个列表合并提供方能列出的全部主机,按更新时间倒序,只在页面或计数显示时读取。列表读取期间,按所选视图排布的骨架行占据列表项的位置。列表项在列表跨多个仓库时写出仓库名,并显示作者、更新时间、会关闭的 issue 和至多一条提示,如“你请求过修改 · 已再次请求”或团队请求;搜索框按[客户端搜索规则](../../client/AGENTS.md#search-and-filter)以标题、编号、仓库和作者筛选列表,粘贴变更请求链接后按 Enter 打开。视图菜单与会话列表的一致:可在“详细”与“紧凑”之间切换(紧凑为每个变更请求一行,悬停时标题滚动显示完整内容,悬停卡列出详情),可只读一个仓库,也可排除团队请求。仓库子菜单始终列出在读取全部仓库时列表里出现过的仓库,并标出当前所选的那个,因此可以直接换到另一个仓库。详情显示状态、仓库与编号、单行标签(放不下时收进 +N)、标题、作者、时间和分支,以及标记为可评审或合并操作和“更多”菜单;“概要”在描述旁显示由若干区块组成的状态栏:合并状态与更新分支,失败、进行中、已取消的检查与重跑失败项,每位评审者及其结论与请求评审,变更行数与关联 issue;检查和评审者区块超过五行时折叠,可展开查看全部,已结束的变更请求则显示结束方式、变更行数和评审者,“变更”显示变更视图,含评审讨论、已审阅文件和提交评审,其中“添加到对话”“引用到对话”把评论或讨论放进该变更请求对话的草稿,并在“对话”标签上计数;“对话”在文件夹名与仓库同名的工作区的空白会话中开始对话,引用该变更请求并提供三个提示,首条消息时绑定该变更请求;“新对话”另开一个,“在主界面打开”在主界面显示它。页面宽度不足 880 px 时只显示一栏;需要登录、触发限流或链接无法识别时在对应位置提示。 - **会话面板**——会话面板的“环境”分栏在项目行之后增加检出行与本地变更行,面板流断开时末尾再加连接行,其后是“变更请求”分栏。面板没有刷新控件:打开时以及窗口重新获得焦点时,它会重新检查检出与登录状态,并轮询每个变更请求,每个会话每 10 秒最多一次,因此在 Session 之外做的改动在切回来时就会出现。打开中的变更请求存在检查失败、被要求修改或冲突时,会话标题栏中的面板开关带黄点,面板隐藏时也会显示。 - **检出行**——显示当前检出的分支(分离 HEAD 时为“不在分支上”与缩写提交),并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);悬停 500ms 后出现的提示给出路径,宿主主目录缩写为 `~`;分支名放不下时,指针停在这一行上会滚动显示全文。这一行及其“更多”按钮打开检出根目录的目录菜单。worktree 已被删除时显示警示图标并提供“恢复”。无法读取 Git 时,这一行说明这一点,行尾的信息按钮在悬停 500ms、键盘聚焦或按下时给出失败原因;不在 Git 检出中时不显示这一行。 - **连接行**——Session 的面板流结束时(包括还没收到第一份状态就结束),环境分栏末尾的状态行说明状态已停止更新,Git 与变更请求信息可能已过时;「重试」重新打开流,这一行随即消失。 @@ -49,9 +50,9 @@ kind: "package-reference" diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes` 与 `maxAnnotationsPerFile` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCachedReviewBytes`、`reviewRefreshMs`、`maxCommits`、`testPaths`、`interfacePaths`、`lensTimeoutMs`、`maxLensReadBytes`、`maxCachedLensBytes`、`maxAnnotationsPerFile`、`reviewListIntervalMs`、`reviewCountIntervalMs`、`reviewMaxBackoffMs` 与 `reviewPageSize` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 -“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度;文件树至少保持上方透镜完整显示各层名称所需的宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。树已经表示了目录,所以只有重命名的文件会在悬停 500ms 后用提示显示新旧两条路径;文件名放不下时,指针停在这一行上会滚动显示全文。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,分段按钮会把这条评论加入用户在代码托管平台上的待提交评审,没有时先开始一个;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时没有该菜单。Agent 引用和已发布的评论保留在对应代码旁。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。代码托管平台不允许用户记录的结论不可用,例如在 GitHub 上用户自己的 PR 里,“批准”和“请求更改”不可用;只剩“评论”时,对话框会说明。视图中的文案按变更请求的提供方称呼代码托管平台及其对变更请求的叫法,例如 GitHub 和 PR。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 +“全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度;文件树至少保持上方透镜完整显示各层名称所需的宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。树已经表示了目录,所以只有重命名的文件会在悬停 500ms 后用提示显示新旧两条路径;文件名放不下时,指针停在这一行上会滚动显示全文。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。可以同时打开多个评论框,再次选中已打开评论框的范围会回到该评论框。两栏时每条评论位于该行自己一侧的下方,左右两侧的评论并排处在同一行,各自延续所在行的底色。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。读到评审讨论且用户可以评审时,分段按钮会把这条评论加入用户在代码托管平台上的待提交评审,没有时先开始一个;评论随后显示为带“待提交”标签的讨论,提交评审之前只有用户自己能看到。下拉菜单可以立即发布单条评论;用户有待提交评审时没有该菜单。Agent 引用和已发布的评论以卡片保留在对应代码旁,卡片标出行范围和状态;卡片菜单里的“移除”把卡片从视图中去掉,不改动主输入框和代码托管平台,随后的提示提供“撤销”。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。有待提交评审时提交该评审,结果不明的提交与直接提交一样,在用户到 GitHub 核对之前阻止再次提交;“丢弃评审”在确认后删除该评审及其中的评论;没有待提交评审时,把总结作为一次评审发布。代码托管平台不允许用户记录的结论不可用,例如在 GitHub 上用户自己的 PR 里,“批准”和“请求更改”不可用;只剩“评论”时,对话框会说明。视图中的文案按变更请求的提供方称呼代码托管平台及其对变更请求的叫法,例如 GitHub 和 PR。新建和删除文件只显示有内容的一侧行号。总结、评审决定,以及 Agent 引用与已发布评论的记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空它们,重新打开从空总结开始。待提交评审、已发布到 GitHub 的评论与已加入主输入框的引用不受影响。早期版本保存在此浏览器中的评论草稿保留在对应代码旁,带“浏览器草稿”标签,可以编辑、确认后删除或加入待提交评审;存在待提交评审时,它们会让“提交评审”保持不可用;没有待提交评审时,“提交评审”把它们连同总结一起发布。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 ----- @@ -63,14 +64,14 @@ diff 按文件树的深度优先顺序排列:同层目录在前、文件在后 `ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,只在状态与已发布的不同时发布新的 `ForgePanelState`,所以检查结果与原来相同时不会通知任何关注方。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 -检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes//HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 +检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --quiet HEAD`(指向 `refs/heads/` 下的分支时即为当前分支)、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`worktreeBases` 在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,从 `refs/remotes//HEAD` 取每个远程的默认分支,略过其他符号引用与未配置远程的分支,并按下文的代码托管识别顺序排列远程,各保留最多 `maxBranches` 个名称包含查询文字的本地分支与每个远程的分支;带名称的 `requestWorktree` 按 Git 的分支名规则检查名称,并在检出中运行 `show-ref`;`diffBases` 像下文的 `localDiff` 一样找出默认分叉点,在 `maxDiffBytes` 以内对 `refs/heads/` 与 `refs/remotes/` 运行 `for-each-ref --sort=-committerdate`,排除 `origin/HEAD` 等符号引用,每类最多保留 `maxBranches` 个名称包含查询文字的分支。之后,检查会为本地变更行统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,采用与下文 `localDiff` 相同的辅助程序和子模块限制,并列出未跟踪文件。每个命令都使用 Session 解析出的沙箱模式:`read-only` 与 `workspace-write` 需要沙箱,`danger-full-access` 无需沙箱后端。命令禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下,只有检出目录位于 Session 沙箱策略的规范工作区根内,且公共 Git 目录位于该根或策略的某个额外可写目录内时才可用。 worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `workspace-root/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。请求用本地分支或远程跟踪分支的完整引用名指定基准(早期面板记录的本地短名称仍可解析),并可指定分支名。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;基准为空时以 `forgePanel/invalid-branch` 拒绝;Git 不接受分支名时以 `forgePanel/invalid-name` 拒绝;检出中已有同名分支时以 `forgePanel/branch-exists` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的下一轮队列时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。排给下一步的消息(例如其他插件注入的通知)不开启一轮,也不启动暂留。暂留用请求的分支名或新的自动名称进行一次尝试,基准是远程跟踪分支时请 worktree 服务先获取它;它在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、是否获取、失败步骤、原因以及分支或目录是否已存在以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,`fetch` 参数为 false 时不获取,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;用另一个名称调用 `requestWorktree` 会改变下一次尝试;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入下一轮队列的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 恢复在修改前记录 `restoring`,仅在成功后记录 `restored`。投影版本 3 在重载后保留未完成的恢复。目录存在本身不能放行等待的消息:检出根目录与公共 Git 目录必须匹配记录的工作树。插件卸载会取消并等待所有创建、恢复与消息等待任务,然后释放面板读取器和投影。 -每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 +每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。源仓库中的命令在 Session 的策略下运行,边界是该仓库,因为 Session 自身的根就是那个缺失的目录。 Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更行保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,补丁与它的 `.gitattributes` 同时读取,补丁读取失败时取消 `.gitattributes` 的读取,两者都结束后才给出结果,补丁的失败优先于 `.gitattributes` 的失败,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。`changeRequestReview` 同样只作用于可见的绑定;head 与最新状态的 head 不同时,读取前就以 `forgePanel/stale-head` 拒绝;随后调用提供方的 `readReview`,把 `stale` 映射为 `forgePanel/stale-head`、`unsupported` 映射为 `forgePanel/review-unsupported`、其余失败映射为 `forgePanel/review-failed`。每个变更请求保留一次读取结果,以 head 提交和更新时间为键;保留的结果按 JSON 计超过 `maxCachedReviewBytes` 时,最久未读的先被丢弃;保留时间达到 `reviewRefreshMs` 后,或读者刷新视图时,重新读取,因为解决 GitHub 讨论不会改变更新时间。每个 `forge/review-changed` 都会丢弃对应变更请求保留的读取结果,并让绑定它的面板条目的 `reviewRevision` 加一,因此其他插件写入后,已打开的视图会重新读取讨论和已审阅标记。`registerLens` 按身份保存透镜,`extensions` 流式发送这些身份和 `maxAnnotationsPerFile`。`changesLens` 像 `localDiff` 或 `changeRequestDiff` 一样读取文件,文件的 `lensVersion` 与请求不同时以 `forgePanel/lens-stale` 拒绝;它运行 `classify` 时传入的 signal 会在取消、透镜撤销或超过 `lensTimeoutMs` 时中止,并把 `text` 返回的 UTF-8 字节数计入 `maxLensReadBytes`。本地变更的旧侧在分叉点、第一个所选提交的父提交、暂存区或 HEAD 上经 `git show` 读取;变更请求的旧侧经 `fileText` 在所选提交的父提交上读取,或在提供方给出的 `baseSha` 与 head 的 `mergeBase` 上读取。结果按文件、透镜和透镜版本保留,按 JSON 计最多 `maxCachedLensBytes`;失败映射为 `forgePanel/lens-failed`,透镜已撤销映射为 `forgePanel/lens-missing`。 @@ -78,7 +79,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时触发自动刷新,按会话由共享的面板 store 限流。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给会话面板中的条目、新会话选项与创建卡片;第一个订阅方出现时,先由一个 `forgePanel` Session 引用打开该 Session 的历史再打开流,使 Host 只恢复一次该 Session、而不与这次打开并行,并持有该引用直到流结束;最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。变更请求分栏是 `conversation.session.panel.section` 中 order 为 100 的 `change-requests` 条目,数量位于 `conversation.session.panel.section.actions`;检出行、本地变更行与连接行是 `conversation.session.panel.environment.row` 中 order 为 20、30 与 40 的条目,位于项目行之后;提醒标记是 `conversation.session.panel.indicator` 条目。检出行用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取;面板显示时它始终挂载,因此由它在挂载时以及窗口 `focus` 与 `visibilitychange` 时触发自动刷新,按会话由共享的面板 store 限流;首个面板状态到达前请求的刷新等到该状态到达后执行,因为 Host 只刷新它正在跟随的面板。toast 位于 `shell.overlay` 条目中,因此比面板存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并且传给每个文件段的值(包括标签页可见性)在多次渲染之间保持同一标识,所以一次渲染只重绘值有变化的文件段,可见性变化时重绘全部文件段。展开的文件在它的段第一次进入滚动区域 1200px 范围内,或跳转到它的某个评审讨论时,才绘制各行,并在同一次渲染中用共享的代码高亮器高亮,此后一直保留;在此之前按每个绘制行 22px 占位;标签页标题显示变更图标与视图名称。文件的整个新版本已知时(为展开而读取,或本地变更在文件绘制时按每次比较读取一次),每段绘制行的每一侧会在空闲时带上文件中它之前最多 120 行重新高亮,旧版本由新版本与 hunk 还原;所有段都算完后新颜色在一次更新中生效,读者正在拖选或文件内有文本选区时等它结束。变更请求的文件不为此读取,因为每次读取都是一次对代码托管平台的请求。 | 源码 | 职责 | |---|---| @@ -92,6 +93,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/diff.ts`](src/diff.ts) | 补丁解析、把未跟踪文件表示为新增,以及 numstat 记录 | | [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、分支提交、新版本文本与 `branch` 范围摘要 | | [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | +| [`src/viewer-lists.ts`](src/viewer-lists.ts) | 评审页的列表与计数,按仓库范围读取,仅在有读者显示时读取 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | | [`src/client/ChangeRequestsSection.tsx`](src/client/ChangeRequestsSection.tsx) | 变更请求分栏、其中的登录状态行及其标题控件 | @@ -101,6 +103,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/client/AttentionIndicator.tsx`](src/client/AttentionIndicator.tsx) | 会话面板开关上的提醒标记 | | [`src/client/ChangeRequestOverview.tsx`](src/client/ChangeRequestOverview.tsx) | 检查、评审、合并与关联 issue 行及其菜单 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | +| [`src/client/review-page/`](src/client/review-page/) | 代码评审页:注册、导航计数、列表、带状态栏的详情与对话 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | | [`src/client/section-reach.ts`](src/client/section-reach.ts) | 文件段何时绘制各行 | @@ -139,11 +142,11 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。对评审讨论使用“添加到输入框”时,会加入一段固定的 `## Review Thread N` 引用,包含 File、Side、Lines、这些行号所在的提交、State、Source、记录下的 diff hunk,以及逐行引用的每条评论的作者、时间和正文。代码评审页的对话把变更请求的编号、标题和 URL 作为引用放进空白会话的草稿,模型只在用户发出的消息中读到它们;该消息时记录的绑定带来[会话绑定](../forge-session/README.zh.md)为已绑定变更请求提供的内容。 #### KV Cache 影响 -新 worktree 的通知没有影响,因为它属于 Session 的第一次请求,那时还没有任何缓存前缀。“在项目目录继续”之后的通知、“创建变更请求”发送的消息与发送后的评审引用都追加在缓存前缀之后。 +新 worktree 的通知没有影响,因为它属于 Session 的第一次请求,那时还没有任何缓存前缀。“在项目目录继续”之后的通知、“创建变更请求”发送的消息与发送后的评审引用都追加在缓存前缀之后;代码评审页的对话是新会话,第一次请求没有缓存前缀。 ## 已知限制与待办工作 @@ -157,7 +160,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **一轮进行中的消息**——Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留:所请求的 worktree 改为在第一步创建,失败时这一轮结束且不带这条消息;已删除的 worktree 不会被检查,工作目录服务会把 Session 移回项目目录。 - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 -- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 +- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用,除非沙箱策略授权了它的 Git 目录:在 workspace-write 下该目录位于可写根之外,新分支与之后的提交都无法写入。面板显示期间注册的授权在下一次检查时生效。Windows 的进程忽略这类授权,因此在 Windows 上该选项可用但创建会失败。在创建出的 worktree 内提交同样需要该授权,见 [worktree 服务](../worktree/README.zh.md#known-limitations-and-deferred-work)的说明。 - **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 @@ -169,7 +172,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **扩展**——透镜只在被选中后运行,结果作用于发出请求时视图所显示的文件;读取整个变更请求的旧侧需要能给出合并基准的提供方。行注解不进入讨论列表、未解决数和讨论导航。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 -- **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 +- **代码评审页**——只有 GitHub 提供方能列出变更请求并读取描述,因此列表中只有 GitHub 主机,每个提供方配置的主机合并列出;通过粘贴链接打开的 GitLab 合并请求显示状态、变更与对话,描述处显示读取失败。在主机与账号之间选择要等到第二个能列出变更请求的提供方。“变更”标签不显示插件的透镜、行注释、工具栏、文件菜单和评论表单入口(这些扩展点以会话为对象),引用放进对话草稿而不是会话输入框。对话在工作区共享的空白会话中开始,“新会话”也显示这个会话,且不检查该工作区是否是此仓库的检出;待绑定的变更请求在首条消息前只保存在 Host 内存中,Host 重启会丢失。未提交的评审评论只在页面显示该变更请求期间保留。 ### 开发备注 diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 44e66d6964..09ae7bf5ec 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -1,7 +1,7 @@ { "name": "@deepseek-ai/dsh-experimental-client-ui-forge", "description": "Session panel entries for a Session's change requests, with a worktree option for new Sessions and its Host Remote", - "version": "0.2.2-rc.4", + "version": "0.2.2-rc.5", "publishConfig": { "access": "public" }, @@ -40,6 +40,7 @@ "dsh": { "client": { "inject": [ + "@deepseek-ai/dsh-api-remote-access", "@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-conversation", @@ -82,6 +83,7 @@ "@deepseek-ai/dsh-api-remote-access": "workspace:*", "@deepseek-ai/dsh-api-remotes": "workspace:*", "@deepseek-ai/dsh-api-session-controller": "workspace:*", + "@deepseek-ai/dsh-api-workspace-controller": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", @@ -95,6 +97,7 @@ "@deepseek-ai/dsh-client-ui-session": "workspace:*", "@deepseek-ai/dsh-client-ui-session-panel": "workspace:*", "@deepseek-ai/dsh-client-ui-settings": "workspace:*", + "@deepseek-ai/dsh-client-ui-sidebar": "workspace:*", "@deepseek-ai/dsh-client-ui-sidebar-right": "workspace:*", "@deepseek-ai/dsh-client-ui-slots": "workspace:*", "@deepseek-ai/dsh-client-ui-workspace": "workspace:*", @@ -116,6 +119,7 @@ "@deepseek-ai/dsh-subprocess-local": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-util-text-search": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", "@testing-library/react": "^16.3.3", diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 9ad8172250..bf3f49b313 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -27,7 +27,7 @@ import { formatAgo } from './format.ts' import { ChangeRequestGlyph, CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import type { ForgeChangeRequestCardActionsProps } from './slots.ts' -import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestTone } from './status.ts' +import { ciSummary, flagOf, numberOf, TONE_LABEL, toneOf, type ChangeRequestEntry, type ChangeRequestTone } from './status.ts' import css from './Forge.module.css' type Translate = PropsLocale['t'] @@ -44,15 +44,15 @@ export interface ChangeRequestActions extends OverviewActions { /** Read the status again after a failed read. */ readonly retry: () => void /** Remove the change request from its Session. */ - readonly remove?: ((entry: ForgePanelChangeRequest) => void) | undefined + readonly remove?: ((entry: ChangeRequestEntry) => void) | undefined /** Mark a draft ready for review; settles once the outcome is reported. */ - readonly markReady?: ((entry: ForgePanelChangeRequest) => Promise) | undefined + readonly markReady?: ((entry: ChangeRequestEntry) => Promise) | undefined /** Merge the change request as `request` describes; settles once the outcome is reported. */ - readonly merge?: ((entry: ForgePanelChangeRequest, request: MergeRequest) => Promise) | undefined + readonly merge?: ((entry: ChangeRequestEntry, request: MergeRequest) => Promise) | undefined /** Load complete check details independently of polling; cancellation follows the open list. */ readonly readChecks?: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined /** Open the changes view of the change request. */ - readonly viewChanges?: ((entry: ForgePanelChangeRequest) => void) | undefined + readonly viewChanges?: ((entry: ChangeRequestEntry) => void) | undefined /** Draw the icon buttons plugins add to the card's head through `forge.change-request.card.actions`. */ readonly renderActions?: ((owner: ForgeChangeRequestCardActionsProps) => ReactNode) | undefined /** @@ -89,6 +89,7 @@ const REVIEW: Record = { const FAILURE: Record = { 'not-found': 'change.failure.notFound', 'unauthenticated': 'change.failure.unauthenticated', + 'rate-limited': 'change.failure.rateLimited', 'too-large': 'change.failure.unavailable', 'stale': 'change.failure.unavailable', 'unsupported': 'change.failure.unavailable', @@ -122,11 +123,13 @@ function DiffSize({ snapshot, locale }: { readonly snapshot: ChangeRequestSnapsh } /** - * The changed lines with the unresolved review thread count, as a row that opens the changes view when the provider - * serves the change request. + * Render the changed lines with the unresolved review thread count, as a row that opens the changes view when the + * provider serves the change request. + * @param props - the change request, its snapshot, how the row names it, the actions, the number locale, and copy. + * @returns the row. */ -function ChangesRow({ entry, snapshot, name, actions, locale, t }: { - readonly entry: ForgePanelChangeRequest +export function ChangesRow({ entry, snapshot, name, actions, locale, t }: { + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot readonly name: string readonly actions: ChangeRequestActions @@ -293,12 +296,22 @@ function MergeMenu({ snapshot, name, usual, busy, onMerge, t }: { ) } -/** The footer with the merge action of an open change request the host would merge now. */ -function Primary({ entry, snapshot, name, actions, t }: { - readonly entry: ForgePanelChangeRequest +/** + * Render the merge action of an open change request the host would merge now. + * @param props.entry - the change request. + * @param props.snapshot - its latest snapshot. + * @param props.name - how menus name it. + * @param props.actions - the actions the surface offers. + * @param props.className - class of the wrapper, the card footer's by default. + * @param props.t - forge panel copy. + * @returns the action, or null when the host would not merge now or the surface does not offer it. + */ +export function ChangeRequestPrimary({ entry, snapshot, name, actions, className = css.footer, t }: { + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot readonly name: string readonly actions: ChangeRequestActions + readonly className?: string | undefined readonly t: Translate }): ReactNode { // One request at a time: the action stays disabled until the previous one settles. @@ -312,7 +325,7 @@ function Primary({ entry, snapshot, name, actions, t }: { const [usual] = snapshot.mergeMethods if (!snapshot.mergeReady || usual === undefined || merge === undefined) return null return ( -
+
+ } + value={finished(snapshot, now, t)} tone={snapshot.state} opens={false} /> +
+ ) +} + +/** + * The aggregate review outcome of an open change request in words, with its tone. + * @param snapshot - the snapshot. + * @param t - forge panel copy. + * @returns the outcome and its tone. + */ +export function reviewOutcome( + snapshot: ChangeRequestSnapshot, t: Translate, +): { readonly value: string; readonly tone: string | undefined } { + return { + value: t(REVIEW[snapshot.reviewDecision]), + tone: snapshot.reviewDecision === 'changes-requested' ? 'error' : snapshot.reviewDecision === 'approved' ? 'success' : undefined, + } +} + +/** + * Render the merge state of an open change request: whether it conflicts with its base, and the branch update. + * @param props - the change request, its snapshot, the update action, and copy. + * @returns the row. + */ +export function MergeStateRow({ entry, snapshot, updateBranch, t }: { + readonly entry: ChangeRequestEntry + readonly snapshot: ChangeRequestSnapshot + readonly updateBranch: ChangeRequestActions['updateBranch'] + readonly t: Translate +}): ReactNode { + const merge = snapshot.mergeability === 'mergeable' + ? t('change.merge.mergeable') + : snapshot.mergeability === 'conflicting' ? t('change.merge.conflicting', { base: snapshot.baseBranch }) : t('change.merge.unknown') + return ( + } + tone={snapshot.mergeability === 'conflicting' ? 'error' : undefined} t={t} /> + ) +} + +/** + * The facts of a change request one row each: the merged or closed state, or the checks, review, and merge state; + * the changed lines; and the linked issues. + */ function Details({ entry, snapshot, name, now, actions, locale, t }: { - readonly entry: ForgePanelChangeRequest + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot readonly name: string readonly now: number @@ -407,28 +478,19 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { if (snapshot.state !== 'open') { return (
-
- } - value={finished(snapshot, now, t)} tone={snapshot.state} opens={false} /> -
+ {changes}
) } - const review = t(REVIEW[snapshot.reviewDecision]) - const reviewTone = snapshot.reviewDecision === 'changes-requested' ? 'error' : snapshot.reviewDecision === 'approved' ? 'success' : undefined - const merge = snapshot.mergeability === 'mergeable' - ? t('change.merge.mergeable') - : snapshot.mergeability === 'conflicting' ? t('change.merge.conflicting', { base: snapshot.baseBranch }) : t('change.merge.unknown') + const review = reviewOutcome(snapshot, t) return (
- - } - tone={snapshot.mergeability === 'conflicting' ? 'error' : undefined} t={t} /> + {changes}
@@ -516,7 +578,7 @@ export function ChangeRequestCard({ entry, expanded, onToggle, now, actions, loc {expanded && snapshot !== null && (
)} - {expanded && snapshot !== null && } + {expanded && snapshot !== null && } ) } diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx index b77f385f7b..41f1c4ad9f 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestOverview.tsx @@ -17,11 +17,10 @@ import type { BranchUpdateMethod, BranchUpdateRequest, ChangeRequestCheck, ChangeRequestIssue, ChangeRequestReviewer, ChangeRequestSnapshot, ForgeRerunRequest, ForgeReviewerCandidate, ReviewVerdict, } from '@deepseek-ai/dsh-experimental-forge/types' -import type { ForgePanelChangeRequest } from '../types.ts' import { formatDuration } from './format.ts' import { CheckGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' -import { checkCounts, checkDuration } from './status.ts' +import { checkCounts, checkDuration, type ChangeRequestEntry } from './status.ts' import { searchFieldKeyDown } from './menu-search.ts' import css from './Forge.module.css' import overview from './ChangeRequestOverview.module.css' @@ -35,7 +34,7 @@ const SEARCH_DELAY_MS = 150 const AVATARS = 3 /** Requests reviews of a change request from more reviewers; settles once the outcome is reported. */ -type RequestReviews = (entry: ForgePanelChangeRequest, reviewers: readonly Pick[]) => Promise +type RequestReviews = (entry: ChangeRequestEntry, reviewers: readonly Pick[]) => Promise /** Lists the accounts a review of the change request at `url` can be requested from. */ type ListCandidates = (url: string, query: string, signal: AbortSignal) => Promise @@ -43,17 +42,20 @@ type ListCandidates = (url: string, query: string, signal: AbortSignal) => Promi /** Overview actions of a card; a surface without a Session binding omits them. */ export interface OverviewActions { /** Rerun the failed checks; settles once the outcome is reported. */ - readonly rerunChecks?: ((entry: ForgePanelChangeRequest, request: ForgeRerunRequest) => Promise) | undefined + readonly rerunChecks?: ((entry: ChangeRequestEntry, request: ForgeRerunRequest) => Promise) | undefined /** Request reviews from more reviewers; settles once the outcome is reported. */ readonly requestReviews?: RequestReviews | undefined /** List accounts a review can be requested from; rejects with the host's reason. */ readonly reviewerCandidates?: ListCandidates | undefined /** Bring the base branch's new commits into the head branch; settles once the outcome is reported. */ - readonly updateBranch?: ((entry: ForgePanelChangeRequest, request: BranchUpdateRequest) => Promise) | undefined + readonly updateBranch?: ((entry: ChangeRequestEntry, request: BranchUpdateRequest) => Promise) | undefined } -/** One action at a time per control: it stays disabled until the previous action settles. */ -function useBusy(): readonly [boolean, (action: () => Promise) => void] { +/** + * One action at a time per control: it stays disabled until the previous action settles. + * @returns whether an action runs, and the function that runs one. + */ +export function useBusy(): readonly [boolean, (action: () => Promise) => void] { const [busy, setBusy] = useState(false) return [busy, (action) => { setBusy(true) @@ -105,6 +107,26 @@ const GROUP_LABEL: Record = { other: 'checks.group.other', } +/** Checks of one outcome group. */ +export interface CheckGroupList { + readonly group: CheckGroup + /** Name of the group. */ + readonly label: ForgePanelKey + readonly checks: readonly ChangeRequestCheck[] +} + +/** + * Group checks by outcome, leaving out empty groups. + * @param checks - the checks of the head commit. + * @param kind - the failed, running, and cancelled groups, which need attention, or the passed and skipped ones. + * @returns the groups in display order. + */ +export function checkGroups(checks: readonly ChangeRequestCheck[], kind: 'attention' | 'quiet'): readonly CheckGroupList[] { + return (kind === 'attention' ? ATTENTION : QUIET) + .map(group => ({ group, label: GROUP_LABEL[group], checks: checks.filter(check => groupOf(check) === group) })) + .filter(entry => entry.checks.length > 0) +} + function groupOf(check: ChangeRequestCheck): CheckGroup { switch (check.state) { case 'failure': return 'failed' @@ -116,14 +138,25 @@ function groupOf(check: ChangeRequestCheck): CheckGroup { } } -function checkTime(check: ChangeRequestCheck, t: Translate): string { +/** + * How long a check took, or that it is queued or running. + * @param check - the check. + * @param t - forge panel copy. + * @returns the text, empty for a finished check without times. + */ +export function checkTime(check: ChangeRequestCheck, t: Translate): string { if (check.state === 'pending') return t(check.startedAt === null ? 'change.check.queued' : 'change.check.running') const elapsed = checkDuration(check) return elapsed === undefined ? '' : formatDuration(elapsed, t) } -/** The checks outcome in a few words: what needs attention, else that all passed. */ -function checksValue(snapshot: ChangeRequestSnapshot, t: Translate): string { +/** + * The checks outcome in a few words: what needs attention, else that all passed. + * @param snapshot - the snapshot whose checks are summarized. + * @param t - forge panel copy. + * @returns the summary. + */ +export function checksValue(snapshot: ChangeRequestSnapshot, t: Translate): string { if (snapshot.checksTruncated) return t('change.checks.truncated', { count: snapshot.checks.length }) const counts = checkCounts(snapshot.checks) const parts = [ @@ -138,13 +171,74 @@ type CheckRead = { readonly kind: 'idle' | 'loading' } | { readonly kind: 'ready'; readonly snapshot: ChangeRequestSnapshot } | { readonly kind: 'failed'; readonly message: string } +type ReadChecks = ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined + +/** + * Complete a check list the poll read only in part: while `active`, read the complete list of the snapshot's head + * independently of polling, and stop when `active` ends or the head moves. + * @param snapshot - the polled snapshot. + * @param active - whether the checks are shown in full. + * @param readChecks - loads the complete checks, or undefined on a surface that cannot. + * @returns the snapshot to display, the state of the read, and a function that reads again. + */ +export function useCompleteChecks(snapshot: ChangeRequestSnapshot, active: boolean, readChecks: ReadChecks): { + readonly displayed: ChangeRequestSnapshot + readonly read: CheckRead + readonly retry: () => void +} { + const [read, setRead] = useState({ kind: 'idle' }) + const [attempt, setAttempt] = useState(0) + const { url, headSha, checksTruncated } = snapshot + useEffect(() => { + if (!active || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } + const controller = new AbortController() + setRead({ kind: 'loading' }) + void (async () => { + try { + const result = await readChecks(url, headSha, controller.signal) + if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) + } catch (error) { + if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) + } + })() + return () => { controller.abort() } + }, [active, url, headSha, checksTruncated, readChecks, attempt]) + return { + displayed: read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot, + read, + retry: () => { setAttempt(value => value + 1) }, + } +} + +/** + * Render the state of a complete-checks read that has not finished: that it loads, or why it failed with a retry. + * @param props - the read, the retry, and copy. + * @returns the status line, or null when nothing is being read or the read finished. + */ +export function ChecksReadStatus({ read, retry, t }: { + readonly read: CheckRead + readonly retry: () => void + readonly t: Translate +}): ReactNode { + if (read.kind === 'loading') { + return
{t('change.checks.loading')}
+ } + if (read.kind !== 'failed') return null + return ( +
+ {t('change.checks.loadFailed', { message: read.message })} + +
+ ) +} + /** Props of the checks row. */ export interface ChecksRowProps { - readonly entry: ForgePanelChangeRequest + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot readonly openLink: (url: string) => void /** Load complete check details independently of polling; cancellation follows the open menu. */ - readonly readChecks: ((url: string, headSha: string, signal: AbortSignal) => Promise) | undefined + readonly readChecks: ReadChecks readonly rerunChecks: OverviewActions['rerunChecks'] readonly t: Translate } @@ -160,6 +254,16 @@ function rerunnable(checks: readonly ChangeRequestCheck[]): boolean { return checks.some(check => check.state === 'failure' && check.rerun !== null && !running.has(check.rerun)) } +/** + * The rerun of failed checks, when the change request is open, the signed-in user may rerun, and a rerun can start. + * @param displayed - the snapshot whose checks are shown. + * @param rerunChecks - the surface's rerun action. + * @returns the action, or undefined when no rerun is offered. + */ +export function rerunOf(displayed: ChangeRequestSnapshot, rerunChecks: OverviewActions['rerunChecks']): OverviewActions['rerunChecks'] { + return displayed.state === 'open' && displayed.canRerunChecks && rerunnable(displayed.checks) ? rerunChecks : undefined +} + /** * Render the checks outcome as a row whose menu lists the failed, running, and cancelled checks by group, offers to * rerun the failed ones, and lists the passed and skipped ones on request. A list the poll read only in part is @@ -170,41 +274,22 @@ function rerunnable(checks: readonly ChangeRequestCheck[]): boolean { export function ChecksRow({ entry, snapshot, openLink, readChecks, rerunChecks, t }: ChecksRowProps): ReactNode { const [open, setOpen] = useState(false) const [quiet, setQuiet] = useState(false) - const [read, setRead] = useState({ kind: 'idle' }) - const [attempt, setAttempt] = useState(0) const [busy, run] = useBusy() - const { url, headSha, checksTruncated } = snapshot - useEffect(() => { - if (!open || !checksTruncated || readChecks === undefined) { setRead({ kind: 'idle' }); return } - const controller = new AbortController() - setRead({ kind: 'loading' }) - void (async () => { - try { - const result = await readChecks(url, headSha, controller.signal) - if (!controller.signal.aborted) setRead({ kind: 'ready', snapshot: result }) - } catch (error) { - if (!controller.signal.aborted) setRead({ kind: 'failed', message: error instanceof Error ? error.message : String(error) }) - } - })() - return () => { controller.abort() } - }, [open, url, headSha, checksTruncated, readChecks, attempt]) - const displayed = read.kind === 'ready' && read.snapshot.headSha === headSha ? read.snapshot : snapshot + const { headSha } = snapshot + const { displayed, read, retry } = useCompleteChecks(snapshot, open, readChecks) if (displayed.checks.length === 0 && !displayed.checksTruncated) { return
} value={t('change.ci.none')} opens={false} />
} const counts = checkCounts(displayed.checks) - const rerun = displayed.state === 'open' && displayed.canRerunChecks && rerunnable(displayed.checks) ? rerunChecks : undefined - const groups = (list: readonly CheckGroup[]): { readonly group: CheckGroup; readonly checks: ChangeRequestCheck[] }[] => - list.map(group => ({ group, checks: displayed.checks.filter(check => groupOf(check) === group) })) - .filter(({ checks }) => checks.length > 0) + const rerun = rerunOf(displayed, rerunChecks) const quietCount = counts.passed + counts.other const close = (): void => { setOpen(false) setQuiet(false) } - const rows = (list: readonly CheckGroup[]): ReactNode => groups(list).map(({ group, checks }) => ( -
-
{`${t(GROUP_LABEL[group])} · ${checks.length}`}
+ const rows = (kind: 'attention' | 'quiet'): ReactNode => checkGroups(displayed.checks, kind).map(({ group, label, checks }) => ( +
+
{`${t(label)} · ${checks.length}`}
{checks.map((check, index) => { const link = check.url return ( @@ -241,21 +326,15 @@ export function ChecksRow({ entry, snapshot, openLink, readChecks, rerunChecks, {t('checks.rerunFailed')} )} - {rows(ATTENTION)} - {quiet ? rows(QUIET) : quietCount > 0 && ( + {rows('attention')} + {quiet ? rows('quiet') : quietCount > 0 && ( 0} icon={ 0 ? 'success' : 'skipped'} size={14} />} onSelect={() => { setQuiet(true) }}> {t('checks.showQuiet', { count: quietCount })} )} - {read.kind === 'loading' &&
{t('change.checks.loading')}
} - {read.kind === 'failed' && ( -
- {t('change.checks.loadFailed', { message: read.message })} - -
- )} + ) } @@ -283,7 +362,7 @@ function Avatar({ url, login, size = 20 }: { readonly url: string | null; readon /** Props of the review row. */ export interface ReviewRowProps { - readonly entry: ForgePanelChangeRequest + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot /** The aggregate review outcome. */ readonly value: string @@ -331,8 +410,7 @@ export function ReviewRow({ entry, snapshot, value, tone, requestReviews, review close() run(() => ask(entry, [reviewer])) } - // Asking again suits people who reviewed and are not asked now; bots review on their own triggers. - const again = reviewers.filter(reviewer => reviewer.kind !== 'bot' && !reviewer.requested && reviewer.verdict !== null) + const again = reviewersToAskAgain(reviewers) return ( )} - {request !== undefined && again.map((reviewer, index) => ( - } - onSelect={() => { request(reviewer) }}> - {t('reviewers.rerequestAria', { login: reviewer.login })} - - ))} - {canRequest && ( - } - onSelect={() => { setSearching(true) }}> - {t('reviewers.requestMore')} - + {request !== undefined && ( + { setSearching(true) }} t={t} /> )} )} @@ -375,8 +444,50 @@ export function ReviewRow({ entry, snapshot, value, tone, requestReviews, review ) } -/** One reviewer in the review menu: avatar, login, what kind of reviewer, and their latest outcome or pending request. */ -function ReviewerLine({ reviewer, headSha, t }: { +/** + * The reviewers a review can be asked of again: people who reviewed and are not asked now. Bots review on their own + * triggers. + * @param reviewers - the change request's reviewers. + * @returns the reviewers to offer. + */ +export function reviewersToAskAgain(reviewers: readonly ChangeRequestReviewer[]): readonly ChangeRequestReviewer[] { + return reviewers.filter(reviewer => reviewer.kind !== 'bot' && !reviewer.requested && reviewer.verdict !== null) +} + +/** + * Render the menu items that request reviews: one per reviewer to ask again, then the search for someone else. + * @param props - the reviewers to ask again, whether a separator precedes the first item, the request and search + * handlers, and copy. + * @returns the items. + */ +export function ReviewRequestItems({ again, separated, onRequest, onSearch, t }: { + readonly again: readonly ChangeRequestReviewer[] + readonly separated: boolean + readonly onRequest: (reviewer: Pick) => void + readonly onSearch: () => void + readonly t: Translate +}): ReactNode { + return ( + <> + {again.map((reviewer, index) => ( + } onSelect={() => { onRequest(reviewer) }}> + {t('reviewers.rerequestAria', { login: reviewer.login })} + + ))} + } onSelect={onSearch}> + {t('reviewers.requestMore')} + + + ) +} + +/** + * Render one reviewer: avatar, login, what kind of reviewer, and their latest outcome or pending request. + * @param props - the reviewer, the head commit their outcome is compared with, and copy. + * @returns the line. + */ +export function ReviewerLine({ reviewer, headSha, t }: { readonly reviewer: ChangeRequestReviewer readonly headSha: string readonly t: Translate @@ -408,8 +519,13 @@ function ReviewerLine({ reviewer, headSha, t }: { type Listing = { readonly query: string } & ( { readonly ok: true; readonly value: readonly ForgeReviewerCandidate[] } | { readonly ok: false }) -/** The searchable account list of a review request: the host's suggestions first, then accounts matching the search. */ -function ReviewerSearch({ url, list, choose, t }: { +/** + * Render the searchable account list of a review request: the host's suggestions first, then accounts matching the + * search. + * @param props - the change request URL, the listing, the choice handler, and copy. + * @returns the search field and its list. + */ +export function ReviewerSearch({ url, list, choose, t }: { readonly url: string readonly list: ListCandidates readonly choose: (login: string) => void @@ -480,7 +596,7 @@ function ReviewerSearch({ url, list, choose, t }: { /** Props of the merge row. */ export interface MergeRowProps { - readonly entry: ForgePanelChangeRequest + readonly entry: ChangeRequestEntry readonly snapshot: ChangeRequestSnapshot /** Glyph of the row. */ readonly icon: ReactNode diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx index 77dafc3b66..583be68686 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestsSection.tsx @@ -9,14 +9,14 @@ import type { } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeReadiness, MergeRequest } from '@deepseek-ai/dsh-experimental-forge/types' import type { PanelDetailsProps } from '@deepseek-ai/dsh-client-ui-session-panel/client' -import type { ForgePanelChangeRequest, ForgePanelState } from '../types.ts' +import type { ForgePanelState } from '../types.ts' import { ChangeRequestCard, type ChangeRequestActions } from './ChangeRequestCard.tsx' import type { createChangeRequestsSectionStore } from './change-requests-store.ts' import type { NS } from './locales.ts' import { ReasonButton } from './ReasonButton.tsx' import type {} from './slots.ts' import type { PanelSnapshot } from './source.ts' -import { defaultExpanded } from './status.ts' +import { defaultExpanded, type ChangeRequestEntry } from './status.ts' import css from './Forge.module.css' /** Business face of the change requests section. */ @@ -32,11 +32,11 @@ export interface ChangeRequestsSectionInjected { */ readonly refresh: () => Promise /** Remove a change request from the Session, offering to undo it. */ - readonly remove: (entry: ForgePanelChangeRequest) => void + readonly remove: (entry: ChangeRequestEntry) => void /** Mark a draft ready for review; settles once the outcome is reported. */ - readonly markReady: (entry: ForgePanelChangeRequest) => Promise + readonly markReady: (entry: ChangeRequestEntry) => Promise /** Merge a change request as `request` describes; settles once the outcome is reported. */ - readonly merge: (entry: ForgePanelChangeRequest, request: MergeRequest) => Promise + readonly merge: (entry: ChangeRequestEntry, request: MergeRequest) => Promise /** Read the complete checks of an opened change request. */ readonly readChecks: NonNullable /** Rerun the failed checks or one check; settles once the outcome is reported. */ @@ -52,7 +52,7 @@ export interface ChangeRequestsSectionInjected { /** Copy text to the clipboard and report the outcome. */ readonly copyText: (text: string) => void /** Open the changes view of a bound change request in the right sidebar. */ - readonly viewChanges: (entry: ForgePanelChangeRequest) => void + readonly viewChanges: (entry: ChangeRequestEntry) => void } /** Full props of the change requests section. */ diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index c05b0d3feb..beb8069120 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -29,20 +29,20 @@ import { assertNever } from '@deepseek-ai/dsh-util-values' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeExtensionState, ForgeLensFrame, - ForgeLensKeep, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, + ForgeLensKeep, ForgeLensRequest, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, } from '../types.ts' import { lensVersion } from '../lens-version.ts' import type { ForgeCommitList, ForgeReviewData, ForgeReviewRequest, ForgeReviewResult, ForgeReviewThread, ForgeReviewWrite, ForgeReviewWriteResult, ForgeThreadId, ForgeViewedFiles, ForgeViewedRequest, } from '@deepseek-ai/dsh-experimental-forge/types' -import { sameReviewSource, type ReviewQueue } from './review-queue.ts' +import { sameReviewSource, type RemovedRecord, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import type { ReviewActions } from './ReviewComposer.tsx' import { SubmitReview } from './SubmitReview.tsx' -import type { ReviewSelection, ReviewSource } from './review.ts' +import type { QuoteCopy, ReviewSelection, ReviewSource } from './review.ts' import { BaseMenu } from './BaseMenu.tsx' -import { parseChangesAddress, type ChangesSource } from './changes-address.ts' +import { parseChangesAddress, type ChangesSource, type ChangesTarget } from './changes-address.ts' import type { ChangesLens, createChangesStore } from './changes-store.ts' import { CommitMenu } from './CommitMenu.tsx' import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' @@ -70,8 +70,8 @@ import type { FileThreads, ThreadActions, ThreadFocus, ThreadWrite } from './Rev import { inFileOrder, type ThreadFilter } from './review-threads.ts' import { usePlacedThreads, useThreadRead, type PlacedThread } from './thread-state.ts' import { ThreadList } from './ThreadList.tsx' -import type { HostStream, PanelSnapshot, StreamSnapshot } from './source.ts' -import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf } from './status.ts' +import type { HostStream, NoticeOptions, PanelSnapshot, StreamSnapshot } from './source.ts' +import { numberOf, openChangeRequestOf, TONE_LABEL, toneOf, type ChangeRequestEntry, type ChangesPanelState } from './status.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -88,9 +88,9 @@ interface Wanted { /** Business face of the changes tab body. */ export interface ChangesTabInjected { /** Append a frozen comment to the main input without submitting it. */ - readonly addReviewToInput: (selection: ReviewSelection) => boolean + readonly addReviewToInput: (selection: ReviewSelection) => boolean | Promise /** Records retained across Session switches and cleared when this tab occurrence closes. */ - readonly reviewQueue: (tab: Pick) => ReviewQueue + readonly reviewQueue: (tab: Pick) => ReviewQueue /** Publish one comment or a completed review; never retries mutations. */ readonly submitReview: (url: string, request: ForgeReviewRequest) => Promise> /** @@ -142,15 +142,15 @@ export interface ChangesTabInjected { /** Write to the review threads or the pending review of a change request; never retries a write. */ readonly changeRequestReviewWrite: (url: string, write: ForgeReviewWrite) => Promise> /** Quote a whole review thread of the change request at `url` in the main input without submitting it. */ - readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean + readonly addThreadToInput: (thread: ForgeReviewThread, url: string, range: string | null) => boolean | Promise /** Open a URL outside the app. */ readonly openLink: (url: string) => void /** Copy a path to the clipboard and report the outcome. */ readonly copyPath: (path: string) => void /** Ask the Session's Agent to create a change request for its changes, reporting the outcome. */ readonly createChangeRequest: () => void - /** Show a failure notice. */ - readonly report: (key: ForgePanelKey, params?: Readonly>) => void + /** Show a notice: a failure unless the options name another tone, with the undo action they carry. */ + readonly report: (key: ForgePanelKey, options?: NoticeOptions) => void } /** Full props of the changes tab body. */ @@ -162,6 +162,32 @@ export type ChangesTabProps = & InjectFace & PropsLocale +/** The tab facts the changes view reads: its sidebar tab's, or the review page's for one change request. */ +export interface ChangesViewTab extends Pick { + /** Identity the view's choices and pending review comments are kept under. */ + readonly id: string + /** Bind the view's refresh to the tab's refresh command; returns the unbinding. */ + readonly actions: Pick +} + +/** Props of the changes view, which the changes tab and the review page draw. */ +export type ChangesViewProps = Omit & { + /** Tab facts. */ + readonly tab: ChangesViewTab + /** What the view shows. */ + readonly source: ChangesSource + /** The view plugins see, or null on the review page, where plugin slots and annotations do not show. */ + readonly target: ChangesTarget | null + /** The panel facts while known, and whether their stream ended. */ + readonly snapshot: { readonly state: ChangesPanelState | null; readonly disconnected: boolean } | undefined + /** Plugin annotations of the view, or undefined before any. */ + readonly annotations: ViewAnnotations | undefined + /** Open a file of the checkout in the right sidebar, by its absolute path; undefined where no sidebar shows. */ + readonly openFile: ((path: string) => void) | undefined + /** Copy of the quote actions where they quote somewhere other than the Session's input. */ + readonly quoteCopy?: QuoteCopy | undefined +} + /** Changes of either source as the view draws them. */ type ChangesData = | { @@ -374,7 +400,7 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: { readonly url: string - readonly entry: ForgePanelChangeRequest | undefined + readonly entry: ChangeRequestEntry | undefined /** Commit picker left of the review button. */ readonly commitMenu: ReactNode readonly reviewCount: number @@ -412,7 +438,7 @@ function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDis * that uncommitted changes count; for another scope, what it compares. */ function LocalHeader({ state, scope, base, missing, visible, diffBases, choose, commitMenu, createChangeRequest, t }: { - readonly state: ForgePanelState | null + readonly state: ChangesPanelState | null /** Commit picker of the `branch` scope, left of the create button. */ readonly commitMenu: ReactNode readonly scope: ScopeKind @@ -517,18 +543,33 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { * @param props - tab information, the tab's choices, the panel snapshot hook, reads and actions, and copy. * @returns the view body. */ -export function ChangesTab({ - useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, - changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, changeRequestViewed, setFileViewed, - openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, submitReview, report, useLenses, - useExtensions, useAnnotations, changesLens, renderSlot, t: translate, -}: ChangesTabProps): ReactNode { +export function ChangesTab({ useTabInfo, sessionId, usePanel, useAnnotations, ...props }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() - const { navigation, signal } = tab const target = useMemo(() => parseChangesAddress(tab.contentId), [tab.contentId]) if (target === undefined) throw new Error(`forge-panel: not a changes address "${tab.contentId}"`) - const source = target.source const snapshot = usePanel(tab.visible ? 'visible' : 'inactive') + const annotations = useAnnotations(tab.contentId) + const tabActions = tab.actions + const openFile = useCallback((path: string) => { + tabActions.openResource(fileAddressFor(sessionId, undefined, path)) + }, [tabActions, sessionId]) + return +} + +/** + * Render the changes of a Session's checkout or of one change request. + * @param props - tab facts, what the view shows, the view's choices, the panel facts, reads and actions, and copy. + * @returns the view body. + */ +export function ChangesView({ + tab, source, target, snapshot, annotations: viewAnnotations, openFile, quoteCopy, useStore, actions, reconnect, localDiff, diffBases, + localText, + localCommits, changeRequestDiff, changeRequestText, changeRequestCommits, changeRequestReview, changeRequestReviewWrite, viewedFiles, + changeRequestViewed, setFileViewed, openLink, copyPath, createChangeRequest, addReviewToInput, addThreadToInput, reviewQueue, + submitReview, report, useLenses, useExtensions, changesLens, renderSlot, t: translate, +}: ChangesViewProps): ReactNode { + const { navigation, signal } = tab const state = snapshot?.state ?? null const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined const { t, host: hostCopy } = useForgeCopy(translate, source.kind === 'change' ? source.url : null, entry?.forge ?? null) @@ -562,8 +603,8 @@ export function ChangesTab({ return message } if (!complete(result.url)) return t('review.unknown') - if (request.kind === 'review') report('review.submitted') - else report('review.published', hostCopy) + if (request.kind === 'review') report('review.submitted', { tone: 'success' }) + else report('review.published', { tone: 'success', params: hostCopy }) if (request.kind === 'review') setReviewOpen(false) return undefined } catch (_error) { @@ -768,7 +809,7 @@ export function ChangesTab({ useEffect(() => { if (withdrawn === null) return actions.filtered(tab.id, null) - report('filterLens.removed', { lens: live.current.lensTitle(withdrawn) }) + report('filterLens.removed', { params: { lens: live.current.lensTitle(withdrawn) } }) }, [withdrawn, actions, tab.id, report]) const chooseLens = (next: string | null): void => { actions.filtered(tab.id, next) } // The hunks each kept file folds stay folded until the reader shows them for that file; a new result folds again. @@ -787,7 +828,7 @@ export function ChangesTab({ } return map }, [allFiles, kept, shownPaths, foldTitle]) - const annotations = useAnnotations(tab.contentId) ?? NO_ANNOTATIONS + const annotations = viewAnnotations ?? NO_ANNOTATIONS // Annotations wait for the Host's limit. const annotationLimit = extensions?.maxAnnotationsPerFile const shownSource = useMemo(() => data === null ? null : reviewSourceOf(data), [data]) @@ -796,9 +837,9 @@ export function ChangesTab({ const hostOwner = useMemo(() => data?.kind === 'change' && data.viewed !== null ? { url: data.url, headSha: data.headSha, files: data.files, viewed: data.viewed } : null, [data]) const host = useHostViewed(hostOwner, setFileViewed, (failure) => { - if (failure.kind === 'stale') report('viewed.syncStale', hostCopy) - else if (failure.kind === 'unknown') report('viewed.syncUnknown', { message: failure.message }) - else report('viewed.syncFailed', { ...hostCopy, message: failure.message }) + if (failure.kind === 'stale') report('viewed.syncStale', { params: hostCopy }) + else if (failure.kind === 'unknown') report('viewed.syncUnknown', { params: { message: failure.message } }) + else report('viewed.syncFailed', { params: { ...hostCopy, message: failure.message } }) }) const marks = host?.marks ?? localMarks // Files marked viewed at their current change, which the file tree draws subdued. @@ -900,7 +941,7 @@ export function ChangesTab({ return } if (result.ok) report('toast.expandStale') - else report('toast.expandFailed', { message: result.error.message }) + else report('toast.expandFailed', { params: { message: result.error.message } }) update((value) => { const { [path]: _text, ...texts } = value.texts const { [path]: _open, ...open } = value.open @@ -929,8 +970,8 @@ export function ChangesTab({ const list: DiffFileAction[] = [{ label: 'diff.copyPath', run: () => { copyPath(file.path) } }] if (file.status === 'deleted') return list if (owner.kind === 'local') { - if (root !== null) { - list.push({ label: 'diff.openFileInSidebar', run: () => { tab.actions.openResource(fileAddressFor(sessionId, undefined, `${root}/${file.path}`)) } }) + if (root !== null && openFile !== undefined) { + list.push({ label: 'diff.openFileInSidebar', run: () => { openFile(`${root}/${file.path}`) } }) } } else { const url = owner.fileUrls[file.path] @@ -954,7 +995,7 @@ export function ChangesTab({ setReviewError(failure) return } - report(done) + report(done, { tone: 'success' }) setReviewOpen(false) } finally { reviewRunning.current = false @@ -1000,11 +1041,15 @@ export function ChangesTab({ return writeReview(selection.source.url, { kind: 'add-pending', headSha: selection.source.headSha, comment: { path, side, startLine, endLine, body } }) } + /** Report a reference or receipt removed from the view and offer to put it back where it was. */ + const reportRemoved = (removed: RemovedRecord): void => { + report('review.recordRemoved', { tone: 'success', undo: () => { if (!queue.restoreRecord(removed)) report('toast.undoFailed') } }) + } const recordActions: ReviewActions = { source: shownSource ?? (source.kind === 'local' ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } : { kind: 'change', url: source.url, headSha: '', commits: changeCommits }), - records: queue, addToInput: addReviewToInput, openLink, + records: queue, addToInput: addReviewToInput, openLink, quoteCopy, onRemoved: reportRemoved, } const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] .filter(item => sameReviewSource(item.source, recordActions.source)).map(item => item.comment.path))] @@ -1017,16 +1062,17 @@ export function ChangesTab({ const threadActions = useMemo((): ThreadActions | null => review === null || url === null ? null : { author: prAuthor, addToInput: (thread, range) => addThreadToInput(thread, url, range), + quoteCopy, openLink, readText: (commit, path) => changeRequestText(url, commit, path), - inputFailed: () => { live.current.report('thread.inputFailed') }, + inputFailed: () => { live.current.report(quoteCopy?.failed ?? 'thread.inputFailed') }, focused: focus, writes: { write: (write: ThreadWrite) => live.current.writeReview(url, { ...write, headSha: review.headSha }), reviewStarted: review.pendingReview !== null, canReview: review.viewerCanReview, }, - }, [review, url, prAuthor, addThreadToInput, openLink, changeRequestText, focus]) + }, [review, url, prAuthor, addThreadToInput, quoteCopy, openLink, changeRequestText, focus]) const fileThreads = useMemo(() => new Map(threadActions === null ? [] : [...placed.files].map(([path, group]) => [path, { ...group, actions: threadActions }])), [placed.files, threadActions]) /** Show a file's next unresolved thread in display order after the one last shown, or its first. */ @@ -1141,7 +1187,7 @@ export function ChangesTab({ // props and state, which the retried render assigns again. const callbacks = { data, expandedByDefault, expand, readContext, markViewed, fileActions, publishReview, writeReview, addPending, report, nextThread, - lensTitle, renderSlot, kept, t, + lensTitle, renderSlot, kept, reportRemoved, t, } const live = useRef(callbacks) live.current = callbacks @@ -1177,9 +1223,9 @@ export function ChangesTab({ }, nextThread: (path) => { live.current.nextThread(path) }, reach, - annotation: (path, item: SourcedAnnotation) => live.current.renderSlot('forge.diff.line.annotation', + annotation: (path, item: SourcedAnnotation) => target === null ? null : live.current.renderSlot('forge.diff.line.annotation', { target, path, annotation: item.annotation }, { entryKey: item.source }), - fileMenu: (file, dismiss) => live.current.renderSlot('forge.changes.file.menu', { target, file, dismiss }), + fileMenu: (file, dismiss) => target === null ? null : live.current.renderSlot('forge.changes.file.menu', { target, file, dismiss }), unfold: (path) => { const { kept: current } = live.current setUnfolded(value => ({ kept: current, paths: new Set([...(value.kept === current ? value.paths : []), path]) })) @@ -1196,9 +1242,11 @@ export function ChangesTab({ const fileReview = useMemo((): ReviewActions | undefined => shownSource === null ? undefined : { source: shownSource, addToInput: addReviewToInput, - renderActions: owner => live.current.renderSlot('forge.diff.comment.actions', { target, ...owner }), + quoteCopy, + renderActions: owner => target === null ? null : live.current.renderSlot('forge.diff.comment.actions', { target, ...owner }), records: queue, openLink, reviewStarted, onQuoted: (selection) => { if (!queue.recordAgent(selection)) live.current.report('review.saveFailed') }, + onRemoved: (removed) => { live.current.reportRemoved(removed) }, publishingBlocked, ...queueable ? { queue: (selection: ReviewSelection) => live.current.addPending(selection) } : {}, ...single ? { @@ -1207,7 +1255,7 @@ export function ChangesTab({ url => queue.published(selection, url)) : Promise.resolve(live.current.t('review.stale')), } : {}, - }, [shownSource, addReviewToInput, queue, openLink, reviewStarted, publishingBlocked, queueable, single, target]) + }, [shownSource, addReviewToInput, quoteCopy, queue, openLink, reviewStarted, publishingBlocked, queueable, single, target]) let body: ReactNode if (data === null) { @@ -1349,7 +1397,7 @@ export function ChangesTab({ )} - {renderSlot('forge.changes.toolbar', { target, form: 'bar', close: noop })} + {target !== null && renderSlot('forge.changes.toolbar', { target, form: 'bar', close: noop })} {/* A truncated read keeps the list, whose footer says so, even when it kept no thread. */} {review !== null && (review.threads.length > 0 || review.truncated) && (
diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css index d79ac0b0e2..5a1a4eb81d 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.module.css @@ -1,9 +1,8 @@ /* Inline review forms use the same field, action, and badge treatments as settings and conversation controls. */ -.root, .thread { box-sizing: border-box; width: calc(100% - 20px); max-width: 680px; margin: 10px; padding: 12px; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md); background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary); font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); white-space: normal; } -.root { background: var(--dsw-alias-bg-layer-2); border-radius: var(--dsw-radius-lg); } +.root { box-sizing: border-box; width: calc(100% - 20px); max-width: 680px; margin: 10px; padding: 12px; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-lg); background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); font: var(--dsw-font-xs-13); font-family: Inter, var(--dsw-font-family); white-space: normal; } .root:focus-within { border-color: var(--dsw-alias-border-l4); } /* Side by side, a comment fills its side's cell under the code instead of the row's width. */ -[data-forge-comments] > .root, [data-forge-comments] > .thread { width: auto; max-width: none; margin: 0; } +[data-forge-comments] > .root { width: auto; max-width: none; margin: 0; } .title { margin-bottom: 12px; color: var(--dsw-alias-label-secondary); overflow-wrap: anywhere; } /* Fixed-size textarea layout stays local during typing; native resizing can still change its outer height. */ .input { display: block; box-sizing: border-box; width: 100%; height: 88px; min-height: 88px; contain: strict; padding: 10px 12px; resize: vertical; border: 0.5px solid var(--dsw-alias-border-l4); border-radius: var(--dsw-radius-md); outline: none; background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-primary); font: inherit; } @@ -16,11 +15,6 @@ .gitAction { display: inline-flex; flex: none; align-items: stretch; } .gitMain { border-start-end-radius: 0; border-end-end-radius: 0; } .gitArrow { width: 30px; padding: 0; border-start-start-radius: 0; border-end-start-radius: 0; border-inline-start: 0.5px solid color-mix(in srgb, var(--dsw-alias-label-primary-foreground) 25%, transparent); } -.threadHeader { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin-bottom: 8px; } -.author { font-weight: 500; } -.range { color: var(--dsw-alias-label-secondary); font-size: 12px; } -.commentBody { white-space: pre-wrap; overflow-wrap: anywhere; } -.threadActions { display: flex; flex-wrap: wrap; gap: 4px; margin: 8px -8px -4px; } .gutter { position: relative; } .line { display: block; width: 100%; height: 100%; padding: 0; color: inherit; text-align: inherit; cursor: pointer; border: 0; border-radius: 0; background: transparent; font: inherit; user-select: none; touch-action: pan-y; } .selected { background: var(--dsw-alias-interactive-bg-hover); outline: 1px solid var(--dsw-alias-border-l2); outline-offset: -1px; } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx index 843b307aff..b2dcaef2dd 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewComposer.tsx @@ -4,8 +4,8 @@ import { useEffect, useRef, useState, type ReactNode } from 'react' import clsx from 'clsx' import { Button, IconChevronDownOutlineRegular, Menu, MenuItemButton } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' -import type { ReviewQueue } from './review-queue.ts' -import { reviewRange, type ReviewSelection, type ReviewSource } from './review.ts' +import type { RemovedRecord, ReviewQueue } from './review-queue.ts' +import { INPUT_QUOTE_COPY, reviewRange, settleQuote, type QuoteCopy, type ReviewSelection, type ReviewSource } from './review.ts' import type { NS } from './locales.ts' import type { ForgeCommentActionsProps } from './slots.ts' import css from './ReviewComposer.module.css' @@ -22,10 +22,14 @@ export interface ReviewActions { readonly openLink?: (url: string) => void /** A write is running or its outcome still needs confirmation. */ readonly publishingBlocked?: boolean - /** Append an atomic quote without sending the Agent a message. */ - readonly addToInput: (selection: ReviewSelection) => boolean + /** Append an atomic quote without sending the Agent a message; resolves to whether it was accepted. */ + readonly addToInput: (selection: ReviewSelection) => boolean | Promise + /** Copy of the quote button, the quoted tag, and the refusal; the input's copy by default. */ + readonly quoteCopy?: QuoteCopy | undefined /** Retain a new comment after its quote was accepted. */ readonly onQuoted?: (selection: ReviewSelection) => void + /** Report a reference or publication receipt the reader removed from the view, so the report can offer to put it back. */ + readonly onRemoved?: (removed: RemovedRecord) => void /** Publish one comment; an error string preserves the editor. */ readonly publish?: (selection: ReviewSelection) => Promise /** Add one comment to the pending review on the code host, starting one when needed; an error string preserves the editor. */ @@ -76,6 +80,7 @@ export function ReviewComposer({ selection, actions, close, visible = true, t }: const [empty, setEmpty] = useState(body.current.trim() === '') const [busy, setBusy] = useState(false) const [error, setError] = useState(null) + const copy = actions.quoteCopy ?? INPUT_QUOTE_COPY const running = useRef(false) const input = useRef(null) useEffect(() => { input.current?.focus() }, []) @@ -115,9 +120,11 @@ export function ReviewComposer({ selection, actions, close, visible = true, t }: + settleQuote(actions.addToInput(selected), (accepted) => { + if (accepted) { actions.onQuoted?.(selected); close() } + else setError(t(copy.failed)) + }) + }}>{t(copy.add)} {actions.renderActions?.({ selection: { path: selection.comment.path, side: selection.comment.side, diff --git a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx index b7f2f818a5..d98df0691e 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewThread.tsx @@ -4,10 +4,12 @@ import { useCallback, useState, useSyncExternalStore, type ReactNode } from 'rea import { Button, Tag } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ReviewActions } from './ReviewComposer.tsx' +import { CardMenu, DeleteConfirm } from './ReviewThreads.tsx' import { EMPTY_FILE_REVIEW, type FileReviewState, type ReviewThread as Thread } from './review-queue.ts' -import { reviewRange } from './review.ts' +import { INPUT_QUOTE_COPY, reviewRange, settleQuote } from './review.ts' import type { NS } from './locales.ts' -import css from './ReviewComposer.module.css' +import css from './ReviewThreads.module.css' +import composerCss from './ReviewComposer.module.css' const noSubscription = (): (() => void) => () => {} @@ -24,7 +26,9 @@ export function useFileReview(actions: ReviewActions | undefined, path: string): } /** - * Render a saved comment at its line. A comment draft kept in the browser can be edited, deleted, or moved into the + * Render a saved comment at its line: its lines and state, the menu of its less frequent actions, its text, and Add to + * input. A reference or a publication receipt can be removed from the view, which leaves the main input and the code + * host as they are. A comment draft kept in the browser can be edited, deleted after a confirmation, or moved into the * pending review on the code host. * @param props - record, edit availability, source actions, and localized copy. * @returns one compact inline comment card. @@ -35,16 +39,21 @@ export function ReviewThread({ thread, actions, locked, outdated, t }: PropsLoca readonly locked: boolean readonly outdated: boolean }): ReactNode { - const [editing, setEditing] = useState(false) + const [mode, setMode] = useState<'view' | 'edit' | 'delete'>('view') const [body, setBody] = useState(thread.selection.comment.body) const [error, setError] = useState(null) const [moving, setMoving] = useState(false) const comment = thread.selection.comment - const quoted = editing && thread.kind === 'pending' ? { ...thread.selection, comment: { ...comment, body } } : thread.selection + // A draft published while its form is open becomes a receipt, which has neither form. + const editing = mode === 'edit' && thread.kind === 'pending' + const confirming = mode === 'delete' && thread.kind === 'pending' + const quoted = editing ? { ...thread.selection, comment: { ...comment, body } } : thread.selection const range = reviewRange(comment) - const status = thread.kind === 'pending' ? 'review.browserDraft' : thread.kind === 'published' ? 'review.published' : 'review.quoted' + const copy = actions.quoteCopy ?? INPUT_QUOTE_COPY + const status = thread.kind === 'pending' ? 'review.browserDraft' : thread.kind === 'published' ? 'review.published' : copy.added const save = (): boolean => actions.records?.editThread(thread.key, body) === true const queue = actions.queue + const waiting = locked || moving /** Add the draft to the pending review on the code host, then delete it from the browser. */ const move = async (add: NonNullable): Promise => { setMoving(true) @@ -59,37 +68,53 @@ export function ReviewThread({ thread, actions, locked, outdated, t }: PropsLoca setMoving(false) } } - return
-
- {t('review.yourComment')} - {range} - {t(outdated ? 'review.outdated' : status)} + const select = (id: string): void => { + if (id === 'edit') { + setBody(comment.body) + setMode('edit') + } else if (id === 'delete') setMode('delete') + else { + const removed = actions.records?.removeRecord(thread.key) ?? null + if (removed === null) setError(t('review.saveFailed')) + else actions.onRemoved?.(removed) + } + } + return
+
+
+ {range} + {t(status)} + {outdated && {t('review.outdated')}} +
+ {!confirming && }
- {editing && thread.kind === 'pending' - ?