Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers

Brings master (fe45cf60271) through the parent branch. The client inline-safe
list keeps master's `plugin-market-index/source` and this branch's
`api-session-controller/client/directories`.
This commit is contained in:
LegGasai committed 2026-11-13 17:05:16 +08:00
commit 8e6fc70ea7
395 files changed
+10939 -5407

No files matched your search

@@ -9,8 +9,8 @@
en: 31fba384d90ce7d2
zh: f8b814868f3280c3
/agent-note-session-working-directory/decision:
en: 1ccc64f8c79dba10
zh: dc90337a78cf2b46
en: 02f6c3415c09566d
zh: 3b19b5e011db0a00
/agent-note-session-working-directory/alternatives-considered:
en: f0995feb9b6bcce8
zh: 97417085fd17f70f
@@ -10,7 +10,7 @@ A fixed Session creation directory cannot represent a task that changes checkout
## Decision
`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `working-directory/change`; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available.
`dsh-working-directory` owns one logged effective directory per Session. Its projection initializes from the immutable original project and folds `workspace-root/change` and stored `working-directory/change` events; consumers read that owner instead of deriving execution paths from the header or sandbox root. Directory changes validate through the filesystem provider, serialize within the Session, and publish only after the new directory is available.
Only Host operations change the directory: worktree creation and exit, the forge panel, SDK requests, and child startup call the service. The [workspace-root note](2026-11-03-session-workspace-root.md) removed the model-facing `working_directory` tool, records each change as `workspace-root/change`, and adds the workspace root on top of this owner.
@@ -10,7 +10,7 @@ Status: implemented
## Decision
`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `working-directory/change`;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。
`dsh-working-directory` 拥有每个 Session 的一个日志化有效目录。投影从不可变的原始项目初始化,并折叠 `workspace-root/change` 与已存储的 `working-directory/change` 事件;消费者读取该服务,而不是从 header 或沙箱根目录派生执行路径。目录变更通过文件系统 provider 验证,在 Session 内串行执行,并只在新目录可用后发布。
只有 Host 操作改变目录:工作树的创建与退出、forge 面板、SDK 请求和子代理启动调用该服务。[工作区根记录](2026-11-03-session-workspace-root.zh.md)移除了面向模型的 `working_directory` 工具,把每次变更记录为 `workspace-root/change`,并在该服务之上增加工作区根。
@@ -30,8 +30,8 @@
en: 99ee505e82fa9c7c
zh: 448bc0e160424cbf
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/consequences:
en: 53d72faa09e78410
zh: a5224e4662a4846b
en: ed424571c81bcb91
zh: 9b79bf03741c1c21
/agent-note-boot-the-preview-worker-from-the-shipped-profile-and-fetch-lazy-chunks-on-demand/testing:
en: 532918df1acd147d
zh: e476c090d183d0a4
@@ -81,7 +81,7 @@ The Worker's structural stubs throw errors carrying `ERR_FEATURE_UNAVAILABLE_ON_
## Consequences
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page and Settings → Built-in plugins list every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
The Preview boots the composition the served Web deployment boots. With no bundle enabled, the Worker composition differs from the served Web composition only by the jsonl platform override, and enabling any bundle skips no patch. The Plugins page lists every `OPTIONAL_BUNDLES` entry with its title and icon and no metadata error. Switching each of the 11 optional bundles on and then off returns `applied` both times; after enabling, every enabled row it changes is active, and after disabling, the plugin list returns to its prior rows. Enabling session-titles disables `@deepseek-ai/dsh-session-title-first-prompt-llm` (row `session-title-llm`) and enables `@deepseek-ai/dsh-session-title-all-prompts-llm`, as in the served Web deployment; enabling inspector-profile runs Session Inspector and starts the NodeJS Inspector degraded. Degradation requires `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`, so a served `dsh web` runs the full Inspector.
Size (MiB, measured): the base image is 9.20 (12.79 with pack-time composition and eager chunks, −28%) including 11 optional bundles, plus 5 lazy tar archives totaling 4.45 (pdf 2.88, excel 1.39, terminal 0.13, frontmatter 0.05, Inspector bottom panel 0.00). The base image contains no lazily loaded chunk, and the page fetches an archive only when it requests the chunk.
@@ -81,7 +81,7 @@ Worker 的结构化 stub 抛出带 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 的错
## 后果
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页和“设置 → 内置插件”列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
Preview 启动的组合与正式 Web 相同。不开 bundle 时,Worker 组合与正式 Web 只差 jsonl 的平台覆盖;开任一 bundle 都没有被跳过的补丁。插件页列出全部 `OPTIONAL_BUNDLES`,每个都显示标题和图标,没有元信息错误。11 个 optional bundle 逐个开启再关闭,两次都返回 `applied`;开启后它改动的每个启用行都是 active,关闭后插件列表恢复原样。启用 session-titles 会禁用 `@deepseek-ai/dsh-session-title-first-prompt-llm`(行 `session-title-llm`)并启用 `@deepseek-ai/dsh-session-title-all-prompts-llm`,与正式 Web 一致;启用 inspector-profile 后 Session Inspector 运行,NodeJS Inspector 降级启动。降级以 `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM` 为前提,所以正常 `dsh web` 运行完整的 Inspector。
体积(MiB,实测):基础镜像 9.20(打包期组合且 chunk 随启动下载时为 12.79,−28%),含 11 个 optional bundle;另有 5 个 lazy tar 共 4.45(pdf 2.88、excel 1.39、terminal 0.13、frontmatter 0.05、inspector 底部面板 0.00)。基础镜像不含懒加载 chunk,页面请求 chunk 时才拉取对应 archive。
@@ -18,8 +18,8 @@
en: 16c4ee08b65ead23
zh: df80d6e49982615b
/agent-note-parallel-tool-call-execution-by-per-call-safety/configuration-and-declarations:
en: 082e5a02b092b656
zh: ca674a08323d8cc1
en: 5ef62a9b07a857eb
zh: 931f648655a0cb34
/agent-note-parallel-tool-call-execution-by-per-call-safety/verification:
en: 20d0e1724ebc1247
zh: baa89694cea135c8
@@ -62,7 +62,7 @@ Any shared state touched during execution must be concurrency-safe. This include
The shipped declarations are conservative. Web search, web fetch, filesystem read, glob, grep, the session-query trace/read tools, and subagent delegation opt in — delegation because a child works in its own session and its run never mutates the parent session, with sibling workspace coordination owned by the model ([parallel subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md)). Read-only queries also opt in: the background job list, the subagent tree and model listings, scheduled task and Team task reads, Cordis Inspect queries, and MCP resource reads. Filesystem writes and edits, bash tools, `job_output` because it consumes a read cursor, the session-query search tools, workflow, user interaction, todo mutation, PTC mode, and Cordis mutation tools remain exclusive. Bash has no proven input-sensitive classifier and remains exclusive. Read-only `lsp` stays exclusive because its language-server pool already serializes queries per workspace, so overlap would gain nothing, and the goal tools stay exclusive under the [goal tools Agent Note](2026-07-19-model-facing-goal-tools.md).
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `working-directory/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session.
Filesystem read relies on a narrow recorder exception: its synchronous observation updates may settle out of order, but write and edit re-check the observed version before mutation, so stale state only produces `FS_STALE_VERSION`. Filesystem read, glob, and grep also share a working-directory recovery exception: when the Session's recorded directory is unset or missing, the body's `ctx.workingDirectory.ensure()` appends `workspace-root/change` and, when it restores a missing directory, injects a model-visible notice; the working-directory service serializes that recovery per Session.
## Verification
@@ -62,7 +62,7 @@ Status: implemented
当前实现中的声明保持保守。Web 搜索、Web 获取、文件系统读取、glob、grep、会话查询的 trace/read 工具和 subagent 委派选择并行;委派之所以并行,是因为子 agent 在自己的会话中工作,其运行绝不变更父会话,并列委派间的工作区协调由模型负责([并行 subagent Agent Note](../../archived/feature/2026-08-09-parallel-subagent-delegations.md))。只读查询也选择并行:后台任务列表、subagent 树与模型列表、定时任务与 Team 任务读取、Cordis Inspect 查询以及 MCP 资源读取。文件系统写入与编辑、bash 工具、`job_output`(因为它会消费读取游标)、会话查询的 search 工具、工作流、用户交互、todo 变更、PTC mode 以及 Cordis 变更工具仍按独占方式执行。Bash 没有已证明的输入敏感分类器,因此仍按独占方式执行。只读的 `lsp` 仍按独占方式执行,因为其语言服务器池已按工作区串行化查询,重叠执行不会带来收益;goal 工具依照 [goal 工具 Agent Note](2026-07-19-model-facing-goal-tools.zh.md) 仍按独占方式执行。
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `working-directory/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。
文件系统读取依赖一个范围很窄的记录器例外:其同步观察更新可以不按顺序结算,但写入和编辑在变更前会重新检查已观察的版本,因此陈旧状态只会导致 `FS_STALE_VERSION`。文件系统读取、glob 和 grep 还共享一个工作目录恢复例外:当会话记录的目录未设置或不存在时,工具主体中的 `ctx.workingDirectory.ensure()` 会追加 `workspace-root/change`,并在恢复不存在的目录时注入一条模型可见的通知;工作目录服务按会话串行化该恢复过程。
## 验证
@@ -9,8 +9,8 @@
en: 344bcc7e9825bbc8
zh: c1d0f4b54f5b3786
/agent-note-change-request-panel-and-worktree-sessions/decision:
en: 4695a1e4f8aa7a25
zh: e17be0e36ea3eaa3
en: cb337f04d0fe41b5
zh: d9dc249507c419b6
/agent-note-change-request-panel-and-worktree-sessions/deferred:
en: 32ef8af85f4d2f66
zh: b82b67f94346399e
@@ -14,7 +14,7 @@ English | [中文](2026-10-09-forge-panel.zh.md)
Review and worktree controls serve one code-change workflow. One Plugins entry lets users enable that workflow without having to distinguish the underlying package split. Packages and the two worktree services remain independent so each owns its before-Session or in-conversation creation flow.
The Remote inspects the checkout through the Session's subprocess provider under its [resolved permissions and query restrictions](../bug-fix/2026-10-28-forge-git-session-permissions.md), so it reads what the Session's commands see. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `working-directory/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun.
The Remote inspects the checkout through the Session's subprocess provider under its [resolved permissions and query restrictions](../bug-fix/2026-10-28-forge-git-session-permissions.md), so it reads what the Session's commands see. Inspection reads the top-level, Git, and common Git directories, the branch or the abbreviated HEAD commit, the upstream, the remotes, and the size of the branch's changes against its fork point. It runs when a Session is followed, after each `workspace-root/change`, `tool/result`, and `sandbox/mode` event, and on refresh, one at a time with one trailing rerun.
Status polling follows panel subscriptions: a Session's bindings are watched only while one of its surfaces is mounted, and the registry stops polling change requests nobody watches. Each card keeps the last snapshot a poll returned, so a transient failure keeps the title and number visible. A Session's only open change request starts expanded, and with several every card starts collapsed; the user's first toggle replaces this default.
@@ -14,7 +14,7 @@ Status: implemented
评审与工作树控件服务于同一个代码修改流程。统一插件入口让用户可以一次启用这些能力,无需根据底层包的拆分判断应该开启哪张卡片。包与两套工作树服务仍保持独立,分别负责会话开始前和对话中创建工作树的流程。
Remote 通过 Session 的子进程提供方,按其[解析出的权限与查询限制](../bug-fix/2026-10-28-forge-git-session-permissions.zh.md)检查检出,因此它读到的与 Session 命令看到的相同。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。
Remote 通过 Session 的子进程提供方,按其[解析出的权限与查询限制](../bug-fix/2026-10-28-forge-git-session-permissions.zh.md)检查检出,因此它读到的与 Session 命令看到的相同。检查读取顶层目录、Git 目录与公共 Git 目录、分支或缩写的 HEAD 提交、上游与远端,以及分支相对于其分叉点的变更规模。它在 Session 被关注时、每个 `workspace-root/change`、`tool/result` 与 `sandbox/mode` 事件之后以及刷新时运行,一次只运行一个,最多再追加一次。
状态轮询跟随面板订阅:只有该 Session 的某个界面挂载时才监听其绑定,注册表停止轮询无人监听的变更请求。每张卡片保留最近一次轮询得到的快照,因此短暂的失败不会让标题与编号消失。Session 只有一个打开的变更请求时,它的卡片默认展开;有多个时全部折叠;用户第一次展开或收起卡片后,以用户的选择为准。
@@ -15,5 +15,5 @@
en: 1e2239783738cec2
zh: 5f248eee47de376e
/agent-note-session-change-request-bindings/consequences:
en: a2960e50ec52c9b6
zh: fd23f4fe1137787d
en: 2786b1dffa995c14
zh: c124420915da5aae
@@ -30,4 +30,4 @@ After each push result, and when a caller such as the forge panel reports the br
## Consequences
Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract without changing the binding rules or the polling. The host needs `gh` signed in for each GitHub host.
Bindings appear without model cooperation for the common `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` flows and add no model tokens. Commands run through scripts, aliases, or other command-line tools are not recognized, and a change request opened elsewhere for a branch appears only after another push, another report of that branch, or a `track`. Another provider adds its own access and URL forms behind the same provider contract and registers its CLI's commands as a [command rule](2026-11-11-forge-provider-command-rules.md), without changing the polling. The host needs `gh` signed in for each GitHub host.
@@ -30,4 +30,4 @@ Status: implemented
## Consequences
在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,无需改变绑定规则或轮询。宿主需要为每个 GitHub 主机登录 `gh`。
在常见的 `gh pr create`、`gh pr view`、`gh pr edit`、`gh pr checkout` 与 `git push` 流程中,绑定无需模型配合即可出现,且不增加模型 token。通过脚本、别名或其他命令行工具运行的命令无法识别;在别处为某个分支打开的变更请求,要等到下一次推送、再次报告该分支或 `track` 之后才会出现。新的提供方在同一提供方契约之后加入自己的访问方式与 URL 形式,并把其 CLI 的命令注册为[命令规则](2026-11-11-forge-provider-command-rules.zh.md),无需改变轮询。宿主需要为每个 GitHub 主机登录 `gh`。
@@ -9,8 +9,8 @@
en: 07ba0c3bf73a2446
zh: 2413783a6697133e
/agent-note-forge-state-in-the-session-list/decision:
en: e1d03cf4e1afd5aa
zh: b2386cb7c17c58dd
en: 51fc671a0c3e682e
zh: cec607f46e7dc4b8
/agent-note-forge-state-in-the-session-list/alternatives-considered:
en: 3b08440ee2bf7809
zh: a90e3fcb89cf3f74
@@ -12,7 +12,7 @@ The [forge panel](2026-10-09-forge-panel.md) named a Session's branch in a chip
The chip beside the Session title is gone, and the tab's first row names the branch. A Session row shows, after its time, a branch glyph while the Session works in the worktree the panel created for it, and the glyph of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. An open change request's glyph keeps the row's subdued color with a dot for its checks; merged and closed ones keep their state colors. The row's hover card section names the worktree branch and what it started from, then up to three change requests with their state and checks, and how many more there are.
Log facts reach the list as projection client views, which the Session summary carries. The `forgeWorktree` projection also records the Session's directory from its header and each `working-directory/change`, and its view is the created worktree while that directory is the worktree or lies below it, else null. The `forgeChangeRequests` view lists the bindings without status, as the [binding decision](2026-10-09-session-change-request-bindings.md) intended. The projection cache keeps both for Sessions that are not loaded.
Log facts reach the list as projection client views, which the Session summary carries. The `forgeWorktree` projection also records the Session's directory from its header and each `workspace-root/change` or `working-directory/change`, and its view is the created worktree while that directory is the worktree or lies below it, else null. The `forgeChangeRequests` view lists the bindings without status, as the [binding decision](2026-10-09-session-change-request-bindings.md) intended. The projection cache keeps both for Sessions that are not loaded.
Polled states reach the list through the `forgePanel.changeRequestStates` stream. One Host run serves every stream and stops with the last one. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of loaded Sessions from `ctx.forgeSession` and those of other Sessions from their cached summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through the shared `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. Every changed state is stored in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL, so a restart shows the last known states before the next poll, and unbound stored states are dropped only when every listed Session has known bindings. A stream sends a `baseline` of the states its caller may read, then `changed` frames, filtered through Remote access.
@@ -12,7 +12,7 @@ Status: implemented
Session 标题旁的标签已移除,由标签页顶部一行写出分支。Session 在面板为它创建的 worktree 中工作时,会话行在时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,并用圆点标出检查;已合并与已关闭的保留各自的状态颜色。会话行悬浮卡片中的部分写出 worktree 分支及其起点,再列出最多三个变更请求的状态与检查,并说明还有多少个。
日志事实经投影的客户端视图进入列表,由 Session 摘要携带。`forgeWorktree` 投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;该目录就是所创建的 worktree 或位于其下时,视图为该 worktree,否则为 null。`forgeChangeRequests` 视图列出绑定但不含状态,与[绑定决策](2026-10-09-session-change-request-bindings.zh.md)的设想一致。投影缓存为未加载的 Session 保留这两项。
日志事实经投影的客户端视图进入列表,由 Session 摘要携带。`forgeWorktree` 投影还从 Session 头部与每个 `workspace-root/change` 或 `working-directory/change` 记录 Session 的目录;该目录就是所创建的 worktree 或位于其下时,视图为该 worktree,否则为 null。`forgeChangeRequests` 视图列出绑定但不含状态,与[绑定决策](2026-10-09-session-change-request-bindings.zh.md)的设想一致。投影缓存为未加载的 Session 保留这两项。
轮询到的状态经 `forgePanel.changeRequestStates` 流进入列表。宿主用一次运行服务所有流,最后一条流结束时运行停止。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的摘要;它跟随已加载 Session 的绑定变化,并经共享的 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,因此重启后在下次轮询之前就能显示最近已知的状态;仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态。每条流先发送调用方可读状态的 `baseline`,之后发送 `changed` 帧,均经 Remote 访问控制过滤。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-11-11-forge-provider-command-rules.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-provider-command-rules.md
/agent-note-forge-provider-command-rules:
en: 1b602c42430a77b4
zh: 8109a6a56901fb89
/agent-note-forge-provider-command-rules/problem:
en: 29def264f0ee5401
zh: 829cdb87861757f5
/agent-note-forge-provider-command-rules/decision:
en: 17e84e777b0d7380
zh: 2cc4720c9437a839
/agent-note-forge-provider-command-rules/alternatives-considered:
en: a5bdd96f8e814246
zh: 29a4f0026cd9abaf
/agent-note-forge-provider-command-rules/consequences:
en: 506047cfeb4645d3
zh: b587240a69b46b8a
@@ -0,0 +1,33 @@
# Agent Note: Forge provider command rules
Status: implemented
English | [中文](2026-11-11-forge-provider-command-rules.zh.md)
## Problem
[Session change request bindings](2026-10-09-session-change-request-bindings.md) recognized `gh` commands inside forge-session, so every new code host's CLI, such as `glab`, meant editing forge-session, and numeric selectors such as `glab mr view 7 -R group/app` need knowledge of that CLI's options and URL forms. Recognition feeds a Session projection, so it must stay deterministic for replay and checkpoints, and a provider enabled after a Session ran its commands should still bind them.
## Decision
Each provider registers a declarative `ForgeCommandRule` with `ctx.forgeSession.registerCommands`: its executable, creation subcommands, reference and raw API request subcommand groups with their own options, change request page path, JSON URL members, and a pure `select` that maps one parsed command to a URL or a read-only lookup. An API request, such as `glab api`, binds only the change request its path names, since its output can list many. [forge-github](../../../../packages/experimental/forge-github/src/commands.ts) registers `gh` and [forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) registers `glab`. forge-session keeps the shared parts: the literal shell tokenizer, option parsing, output reading, lookups in the call's shell, and the projection.
The `forgeChangeRequests` state version derives from the recognized rules, `5 × 2^32` plus a hash of the sorted `id@version` pairs, so a checkpoint folded under another rule set is discarded and the log folds again. A registration that changes the set releases the projection and registers it at the new version, then refreshes watchers; the released handle stays readable during the swap. Ending a registration keeps its rule recognized until the service restarts or another rule replaces its id or executable.
## Alternatives considered
**Recognition per CLI inside forge-session.** Every provider change would edit forge-session, and its tests would own other CLIs' option sets.
**Rules on `ForgeProvider`.** forge-session could read rules from `ctx.forge`, but the forge Service Definition would carry a field that only one Consumer uses.
**Rules for later events only.** Folding only events after a registration skips the commands a Session ran before the provider loaded.
**A fixed state version.** Folding with whatever rules are loaded breaks the rule that a restored checkpoint plus suffix replay equals full replay once the rules change.
**Rebuilding on unregistration.** Providers unload before forge-session at shutdown, so every exit would checkpoint a smaller rule set and every start would refold every Session.
**Option parsing in each provider.** The token walk would repeat in every provider.
## Consequences
A new provider rule or a raised rule version refolds every Session once; until a Session is opened again, the Session list shows no cached bindings for it, and re-registration emits no projection change event, so an open Session's summary shows the refolded bindings after a later event. Providers own their rule versions. Unloading a provider at runtime leaves its commands recognized until restart, though they run no lookup; starting without it removes the bindings that only its commands made, while binding records stay. Each start registers the projection without rules and once more after the providers register theirs. The [forge-session README](../../../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition rules.
@@ -0,0 +1,33 @@
# Agent Note: Forge 提供方命令规则
Status: implemented
[English](2026-11-11-forge-provider-command-rules.md) | 中文
## Problem
[Session 变更请求绑定](2026-10-09-session-change-request-bindings.zh.md)在 forge-session 内部识别 `gh` 命令,因此每接入一个代码托管平台的 CLI(如 `glab`)都要修改 forge-session;而 `glab mr view 7 -R group/app` 这类数字编号需要了解该 CLI 的选项与 URL 形式。识别结果供 Session 投影使用,因此必须在重放与检查点下保持确定;提供方在 Session 执行过命令之后才启用时,也应能绑定这些命令。
## Decision
每个提供方通过 `ctx.forgeSession.registerCommands` 注册一条声明式的 `ForgeCommandRule`:其可执行文件、创建子命令、各带选项的引用子命令组与原始 API 请求子命令组、变更请求页面路径、JSON URL 成员,以及一个纯函数 `select`,把一条解析后的命令映射为 URL 或只读查询。API 请求(如 `glab api`)只绑定其路径指向的变更请求,因为其输出可能列出许多变更请求。[forge-github](../../../../packages/experimental/forge-github/src/commands.ts) 注册 `gh`,[forge-gitlab](../../../../packages/experimental/forge-gitlab/src/commands.ts) 注册 `glab`。forge-session 保留共用部分:字面量 shell 拆词、选项解析、输出读取、在调用所在 shell 中的查询,以及投影。
`forgeChangeRequests` 的状态版本由已识别规则派生,即 `5 × 2^32` 加上排序后 `id@version` 对的哈希,因此按其他规则集折叠的检查点会被丢弃,日志重新折叠。改变规则集的注册会释放投影并以新版本重新注册,再刷新监听方;切换期间已释放的句柄仍可读取。注册结束后,其规则仍被识别,直到服务重启或另一条规则替换其 id 或可执行文件。
## Alternatives considered
**在 forge-session 内按 CLI 识别。**每次提供方变化都要修改 forge-session,其测试还要承担其他 CLI 的选项集。
**把规则放在 `ForgeProvider` 上。**forge-session 可以从 `ctx.forge` 读取规则,但 forge 的 Service Definition 就会带上只有一个 Consumer 使用的字段。
**规则只作用于之后的事件。**只折叠注册之后的事件,会漏掉 Session 在提供方加载之前执行的命令。
**固定的状态版本。**按当前加载的规则折叠,一旦规则变化,就违背了"恢复的检查点加后缀重放等于完整重放"这一规则。
**注销时重建。**关闭时提供方先于 forge-session 卸载,因此每次退出都会按更小的规则集写入检查点,每次启动都要重新折叠所有 Session。
**由各提供方解析选项。**逐词解析会在每个提供方中重复。
## Consequences
新增提供方规则或提高规则版本,会使每个 Session 重新折叠一次;Session 再次打开之前,Session 列表不显示它的缓存绑定;重新注册不发出投影变化事件,因此已打开 Session 的摘要要在后续事件之后才显示重新折叠的绑定。规则版本由提供方负责。运行时卸载提供方后,其命令仍被识别,直到重启,但不再执行反查;不加载该提供方启动时,只由其命令产生的绑定会消失,绑定记录保留。每次启动时投影先在没有规则的情况下注册,提供方注册规则后再注册一次。识别规则见 [forge-session README](../../../../packages/experimental/forge-session/README.zh.md#use-this-package)。
+35 -22
View File
@@ -17,13 +17,25 @@ const SESSION_ACTION_EXPECTED = join(EXPECTED, 'session-actions.expected.md')
const SESSION_SEED = fileURLToPath(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url))
const SESSION_TITLE = 'Session action extension'
async function openInventory(page: Page, url: string) {
/** Load the page on the Plugins page, which reports this page's client synchronization. */
async function openPlugins(page: Page, url: string) {
await page.goto(url, { waitUntil: 'load' })
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
await page.locator('[data-plugin-body]').waitFor({ timeout: 10_000 })
}
/** Open the Models settings page's add-provider card and return its API key field, a page-local draft. */
async function openDraft(page: Page) {
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '内置插件', exact: true }).click()
await dialog.getByRole('searchbox', { name: '搜索插件' }).waitFor()
return dialog
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const add = dialog.getByRole('button', { name: '添加模型提供商', exact: true })
await expect.poll(() => add.isEnabled(), { timeout: 10_000 }).toBe(true)
await add.click()
await dialog.getByLabel('提供商', { exact: true }).selectOption('minimax-cn')
const draft = dialog.getByRole('textbox', { name: 'API 密钥', exact: true })
await draft.waitFor({ timeout: 10_000 })
return draft
}
it('keeps ordered legacy Session menu rows before Archive and removes them with their fiber', async () => {
@@ -237,8 +249,9 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
const other = await otherContext.newPage()
const consoles = [watchConsole(page), watchConsole(other)]
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-live'))
await openInventory(page, scaffold.authenticatedUrl)
const otherInventory = await openInventory(other, scaffold.authenticatedUrl)
await openPlugins(page, scaffold.authenticatedUrl)
await openPlugins(other, scaffold.authenticatedUrl)
const draft = await openDraft(other)
let entryId: string | undefined
const toggle = async () => {
if (entryId === undefined) entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' })
@@ -265,9 +278,8 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
}
await compareOrRefreshGolden(join(EXPECTED, 'enabled.expected.md'), await captureStableAria(page, '[data-live-client]', scaffold.workspaceCwd), webSnapshotMode())
// The inventory filter is page-owned state that live composition must preserve.
const draft = otherInventory.getByRole('searchbox', { name: '搜索插件' })
await draft.fill('unfinished-filter')
// An unsaved Settings field is page-owned state that live composition must preserve.
await draft.fill('unfinished-draft')
await toggle()
for (const target of [page, other]) {
await expect.poll(() => live(target).count()).toBe(0)
@@ -276,7 +288,7 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
expect((await dataset(target)).liveHits).toBe('1')
expect(await target.locator('style[data-plugin="@fixture/live-client"]').count()).toBe(0)
}
expect(await draft.inputValue()).toBe('unfinished-filter')
expect(await draft.inputValue()).toBe('unfinished-draft')
await toggle()
for (const target of [page, other]) {
await live(target).waitFor()
@@ -299,7 +311,7 @@ it('synchronizes two pages, disposes effects and restores an offline page from t
expect(await live(other).count()).toBe(1)
await otherContext.setOffline(false)
await expect.poll(() => live(other).count(), { timeout: 20_000 }).toBe(0)
expect(await draft.inputValue()).toBe('unfinished-filter')
expect(await draft.inputValue()).toBe('unfinished-draft')
expect(navigations).toBe(0)
expect(scaffold.ctx.loader.ctx.fiber.uid).toBe(host)
for (const console of consoles) expect(console.pageErrors).toEqual([])
@@ -315,7 +327,7 @@ it('keeps a failed client download local and retries without changing Host enabl
try {
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-live-retry'))
await openInventory(page, scaffold.authenticatedUrl)
await openPlugins(page, scaffold.authenticatedUrl)
const bundle = (url: URL) => url.pathname.startsWith('/plugins/') && url.search.includes('@fixture/live-client/client.js')
await page.route(bundle, route => route.abort())
const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' })
@@ -352,9 +364,9 @@ it('recovers an uncreated client entry with rebuilt factory code without navigat
try {
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-factory-rebuild'))
const inventory = await openInventory(page, scaffold.authenticatedUrl)
const draft = inventory.getByRole('searchbox', { name: '搜索插件' })
await draft.fill('unfinished-filter')
await openPlugins(page, scaffold.authenticatedUrl)
const draft = await openDraft(page)
await draft.fill('unfinished-draft')
let navigations = 0
page.on('framenavigated', () => { navigations++ })
const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' })
@@ -366,7 +378,7 @@ it('recovers an uncreated client entry with rebuilt factory code without navigat
await page.getByText('动态插件 r1 已启用', { exact: true }).waitFor()
await expect.poll(() => failure.count()).toBe(0)
await compareOrRefreshGolden(join(EXPECTED, 'recovered.expected.md'), await captureStableAria(page, '[data-live-client]', scaffold.workspaceCwd), webSnapshotMode())
expect(await draft.inputValue()).toBe('unfinished-filter')
expect(await draft.inputValue()).toBe('unfinished-draft')
expect(await page.locator('style[data-plugin="@fixture/live-client"]').count()).toBe(1)
expect(await page.evaluate(() => document.documentElement.dataset.liveMounts)).toBe('1')
expect(scaffold.ctx.loader.resolve(entryId).fiber?.state).toBe(2)
@@ -386,9 +398,9 @@ it('reports bootstrap rebuilds without remounting the settings page or navigatin
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
const console = watchConsole(page)
onTestFailed(() => saveFailureShot(page, 'web-e2e-client-bootstrap-rebuild'))
const inventory = await openInventory(page, scaffold.authenticatedUrl)
const draft = inventory.getByRole('searchbox', { name: '搜索插件' })
await draft.fill('unfinished-filter')
await openPlugins(page, scaffold.authenticatedUrl)
const draft = await openDraft(page)
await draft.fill('unfinished-draft')
const originalInput = await draft.elementHandle()
let navigations = 0
page.on('framenavigated', () => { navigations++ })
@@ -399,11 +411,12 @@ it('reports bootstrap rebuilds without remounting the settings page or navigatin
scaffold.ctx.clientModules.rebuilt('@deepseek-ai/dsh-client-modules')
const failure = page.locator('[data-client-sync-failure]')
await failure.getByText(/replacing bootstrap module .* requires a page reload/).waitFor()
await failure.getByRole('button', { name: '重试本页面同步' }).click()
// The Settings dialog holding the draft covers the Plugins page, so the retry is dispatched to its button.
await failure.getByRole('button', { name: '重试本页面同步' }).dispatchEvent('click')
await failure.getByText(/replacing bootstrap module .* requires a page reload/).waitFor()
await compareOrRefreshGolden(join(EXPECTED, 'bootstrap-rebuild.expected.md'), await captureStableAria(page, '[data-client-sync-failure]', scaffold.workspaceCwd), webSnapshotMode())
expect(await originalInput!.evaluate(input => input.isConnected)).toBe(true)
expect(await draft.inputValue()).toBe('unfinished-filter')
expect(await draft.inputValue()).toBe('unfinished-draft')
expect(scaffold.ctx.loader.ctx.fiber.uid).toBe(host)
expect(navigations).toBe(0)
expect(console.pageErrors).toEqual([])
@@ -421,7 +434,7 @@ it('removes the client UI and resources while Host cleanup is still pending', as
const browser = await chromium.launch()
try {
const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE })
await openInventory(page, scaffold.authenticatedUrl)
await openPlugins(page, scaffold.authenticatedUrl)
let navigations = 0
page.on('framenavigated', () => { navigations++ })
const entryId = await scaffold.ctx.loader.create({ name: '@fixture/live-client' })
+8 -2
View File
@@ -112,7 +112,8 @@ it.skipIf(process.platform !== 'darwin').each([
expect(await card.getByText('实验性', { exact: true }).count()).toBe(1)
expect(await card.textContent()).not.toContain('将 PTC 模式改为可持久化')
expect(await card.textContent()).not.toContain('请切换到 PTC 模式')
expect(await card.textContent()).toContain('通过 npm 安装 DSH 的 Windows 用户需要单独配置 helper')
expect(await card.textContent()).toContain('允许 agent 直接操作电脑上的应用程序。')
expect(await card.textContent()).not.toContain('helper')
expect(await card.textContent()).not.toContain('Swift')
const description = await card.getByRole('button', { name: '查看 Computer Use', exact: true }).evaluate((button) => {
const element = document.getElementById(button.getAttribute('aria-describedby')!)!
@@ -175,7 +176,12 @@ it.skipIf(process.platform !== 'darwin').each([
expect(scaffold.ctx.agentPresets.composedPreset(fresh.ctx)).toBe('ptc')
expect(scaffold.ctx.tools.schemas(fresh).some(tool => tool.name === 'cua')).toBe(true)
await card.getByRole('button', { name: '查看 Computer Use', exact: true }).click()
await plugins.locator('[data-detail-document]').getByText('helperPath', { exact: true }).waitFor()
const detail = plugins.locator('[data-detail-document]')
await detail.getByRole('img', { name: '将会议要点填入备忘录的指令和输入结果' }).waitFor()
const guidance = plugins.locator('[data-cua-guidance]')
await guidance.getByText(/请谨慎在生产环境中使用/).waitFor()
expect(await guidance.textContent()).not.toContain('helperPath')
expect(await detail.textContent()).not.toContain('PTC')
toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 Computer Use', exact: true })
const persistent = page.getByRole('group', { name: 'PTC 执行方式', exact: true })
if (!codingTools) {
+38
View File
@@ -333,3 +333,41 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
await diagnostic.waitFor({ state: 'hidden' })
expect(tripwire.pageErrors).toEqual([])
})
it.skipIf(process.platform !== 'darwin' && process.platform !== 'win32')('shows Windows setup when the helper is missing', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cua-missing-helper-'))
const resources: { scaffold?: WebScaffold; browser?: Browser } = {}
onTestFinished(async () => {
try { await resources.browser?.close() } finally {
try { await resources.scaffold?.close() } finally { await rm(root, { recursive: true, force: true }) }
}
})
const patch = join(root, 'missing-helper.yml')
const row = process.platform === 'win32' ? 'cua-windows' : 'cua-macos'
await writeFile(patch, JSON.stringify([{ id: row, config: { helperPath: join(root, 'missing.exe') } }]))
const scaffold = resources.scaffold = await launchWebScaffold({
profile: { packages: [{ dir: bundle, enabled: true }] }, extraOverlayPath: patch,
})
if (process.platform === 'darwin') {
// The Host inventory reads this Loader flag; only the platform-specific input is substituted on macOS.
const windows = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'cua-windows')
if (!windows) throw new Error('CUA bundle has no Windows provider row')
vi.spyOn(windows, 'disabled', 'get').mockReturnValue(false)
}
const browser = resources.browser = await chromium.launch()
const page = await newEnglishPage(browser)
await page.goto(scaffold.authenticatedUrl)
await page.getByRole('button', { name: 'Plugins', exact: true }).click()
await page.getByRole('button', { name: 'View Computer use', exact: true }).click()
const panel = page.locator('[data-cua-settings]')
const guidance = panel.locator('[data-cua-guidance]')
await guidance.getByText(/pnpm run build:native:x64/).waitFor()
await guidance.getByText(/helperPath/).waitFor()
const preview = page.locator('[data-detail-document] img')
await preview.evaluate(async (image) => { await (image as HTMLImageElement).decode() })
const firstSetting = panel.getByRole('group', { name: 'Default mode for new sessions', exact: true })
const previewBox = await preview.boundingBox(), guidanceBox = await guidance.boundingBox(), settingBox = await firstSetting.boundingBox()
expect(previewBox!.y + previewBox!.height).toBeLessThanOrEqual(guidanceBox!.y)
expect(guidanceBox!.y + guidanceBox!.height).toBeLessThanOrEqual(settingBox!.y)
expect(await panel.getByRole('button', { name: 'Request permission', exact: true }).count()).toBe(0)
})
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -1,4 +1,5 @@
- region "Authorize computer use":
- paragraph: Computer use is an experimental preview. The agent may click the wrong button or type in the wrong window. Use caution in production environments. We recommend native PTC mode so the agent can operate apps and call other tools in the same program.
- heading "Authorize computer use" [level=3]
- group "Default mode for new sessions":
- strong: Default mode for new sessions
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "General"
- button "Models"
- button "Built-in plugins"
- button "Plugins"
- button "Agent presets"
- button "Open configuration file"
- button "Close"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -39,7 +39,7 @@
- switch "启用 自动授权审查"
- listitem:
- button "查看 变更请求与工作树": 变更请求与工作树
- text: 实验性 在会话侧栏集中跟踪关联的 GitHub PR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。
- text: 实验性 在会话侧栏集中跟踪关联的代码变更请求,支持 GitHub PR 以及 GitLab MR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。GitLab 合并请求需要本机安装 glab 并登录。
- status
- switch "启用 变更请求与工作树"
- heading "已安装插件" [level=3]
@@ -5,12 +5,12 @@
- text: v{{version}} 实验性
- paragraph:
- code: "@deepseek-ai/dsh-experimental-forge-bundle"
- paragraph: 在会话侧栏集中跟踪关联的 GitHub PR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。
- paragraph: 在会话侧栏集中跟踪关联的代码变更请求,支持 GitHub PR 以及 GitLab MR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。GitLab 合并请求需要本机安装 glab 并登录。
- region "详细介绍":
- paragraph:
- img "会话关联 GitHub PR,跟踪检查、评审与代码差异,并用工作树隔离任务改动"
- heading "包含的组件" [level=4]
- text: 共 6 个 · 6 已停用
- text: 共 7 个 · 7 已停用
- list:
- listitem:
- text: 工作树服务 创建命名的 Git 工作树,并切换当前会话的工作目录。
@@ -32,6 +32,11 @@
- code: forge-github
- code: "@deepseek-ai/dsh-experimental-forge-github"
- text: 已关闭
- listitem:
- text: GitLab 变更请求 通过宿主上的 GitLab CLI 为 forge 注册表读写 GitLab 合并请求。
- code: forge-gitlab
- code: "@deepseek-ai/dsh-forge-gitlab"
- text: 已关闭
- listitem:
- text: 会话变更请求 把变更请求绑定到创建、推送或跟踪它们的会话,并监听其状态。
- code: forge-session
@@ -39,7 +39,7 @@
- switch "启用 自动授权审查"
- listitem:
- button "查看 变更请求与工作树": 变更请求与工作树
- text: 实验性 在会话侧栏集中跟踪关联的 GitHub PR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。
- text: 实验性 在会话侧栏集中跟踪关联的代码变更请求,支持 GitHub PR 以及 GitLab MR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。GitLab 合并请求需要本机安装 glab 并登录。
- status
- switch "启用 变更请求与工作树"
- heading "已安装插件" [level=3]
@@ -39,7 +39,7 @@
- switch "启用 自动授权审查"
- listitem:
- button "查看 变更请求与工作树": 变更请求与工作树
- text: 实验性 在会话侧栏集中跟踪关联的 GitHub PR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。
- text: 实验性 在会话侧栏集中跟踪关联的代码变更请求,支持 GitHub PR 以及 GitLab MR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。GitLab 合并请求需要本机安装 glab 并登录。
- status
- switch "启用 变更请求与工作树"
- heading "已安装插件" [level=3]
@@ -2,7 +2,7 @@
Touch refresh: one refresh request; no tooltip
Touch explanation: visible within the 390px viewport
- tooltip "在这里配置官方插件,安装和管理其他插件。内置插件列表及运行状态可在「设置 → 内置插件」中查看"
- tooltip "在这里配置官方插件,安装、管理和配置其他插件。"
Explanation closes on another tap or an outside touch
Keyboard focus after touch: refresh tooltip visible
Mouse hover after touch: refresh tooltip visible
@@ -5,4 +5,6 @@
- 768px: single row; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
- 1280px: single row; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
The source dialog treats a Raw URL and an unmarked custom URL as JSON. It shows Git fields for an SSH clone address or a git+https URL. The fields fit and stay reachable at 390px and 1280px. Editing the address preserves the Git draft, and Escape closes the dialog.
At 390px, restoring the previous no-wrap layout causes horizontal overflow and fails the same layout check. Removing that override restores the controls and preserves search focus.
@@ -3,7 +3,7 @@
- navigation:
- button "General"
- button "Models"
- button "Built-in plugins"
- button "Plugins"
- button "Agent presets"
- button "Open configuration file"
- button "Close"
@@ -3,7 +3,7 @@
- navigation:
- button "General"
- button "Models"
- button "Built-in plugins"
- button "Plugins"
- button "Agent presets"
- button "Open configuration file"
- button "Close"
@@ -3,7 +3,7 @@
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "插件管理"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
@@ -1,16 +0,0 @@
- list:
- listitem:
- button "子智能体控制工具, tool-subagent-control, 已启用":
- strong: 子智能体控制工具
- text: 让 AI 向子智能体发送消息或中断其运行。
- code: tool-subagent-control
- listitem:
- button "子智能体委派工具, tool-subagent, 已启用":
- strong: 子智能体委派工具
- text: 让 AI 将任务交给子智能体,并获取运行结果。
- code: tool-subagent
- listitem:
- button "子智能体委派工具, tool-subagent-fork, 已启用":
- strong: 子智能体委派工具
- text: 让 AI 将任务交给子智能体,并获取运行结果。
- code: tool-subagent-fork
@@ -1,5 +0,0 @@
- listitem:
- button "子智能体委派工具, tool-subagent, 已启用":
- strong: 子智能体委派工具
- text: 让 AI 将任务交给子智能体,并获取运行结果。
- code: tool-subagent
@@ -0,0 +1,16 @@
/** Test package registering its own settings page into `settings.section`. */
window.__ModuleLoader__.load({
id: '@fixture/settings-section',
factory(require) {
const React = require('react')
return {
inject: ['slots'],
apply(ctx) {
ctx.slots.inject('settings.section', () => ctx.slots.register({
name: 'settings.section', id: 'fixture-settings-section', label: 'Fixture settings',
}, () => React.createElement('section', { 'data-fixture-settings-section': '', 'aria-label': 'Fixture settings' },
React.createElement('p', null, 'Settings content from the fixture'))))
},
}
},
})
@@ -0,0 +1,4 @@
# Web e2e fixture bundle whose browser half registers a plugin settings page.
- insert:
- id: fixture-settings-section
name: '@fixture/settings-section'
@@ -0,0 +1,2 @@
/** Host companion for the plugin settings page fixture. */
export function apply() {}
@@ -0,0 +1,12 @@
{
"name": "@fixture/settings-section",
"version": "0.0.1",
"private": true,
"type": "module",
"main": "index.js",
"exports": { ".": "./index.js", "./client": "./client.js" },
"dsh": {
"bundle": { "patch": "./cordis.patch.yml" },
"client": { "platform": "web" }
}
}
+5 -5
View File
@@ -77,9 +77,9 @@ const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, 'utf8')
const save = () => { writeFileSync(statePath, JSON.stringify(state)) }
if (args[0] === 'pr' && args[1] === 'view' && args[2] === '7') {
const fields = args[args.indexOf('--json') + 1]
process.stdout.write(JSON.stringify(fields === 'url'
? { url: 'https://github.com/octo/demo/pull/7' }
: { number: 7, title: 'Add the pull request panel' }))
const url = 'https://github.com/octo/demo/pull/7'
process.stdout.write(fields !== 'url' ? JSON.stringify({ number: 7, title: 'Add the pull request panel' })
: args.includes('--jq') ? url + '\\n' : JSON.stringify({ url }))
process.exit(0)
}
if (args[0] === 'pr' && args[1] === 'ready' && args[2] === '9') {
@@ -319,7 +319,7 @@ if (args[0] === 'api' && args[1] === 'graphql') {
}).filter(thread => thread.comments.nodes.length > 0)
const pendingComments = threads.flatMap(thread => thread.comments.nodes).filter(comment => comment.state === 'PENDING').length
process.stdout.write(JSON.stringify({ data: { viewer: { login: VIEWER }, repository: { isArchived: false, viewerPermission: 'WRITE',
pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid, locked: false,
pullRequest: { id: 'pull-' + number, headRefOid: pulls[number].headRefOid, locked: false, viewerDidAuthor: false,
reviews: { nodes: current.pending === null ? [] : [{ id: current.pending.id, viewerDidAuthor: true, comments: { totalCount: pendingComments } }] },
reviewThreads: page(threads) } } } }))
process.exit(0)
@@ -733,7 +733,7 @@ async function expectNumberedReference({ scaffold, page, project, tripwire }: Pa
})
}).toEqual([{ action: 'reference', url: PULL }])
const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[])
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url'])
expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url', '--jq', '.url'])
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}
+42 -2
View File
@@ -10,13 +10,13 @@ import { fileURLToPath } from 'node:url'
import type { Browser, Locator, Page } from 'playwright'
import { chromium } from 'playwright'
import { HIDDEN_BUNDLES } from '@deepseek-ai/dsh-official-bundles'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import { afterAll, beforeAll, describe, expect, it, onTestFailed, onTestFinished } from 'vitest'
import { join } from 'node:path'
import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
import { ZH_BROWSER_LOCALE, openSettings, saveFailureShot } from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/plugin-config', import.meta.url))
const OFFICIAL_EXPECTED = join(SNAPSHOT_DIR, 'official.expected.md')
@@ -503,6 +503,46 @@ describe('web e2e: plugin configuration pages', () => {
expect(tripwire.warnings).toEqual([])
await assertFixtureInventory(SNAPSHOT_DIR, ['bundle.expected.md', 'official.expected.md', 'row.expected.md', 'subagent.expected.md', 'web-search.expected.md'])
})
})
describe('web e2e: a community plugin settings page', () => {
it('shows a settings.section entry in Settings and on its bundle row', async () => {
const scaffold = await launchWebScaffold({
profile: { packages: [{ dir: join(FIXTURE_PLUGINS, 'fixture-settings-section') }] },
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
const console = watchConsole(page)
onTestFailed(() => saveFailureShot(page, 'web-e2e-plugin-config-settings-section'))
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const panel = page.locator('[data-plugin-panel]')
await panel.getByRole('button', { name: '查看 @fixture/settings-section', exact: true }).click({ timeout: 20_000 })
const row = panel.locator('[data-plugin-row]', { hasText: 'fixture-settings-section' })
await row.waitFor({ timeout: 10_000 })
const configure = panel.getByRole('button', { name: '配置 @fixture/settings-section' })
expect(await configure.count()).toBe(0)
// Switched on, the browser half mounts and its settings page claims the row.
await panel.getByRole('switch', { name: '启用 @fixture/settings-section' }).click()
await configure.waitFor({ timeout: 30_000 })
await configure.click()
const rowPage = panel.locator('[data-plugin-row-detail="@fixture/settings-section#fixture-settings-section"]')
await rowPage.waitFor({ timeout: 10_000 })
await rowPage.getByRole('region', { name: 'Fixture settings', exact: true })
.getByText('Settings content from the fixture', { exact: true }).waitFor({ timeout: 10_000 })
// Settings keeps the same page in its navigation.
await openSettings(page, 'zh')
const dialog = page.getByRole('dialog', { name: '设置', exact: true })
await dialog.getByRole('navigation').getByRole('button', { name: 'Fixture settings', exact: true }).click()
await dialog.getByRole('region', { name: 'Fixture settings', exact: true })
.getByText('Settings content from the fixture', { exact: true }).waitFor({ timeout: 10_000 })
await page.keyboard.press('Escape')
await expect.poll(() => dialog.count(), { timeout: 5_000 }).toBe(0)
expect(console.pageErrors).toEqual([])
expect(console.warnings).toEqual([])
}, 90_000)
})
+2 -2
View File
@@ -792,14 +792,14 @@ describe('web e2e: plugin manager', () => {
await info.hover()
const hoverHelp = page.getByRole('tooltip')
await hoverHelp.waitFor()
expect(await hoverHelp.textContent()).toBe('在这里配置官方插件,安装和管理其他插件。内置插件列表及运行状态可在「设置 → 内置插件」中查看')
expect(await hoverHelp.textContent()).toBe('在这里配置官方插件,安装、管理和配置其他插件。')
await panel.getByRole('heading', { name: '插件', exact: true }).hover()
await hoverHelp.waitFor({ state: 'hidden' })
await info.focus()
await page.keyboard.press('Enter')
const help = page.getByRole('tooltip')
await help.waitFor()
expect(await help.textContent()).toContain('设置 → 内置插件')
expect(await help.textContent()).toBe('在这里配置官方插件,安装、管理和配置其他插件。')
await page.keyboard.press('Escape')
expect(await help.count()).toBe(0)
expect(await info.evaluate(element => element === document.activeElement)).toBe(true)
+47 -2
View File
@@ -1,9 +1,9 @@
/** Keyless browser geometry for the Discover toolbar against a local plugin index. */
/** Keyless browser checks for Discover against a local plugin index. */
import { once } from 'node:events'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator } from 'playwright'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it } from 'vitest'
import type {} from '@deepseek-ai/dsh-plugin-market'
import { compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts'
@@ -53,6 +53,49 @@ function validLayout(layout: Awaited<ReturnType<typeof measure>>): boolean {
&& !layout.overflow && !layout.pageOverflow && layout.focused
}
async function checkSourceForm(page: Page, toolbar: Locator): Promise<void> {
await toolbar.getByRole('button', { name: /^切换插件索引/u }).click()
await page.getByRole('menuitem', { name: '管理索引源…', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '索引源', exact: true })
const address = dialog.getByRole('textbox', { name: '源地址', exact: true })
const path = dialog.getByRole('textbox', { name: '索引文件路径', exact: true })
const ref = dialog.getByRole('textbox', { name: 'Git 引用', exact: true })
const add = dialog.getByRole('button', { name: '添加', exact: true })
await expect.poll(() => address.evaluate(element => element === document.activeElement)).toBe(true)
expect(await dialog.getByRole('combobox').count()).toBe(0)
await address.fill('https://git.example/acme/plugins')
expect(await add.isEnabled()).toBe(true)
expect(await path.count()).toBe(0)
await address.fill('https://raw.githubusercontent.com/acme/plugins/main/index.json')
expect(await add.isEnabled()).toBe(true)
expect(await path.count()).toBe(0)
await address.fill('git@github.com:acme/plugins.git')
expect(await address.evaluate(element => element === document.activeElement)).toBe(true)
await path.fill('distribution/market/catalogs/team-index.json')
await ref.fill('release/plugins')
for (const width of [390, 1280]) {
await page.setViewportSize({ width, height: 844 })
await expect.poll(() => dialog.locator('form').evaluate((form) => {
const bounds = form.getBoundingClientRect()
return Array.from(form.querySelectorAll('input, button')).every((control) => {
const rect = control.getBoundingClientRect()
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
return rect.left >= bounds.left && rect.right <= bounds.right && rect.left >= 0 && rect.right <= innerWidth
&& hit !== null && control.contains(hit)
})
})).toBe(true)
expect(await ref.evaluate(element => element === document.activeElement)).toBe(true)
}
await address.fill('https://git.example/acme/plugins')
expect(await path.count()).toBe(0)
await address.fill('git+https://git.example/acme/plugins')
expect(await path.inputValue()).toBe('distribution/market/catalogs/team-index.json')
expect(await ref.inputValue()).toBe('release/plugins')
await page.keyboard.press('Escape')
await dialog.waitFor({ state: 'hidden' })
}
it('keeps Discover controls reachable when the toolbar wraps and retains search focus across widths', async () => {
const body = await readFile(INDEX)
const source = createServer((request, response) => {
@@ -113,7 +156,9 @@ it('keeps Discover controls reachable when the toolbar wraps and retains search
}, previous)
}
await expect.poll(async () => validLayout(await measure(toolbar))).toBe(true)
await checkSourceForm(page, toolbar)
expect(consoleWatch.pageErrors).toEqual([])
facts.push('', 'The source dialog treats a Raw URL and an unmarked custom URL as JSON. It shows Git fields for an SSH clone address or a git+https URL. The fields fit and stay reachable at 390px and 1280px. Editing the address preserves the Git draft, and Escape closes the dialog.')
await compareOrRefreshGolden(EXPECTED,
`# Discover toolbar responsive layout\n\n${facts.join('\n')}\n\nAt 390px, restoring the previous no-wrap layout causes horizontal overflow and fails the same layout check. Removing that override restores the controls and preserves search focus.`,
webSnapshotMode())
@@ -189,12 +189,6 @@ it('shares settings card materials and control sizes in both palettes', async ()
await compareOrRefreshGolden(join(EXPECTED, 'account.expected.md'),
await captureStableAria(page, 'section[aria-label="账号与余额"]', scaffold.workspaceCwd), webSnapshotMode())
await dialog.getByRole('button', { name: '内置插件', exact: true }).click()
await dialog.getByRole('button', { name: /^全局/ }).click()
const plugin = dialog.locator('[data-plugin-scope="global"] [data-plugin-entry]').first()
await plugin.waitFor()
expect(await appearance(plugin)).toMatchObject(material)
await dialog.getByRole('button', { name: 'Agent 预设', exact: true }).click()
const preset = dialog.locator('li').first()
await preset.waitFor()
+26 -93
View File
@@ -24,11 +24,8 @@ import { brandString } from '@deepseek-ai/dsh-brand'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/settings-chrome', import.meta.url))
const DIALOG_EXPECTED = join(SNAPSHOT_DIR, 'dialog.expected.md')
const PLUGINS_EXPECTED = join(SNAPSHOT_DIR, 'plugins.expected.md')
const PLUGIN_INSTANCES_EXPECTED = join(SNAPSHOT_DIR, 'plugin-instances.expected.md')
// The English fallback surface: a browser naming no shipped language.
const DIALOG_EN_EXPECTED = join(SNAPSHOT_DIR, 'dialog-en.expected.md')
const PLUGIN_ROW_SELECTOR = '[data-plugin-scope="preset"] [data-plugin-entry="tool-subagent"]'
const MODE = webSnapshotMode()
const SCREENSHOTS = 'screenshots/collapse-timing-settings'
const SCREENSHOT_DIR = fileURLToPath(new URL(`../../../.artifacts/${SCREENSHOTS}`, import.meta.url))
@@ -140,84 +137,6 @@ describe('web e2e: settings modal and General preferences', () => {
await dialog.getByRole('button', { name: '模型', exact: true }).click()
await expect.poll(() => dialog.getByRole('button', { name: '模型', exact: true }).getAttribute('aria-current'), { timeout: 5_000 }).toBe('true')
expect(await dialog.getByRole('button', { name: '通用设置' }).getAttribute('aria-current')).toBeNull()
// Built-in plugins: the read-only Plugin list, a projection of the same
// assembled Loader tree, shown as the section's one page; management and
// configuration live on the sidebar's Plugins panel (its own scenario files
// drive that page over a profile runtime). Capture one stable shipped row
// rather than the whole inventory so adding an unrelated plugin does not
// rewrite this surface's golden.
await dialog.getByRole('button', { name: '内置插件', exact: true }).click()
await dialog.getByRole('heading', { name: '内置插件', exact: true }).waitFor({ timeout: 10_000 })
// The preset group starts open under its display-only switcher; the global group starts folded.
const presetSwitcher = dialog.getByRole('button', { name: '选择要查看的 Agent 预设' })
await presetSwitcher.waitFor({ timeout: 10_000 })
// The shipped default's zh display name comes from the zh dictionaries.
expect(await presetSwitcher.textContent()).toBe('标准模式(默认)')
const presetToggle = dialog.getByRole('button', { name: '会话插件', exact: true })
expect(await presetToggle.getAttribute('aria-expanded')).toBe('true')
expect(await dialog.locator('[data-plugin-scope="preset"] [data-plugin-entry]').count()).toBeGreaterThan(0)
const globalToggle = dialog.getByRole('button', { name: /^全局/ })
expect(await globalToggle.getAttribute('aria-expanded')).toBe('false')
await globalToggle.click()
const pluginRow = dialog.locator(PLUGIN_ROW_SELECTOR)
await pluginRow.waitFor({ timeout: 10_000 })
const expectedPluginCount = [...scaffold.ctx.loader.entries()]
.filter(entry => !entry.options.group)
.length
const pluginSearch = dialog.getByRole('searchbox', { name: '搜索插件' })
expect(await pluginSearch.count()).toBe(1)
// Every Loader entry appears exactly once in the global group — rows the
// presets took over included, preset compositions excluded.
expect(await dialog.locator('[data-plugin-scope="global"] [data-plugin-entry]').count())
.toBe(expectedPluginCount)
// A plainly enabled row states its status only in its accessible name: it
// carries no tag, and an active fiber draws no dot, so no global row shows
// either. Guard the assertions against matching nothing because no row is enabled.
const enabledRows = dialog.locator('[data-plugin-scope="global"] [data-plugin-entry] button[aria-label$="已启用"]')
expect(await enabledRows.count()).toBeGreaterThan(0)
expect(await enabledRows.getByText('已启用', { exact: true }).count()).toBe(0)
expect(await dialog.locator('[data-plugin-scope="global"] [role="img"][aria-label="运行中"]').count()).toBe(0)
expect(await dialog.getByText('由 Agent 预设按会话组成', { exact: true }).count()).toBe(1)
expect(await dialog.getByText('系统与所有会话共用', { exact: true }).count()).toBe(1)
expect(await dialog.getByRole('button', { name: '内置插件', exact: true }).getAttribute('aria-current')).toBe('true')
// One contribution shows as the page itself, without a tab row.
expect(await dialog.getByRole('tab').count()).toBe(0)
expect(await dialog.getByRole('button', { name: '模型', exact: true }).getAttribute('aria-current')).toBeNull()
const pluginsSnapshot = await captureStableAria(
page,
PLUGIN_ROW_SELECTOR,
scaffold.workspaceCwd,
)
await compareOrRefreshGolden(PLUGINS_EXPECTED, pluginsSnapshot, MODE)
await pluginSearch.fill('tool-subagent')
const instanceRows = [
['tool-subagent', '已启用'],
['tool-subagent-fork', '已启用'],
] as const
for (const [entryId, status] of instanceRows) {
const row = dialog.locator(`[data-plugin-scope="preset"] [data-plugin-entry="${entryId}"]`)
const name = `子智能体委派工具, ${entryId}, ${status}`
const trigger = row.getByRole('button', { name, exact: true })
await trigger.waitFor({ timeout: 10_000 })
expect(await trigger.getAttribute('aria-expanded')).toBe('false')
const identity = row.locator('code')
expect(await identity.textContent()).toBe(entryId)
expect(await identity.getAttribute('title')).toBe(entryId)
}
expect(await dialog.locator('[data-plugin-entry="tool-subagent-codex"], [data-plugin-entry="tool-subagent-claude-code"]').count()).toBe(0)
const instancesSnapshot = await captureStableAria(
page,
'[data-plugin-scope="preset"] ul',
scaffold.workspaceCwd,
)
await compareOrRefreshGolden(PLUGIN_INSTANCES_EXPECTED, instancesSnapshot, MODE)
await dialog.getByRole('button', {
name: '子智能体委派工具, tool-subagent-fork, 已启用',
exact: true,
}).click()
expect(await dialog.locator('[data-plugin-entry="tool-subagent-fork"] button')
.getAttribute('aria-expanded')).toBe('true')
await pluginSearch.fill('')
// Close path 1: Escape.
await page.keyboard.press('Escape')
await expect.poll(() => page.getByRole('dialog', { name: '设置' }).count(), { timeout: 5_000 }).toBe(0)
@@ -229,6 +148,27 @@ describe('web e2e: settings modal and General preferences', () => {
expect(tripwire.pageErrors).toEqual([])
}, 60_000)
it('leaves Settings for the sidebar Plugins page from the Plugin management entry', async () => {
const linkPage = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
onTestFinished(() => linkPage.close())
onTestFailed(() => saveSettingsFailureShot(linkPage, 'settings-plugins-link'))
const linkConsole = watchConsole(linkPage)
await linkPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await openSettings(linkPage, 'zh')
const dialog = linkPage.getByRole('dialog', { name: '设置', exact: true })
const sections = await dialog.getByRole('navigation').getByRole('button').allTextContents()
// The entry holds the position between Models and Agent presets.
expect(sections.indexOf('插件管理')).toBe(sections.indexOf('模型') + 1)
expect(sections.indexOf('Agent 预设')).toBe(sections.indexOf('插件管理') + 1)
await dialog.getByRole('button', { name: '插件管理', exact: true }).click()
await expect.poll(() => dialog.count(), { timeout: 5_000 }).toBe(0)
const pluginsEntry = linkPage.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true })
await expect.poll(() => pluginsEntry.getAttribute('aria-current'), { timeout: 10_000 }).toBe('page')
await linkPage.locator('[data-plugin-panel]').getByRole('heading', { name: '插件', exact: true }).waitFor({ timeout: 10_000 })
expect(linkConsole.pageErrors).toEqual([])
expect(linkConsole.warnings).toEqual([])
})
it('scrolls overflowing section navigation independently of the title and settings content', async () => {
const overflowPage = await browser.newPage({ viewport: { width: 1280, height: 768 }, locale: ZH_BROWSER_LOCALE })
onTestFinished(() => overflowPage.close())
@@ -953,17 +893,12 @@ describe('web e2e: settings modal and General preferences', () => {
const dialog = enPage.getByRole('dialog', { name: 'Settings' })
await dialog.waitFor({ timeout: 10_000 })
await dialog.getByRole('button', { name: 'English' }).waitFor({ timeout: 10_000 })
// The plugin list resolves shipped preset names through the en
// dictionaries instead of echoing the preset declarations' Chinese metadata.
await dialog.getByRole('button', { name: 'Built-in plugins', exact: true }).click()
const presetSwitcher = dialog.getByRole('button', { name: 'Choose the agent preset to inspect' })
await presetSwitcher.waitFor({ timeout: 10_000 })
expect(await presetSwitcher.textContent()).toBe('Standard mode (default)')
// The plugin manager speaks the en dictionary too: its sidebar entry
// and the unavailable notice a scaffold without a profile runtime shows.
await enPage.keyboard.press('Escape')
// The plugin manager speaks the en dictionary too: its Settings entry
// leaves Settings for the Plugins page, whose header and the sidebar entry are English.
await dialog.getByRole('button', { name: 'Plugins', exact: true }).click()
await expect.poll(() => enPage.getByRole('dialog', { name: 'Settings' }).count(), { timeout: 5_000 }).toBe(0)
await enPage.getByRole('navigation', { name: 'Global panels' }).getByRole('button', { name: 'Plugins', exact: true }).click()
await expect.poll(() => enPage.getByRole('navigation', { name: 'Global panels' })
.getByRole('button', { name: 'Plugins', exact: true }).getAttribute('aria-current'), { timeout: 10_000 }).toBe('page')
await enPage.getByRole('button', { name: 'Add plugin', exact: true })
.waitFor({ timeout: 10_000 })
// This page has no closing inventory spec to sweep its console, so the
@@ -1042,8 +977,6 @@ describe('web e2e: settings modal and General preferences', () => {
'dialog.expected.md',
'collapse-timing-en.expected.md',
'collapse-timing-zh.expected.md',
'plugin-instances.expected.md',
'plugins.expected.md',
])
})
})
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: 27aeeae6cfadf63f
zh: 95c8d86301ab16dc
en: 676d9f8a0565d89a
zh: 34933f54af9fdee7
+4 -4
View File
@@ -29,7 +29,6 @@ flowchart LR
svc_pluginRegistryProbe["ctx.pluginRegistryProbe<br/>Host registry response comparison"]
pkg_plugin_manager["plugin-manager"]
svc_pluginManager["ctx.pluginManager<br/>Current-profile plugin and bundle management"]
pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"]
pkg_plugin_market["plugin-market"]
svc_pluginMarket["ctx.pluginMarket<br/>Plugin market index reader"]
pkg_client_ui_plugin_market["client-ui-plugin-market"]
@@ -44,6 +43,7 @@ flowchart LR
pkg_experimental_forge["experimental-forge"]
svc_forge["ctx.forge<br/>Code host change requests"]
pkg_experimental_forge_github["experimental-forge-github"]
pkg_forge_gitlab["forge-gitlab"]
pkg_experimental_forge_session["experimental-forge-session"]
pkg_experimental_client_ui_forge["experimental-client-ui-forge"]
svc_forgeSession["ctx.forgeSession<br/>Session change request bindings"]
@@ -390,6 +390,7 @@ flowchart LR
pkg_experimental_worktree --> svc_worktrees
pkg_file_reference --> svc_fileReferences
pkg_file_reference_local --> svc_fileReferences
pkg_forge_gitlab --> svc_forge
pkg_fs --> svc_fs
pkg_fs_local --> svc_fs
pkg_fs_sandbox --> svc_fs
@@ -556,7 +557,6 @@ flowchart LR
svc_otel --> pkg_host_product_telemetry_otel
svc_otel --> pkg_session_telemetry_otel
svc_pluginManager --> pkg_plugin_manager
svc_pluginManager --> pkg_ui_settings_plugin_inventory
svc_pluginMarket --> pkg_client_ui_plugin_market
svc_pluginMarket --> pkg_plugin_market
svc_pluginRecommendations --> pkg_client_ui_plugin_recommendations
@@ -682,12 +682,12 @@ flowchart LR
| `ctx.translator` | `service` | [`experimental-translator`](../packages/experimental/translator) | - | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | Resolves Google or Bing requests and retains shared experimental records through the active Session writer. |
| `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | Owns module and exact configuration watchers; application mutations share its queue and automatic reloads await the application file lock. |
| `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | Races public registry responses on the Host; the Client owns the initial registry recommendation. |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | Shares profile package operations with the CLI and reports persisted and running state to Web and agent callers. |
| `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | Fetches and validates the index sources the user configures; installation goes through the plugin manager. |
| `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | The dsh launcher supplies data-only profile locations and composition inputs; reload scheduling belongs to dsh-hmr. |
| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | Applies source policy and shared HTTP request dispatch; credential verification belongs to ConnectionAuthentication, and API adapters register endpoints and streams. |
| `ctx.connection.authentication` | `seam` | [`client-connection`](../packages/client/connection) | [`host-authentication-token`](../packages/host/authentication-token), [`host-authentication-desktop`](../packages/host/authentication-desktop) | [`client-connection`](../packages/client/connection) | - | Tries scope-owned credential verifiers in registration order and returns the first live Peer; transport source policy and business authorization stay with their consumers. |
| `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Providers map remote and change request URLs, look up change requests by head branch, and read status in batches; watchers of one change request share one polling loop. |
| `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github), [`forge-gitlab`](../packages/experimental/forge-gitlab) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Providers map remote and change request URLs, look up change requests by head branch, and read status in batches; watchers of one change request share one polling loop. |
| `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. |
+4 -4
View File
@@ -31,7 +31,6 @@ flowchart LR
svc_pluginRegistryProbe["ctx.pluginRegistryProbe<br/>Host registry response comparison"]
pkg_plugin_manager["plugin-manager"]
svc_pluginManager["ctx.pluginManager<br/>Current-profile plugin and bundle management"]
pkg_ui_settings_plugin_inventory["ui-settings-plugin-inventory"]
pkg_plugin_market["plugin-market"]
svc_pluginMarket["ctx.pluginMarket<br/>Plugin market index reader"]
pkg_client_ui_plugin_market["client-ui-plugin-market"]
@@ -46,6 +45,7 @@ flowchart LR
pkg_experimental_forge["experimental-forge"]
svc_forge["ctx.forge<br/>Code host change requests"]
pkg_experimental_forge_github["experimental-forge-github"]
pkg_forge_gitlab["forge-gitlab"]
pkg_experimental_forge_session["experimental-forge-session"]
pkg_experimental_client_ui_forge["experimental-client-ui-forge"]
svc_forgeSession["ctx.forgeSession<br/>Session change request bindings"]
@@ -392,6 +392,7 @@ flowchart LR
pkg_experimental_worktree --> svc_worktrees
pkg_file_reference --> svc_fileReferences
pkg_file_reference_local --> svc_fileReferences
pkg_forge_gitlab --> svc_forge
pkg_fs --> svc_fs
pkg_fs_local --> svc_fs
pkg_fs_sandbox --> svc_fs
@@ -558,7 +559,6 @@ flowchart LR
svc_otel --> pkg_host_product_telemetry_otel
svc_otel --> pkg_session_telemetry_otel
svc_pluginManager --> pkg_plugin_manager
svc_pluginManager --> pkg_ui_settings_plugin_inventory
svc_pluginMarket --> pkg_client_ui_plugin_market
svc_pluginMarket --> pkg_plugin_market
svc_pluginRecommendations --> pkg_client_ui_plugin_recommendations
@@ -684,12 +684,12 @@ flowchart LR
| `ctx.translator` | `service` | [`experimental-translator`](../packages/experimental/translator) | - | [`experimental-client-ui-cot-translation`](../packages/experimental/client-ui-cot-translation) | - | 解析 Google 或 Bing 请求,并可选保留统一的实验性 Session 记录。 |
| `ctx.hmr` | `core` | [`hmr`](../packages/boot/hmr) | - | [`app-boot`](../packages/boot/app-boot) | - | 负责模块和精确配置监听;应用修改共用其队列,自动重载等待应用文件锁。 |
| `ctx.pluginRegistryProbe` | `core` | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | [`client-ui-plugin-manager`](../packages/client/ui-plugin-manager) | - | 在 Host 上并发比较公共安装源响应;初始安装源推荐由 Client 负责。 |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager), `ui-settings-plugin-inventory` | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 |
| `ctx.pluginManager` | `core` | [`plugin-manager`](../packages/boot/plugin-manager) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | 与 CLI 共享 profile 包操作,并向 Web 和 Agent 调用方分别报告持久状态与运行状态。 |
| `ctx.pluginMarket` | `core` | [`plugin-market`](../packages/boot/plugin-market) | - | [`client-ui-plugin-market`](../packages/client/ui-plugin-market), [`plugin-market`](../packages/boot/plugin-market) | - | 获取并校验用户配置的索引源;安装通过插件管理器完成。 |
| `ctx.profileContext` | `core` | [`app-boot`](../packages/boot/app-boot) | - | [`plugin-manager`](../packages/boot/plugin-manager) | - | dsh launcher 提供纯数据形式的 profile 位置与组合输入;重载调度由 dsh-hmr 负责。 |
| `ctx.connection` | `core` | [`client-connection`](../packages/client/connection) | - | [`api-gateway`](../packages/api/gateway), [`host-frontend-static`](../packages/host/frontend-static) | - | 执行来源策略与共享 HTTP 请求分发;凭据验证归 ConnectionAuthentication,API 适配器注册端点和流。 |
| `ctx.connection.authentication` | `seam` | [`client-connection`](../packages/client/connection) | [`host-authentication-token`](../packages/host/authentication-token), [`host-authentication-desktop`](../packages/host/authentication-desktop) | [`client-connection`](../packages/client/connection) | - | 按注册顺序尝试作用域拥有的凭据验证器,返回首个存活 Peer;传输来源策略和业务授权仍归各自消费者。 |
| `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | 提供方映射远端与变更请求 URL、按 head 分支查找变更请求并批量读取状态;同一变更请求的监听方共享一个轮询循环。 |
| `ctx.forge` | `seam` | [`experimental-forge`](../packages/experimental/forge) | [`experimental-forge-github`](../packages/experimental/forge-github), [`forge-gitlab`](../packages/experimental/forge-gitlab) | [`experimental-forge-session`](../packages/experimental/forge-session), [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | 提供方映射远端与变更请求 URL、按 head 分支查找变更请求并批量读取状态;同一变更请求的监听方共享一个轮询循环。 |
| `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 目录。 |
+40 -9
View File
@@ -1182,7 +1182,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:483`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1270,7 +1270,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1293,7 +1293,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge-github`
- `inject`: `forge`
- `source`: [`packages/experimental/forge-github/src/index.ts:14`](../packages/experimental/forge-github/src/index.ts)
- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts)
```ts config-catalog
/** GitHub CLI executable, served hosts, and invocation limits. */
@@ -1325,7 +1325,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge-session`
- `inject`: `forge` · `sessions` · `sessionProjections`
- `source`: [`packages/experimental/forge-session/src/types.ts:91`](../packages/experimental/forge-session/src/types.ts)
- `source`: [`packages/experimental/forge-session/src/types.ts:160`](../packages/experimental/forge-session/src/types.ts)
```ts config-catalog
/** Deployment settings of `forgeSession`. */
@@ -1629,6 +1629,39 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-file-reference-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
<a id="deepseek-aidsh-forge-gitlab"></a>
## `@deepseek-ai/dsh-forge-gitlab`
- `inject`: `forge`
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts)
```ts config-catalog
/** GitLab CLI executable, served hosts, and read limits. */
export interface Config {
/** GitLab CLI executable name or absolute host path. */
glabCommand?: string
/** Host names this provider serves; list self-managed GitLab hosts explicitly. */
hosts?: string[]
/** Deadline in milliseconds for one `glab` invocation. */
timeoutMs?: number
/** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */
maxOutputBytes?: number
/** Most review threads one review read returns, which reports itself truncated past it. */
maxReviewThreads?: number
/** Most commits one merge request commit listing returns, the oldest ones when there are more. */
maxCommits?: number
/** Most merge requests one status query reads; GitLab refuses a query over its complexity limit, which halves the batch. */
statusBatchSize?: number
/** Most `glab` processes one status fetch runs at once. */
maxConcurrentRequests?: number
/** Most bytes of diff version patches kept in memory for the hunks of outdated review threads. */
maxCachedVersionBytes?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-fs-local -->
<a id="deepseek-aidsh-fs-local"></a>
@@ -2844,14 +2877,14 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:45`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
export interface Config {
/** Index URLs in display order; Settings and `setIndexes` write this field without remounting the service. */
indexes: Volatile<string[]>
/** Deadline for one index fetch, including the body. */
/** Deadline for an HTTP index or detail file request, including its body. */
fetchTimeoutMs: number
/** Largest accepted index body in bytes. */
maxBytes: number
@@ -2867,7 +2900,7 @@ export interface Config {
detailCacheMaxBytes: number
/** Directory of the partial clones, relative to the profile directory; absent means `.plugin-market/repositories`. */
detailCacheDir?: string
/** Deadline of one Git command of the clone fallback. */
/** Deadline for a Git index read and for each Git command used to read an index or plugin details. */
detailGitTimeoutMs: number
/** npm file CDNs read in order; a read's `npmFileSources` moves the CDNs it names first. */
detailNpmFileSources: NpmFileSource[]
@@ -5244,8 +5277,6 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-plugin-inventory` | — | [`packages/client/ui-settings-plugin-inventory/src/index.ts`](../packages/client/ui-settings-plugin-inventory/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-plugins` | — | [`packages/client/ui-settings-plugins/src/index.ts`](../packages/client/ui-settings-plugins/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-session-log` | — | [`packages/client/ui-settings-session-log/src/index.ts`](../packages/client/ui-settings-session-log/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-shell` | — | [`packages/client/ui-settings-shell/src/index.ts`](../packages/client/ui-settings-shell/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-subagent` | — | [`packages/client/ui-settings-subagent/src/index.ts`](../packages/client/ui-settings-subagent/src/index.ts) |
+40 -9
View File
@@ -1184,7 +1184,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:483`](../packages/experimental/client-ui-forge/src/types.ts)
- `source`: [`packages/experimental/client-ui-forge/src/types.ts:485`](../packages/experimental/client-ui-forge/src/types.ts)
```ts config-catalog
/** Host settings of the forge panel Remote. */
@@ -1272,7 +1272,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge`
- `source`: [`packages/experimental/forge/src/types.ts:603`](../packages/experimental/forge/src/types.ts)
- `source`: [`packages/experimental/forge/src/types.ts:638`](../packages/experimental/forge/src/types.ts)
```ts config-catalog
/** Poll cadence and fetch deadline for watched change requests. */
@@ -1295,7 +1295,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge-github`
- `inject`: `forge`
- `source`: [`packages/experimental/forge-github/src/index.ts:14`](../packages/experimental/forge-github/src/index.ts)
- `source`: [`packages/experimental/forge-github/src/index.ts:19`](../packages/experimental/forge-github/src/index.ts)
```ts config-catalog
/** GitHub CLI executable, served hosts, and invocation limits. */
@@ -1327,7 +1327,7 @@ export interface Config {
## `@deepseek-ai/dsh-experimental-forge-session`
- `inject`: `forge` · `sessions` · `sessionProjections`
- `source`: [`packages/experimental/forge-session/src/types.ts:91`](../packages/experimental/forge-session/src/types.ts)
- `source`: [`packages/experimental/forge-session/src/types.ts:160`](../packages/experimental/forge-session/src/types.ts)
```ts config-catalog
/** Deployment settings of `forgeSession`. */
@@ -1631,6 +1631,39 @@ export interface Config {
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-file-reference-local -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
<a id="deepseek-aidsh-forge-gitlab"></a>
## `@deepseek-ai/dsh-forge-gitlab`
- `inject`: `forge`
- `source`: [`packages/experimental/forge-gitlab/src/index.ts:19`](../packages/experimental/forge-gitlab/src/index.ts)
```ts config-catalog
/** GitLab CLI executable, served hosts, and read limits. */
export interface Config {
/** GitLab CLI executable name or absolute host path. */
glabCommand?: string
/** Host names this provider serves; list self-managed GitLab hosts explicitly. */
hosts?: string[]
/** Deadline in milliseconds for one `glab` invocation. */
timeoutMs?: number
/** Maximum captured bytes per `glab` output stream and combined JSON bytes of one complete check read or review read. */
maxOutputBytes?: number
/** Most review threads one review read returns, which reports itself truncated past it. */
maxReviewThreads?: number
/** Most commits one merge request commit listing returns, the oldest ones when there are more. */
maxCommits?: number
/** Most merge requests one status query reads; GitLab refuses a query over its complexity limit, which halves the batch. */
statusBatchSize?: number
/** Most `glab` processes one status fetch runs at once. */
maxConcurrentRequests?: number
/** Most bytes of diff version patches kept in memory for the hunks of outdated review threads. */
maxCachedVersionBytes?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-forge-gitlab -->
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-fs-local -->
<a id="deepseek-aidsh-fs-local"></a>
@@ -2846,14 +2879,14 @@ export interface Config {
- `inject`: `pluginManager`
- `refs`: [`NpmFileSource`](subsystems/boot.zh.md) · `Volatile` (`@deepseek-ai/cordis`)
- `source`: [`packages/boot/plugin-market/src/index.ts:44`](../packages/boot/plugin-market/src/index.ts)
- `source`: [`packages/boot/plugin-market/src/index.ts:45`](../packages/boot/plugin-market/src/index.ts)
```ts config-catalog
/** Index sources and fetch limits. */
export interface Config {
/** Index URLs in display order; Settings and `setIndexes` write this field without remounting the service. */
indexes: Volatile<string[]>
/** Deadline for one index fetch, including the body. */
/** Deadline for an HTTP index or detail file request, including its body. */
fetchTimeoutMs: number
/** Largest accepted index body in bytes. */
maxBytes: number
@@ -2869,7 +2902,7 @@ export interface Config {
detailCacheMaxBytes: number
/** Directory of the partial clones, relative to the profile directory; absent means `.plugin-market/repositories`. */
detailCacheDir?: string
/** Deadline of one Git command of the clone fallback. */
/** Deadline for a Git index read and for each Git command used to read an index or plugin details. */
detailGitTimeoutMs: number
/** npm file CDNs read in order; a read's `npmFileSources` moves the CDNs it names first. */
detailNpmFileSources: NpmFileSource[]
@@ -5246,8 +5279,6 @@ export interface Config {
| `@deepseek-ai/dsh-client-ui-settings` | — | [`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-agent-loop` | — | [`packages/client/ui-settings-agent-loop/src/index.ts`](../packages/client/ui-settings-agent-loop/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-general` | — | [`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-plugin-inventory` | — | [`packages/client/ui-settings-plugin-inventory/src/index.ts`](../packages/client/ui-settings-plugin-inventory/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-plugins` | — | [`packages/client/ui-settings-plugins/src/index.ts`](../packages/client/ui-settings-plugins/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-session-log` | — | [`packages/client/ui-settings-session-log/src/index.ts`](../packages/client/ui-settings-session-log/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-shell` | — | [`packages/client/ui-settings-shell/src/index.ts`](../packages/client/ui-settings-shell/src/index.ts) |
| `@deepseek-ai/dsh-client-ui-settings-subagent` | — | [`packages/client/ui-settings-subagent/src/index.ts`](../packages/client/ui-settings-subagent/src/index.ts) |
@@ -12,8 +12,8 @@
en: 9c2680c175632a58
zh: 46927fca484b5df0
/cookbook-live-configuration-forms/3-verify-editing:
en: dc5dc7ab4c211b97
zh: 88f8af745c576a6d
en: cf8d614d67a0ade6
zh: 92a7b53ce83e967a
/cookbook-live-configuration-forms/4-contribute-to-another-plugin-s-page:
en: 0abb582a1a25b3d9
zh: 6078a707324ec515
+1 -1
View File
@@ -39,7 +39,7 @@ Give each instance a unique profile entry id. The base bundle mounts settings an
Change a field in Plugins and save. Verify the profile patch, the next consumer operation, unchanged plugin instance identity, and restoration after restart. Reject an invalid value and verify that neither the file nor the live value changed.
Custom plugin pages receive `form.state` and `form.mutate(operations, expectedRevision)` from the Plugins page owner. The Host validates full Config and applies edits through ConfigEditor and volatile HMR. The [plugin settings package](../../packages/client/ui-settings-plugins/README.md) owns the existing card examples.
Custom plugin pages receive `form.state` and `form.mutate(operations, expectedRevision)` from the Plugins page owner. The Host validates full Config and applies edits through ConfigEditor and volatile HMR. The [Plugins page README](../../packages/client/ui-plugin-manager/README.md#configuration-pages) lists the slots such a page registers into and how a `settings.section` entry also appears there; [ui-settings-shell](../../packages/client/ui-settings-shell/README.md) is an existing page.
## 4. Contribute to another plugin's page
+1 -1
View File
@@ -39,7 +39,7 @@ export function apply(ctx: Context, config: Config): void {
在插件页面修改字段并保存。验证 profile patch、消费者下一次操作、插件实例标识不变,以及重启后的恢复。提交无效值,并确认文件和即时值均未改变。
自定义插件页面从 Plugins 页面所有者接收 `form.state` 和 `form.mutate(operations, expectedRevision)`。Host 校验完整 Config,并通过 ConfigEditor 和 volatile HMR 应用修改。[插件设置包](../../packages/client/ui-settings-plugins/README.zh.md) 提供现有卡片示例。
自定义插件页面从 Plugins 页面所有者接收 `form.state` 和 `form.mutate(operations, expectedRevision)`。Host 校验完整 Config,并通过 ConfigEditor 和 volatile HMR 应用修改。[插件页面 README](../../packages/client/ui-plugin-manager/README.zh.md#configuration-pages) 列出此类页面可注册的 slot,以及 `settings.section` 条目如何同时出现在那里;[ui-settings-shell](../../packages/client/ui-settings-shell/README.zh.md) 是一个现有页面。
## 4. 向其他插件的页面贡献内容
+2 -2
View File
@@ -47,8 +47,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/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:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
| `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` |
| `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` |
+2 -2
View File
@@ -49,8 +49,8 @@
| `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:29`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | [`deepseek-account`](../packages/credentials/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:30`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `forge/review-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:39`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `client-ui-forge` |
| `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` |
| `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` |
+9 -7
View File
@@ -202,8 +202,6 @@ flowchart TD
pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"]
pkg_client_ui_settings_general["client-ui-settings-general"]
pkg_client_ui_settings_models["client-ui-settings-models"]
pkg_client_ui_settings_plugin_inventory["client-ui-settings-plugin-inventory"]
pkg_client_ui_settings_plugins["client-ui-settings-plugins"]
pkg_client_ui_settings_session_log["client-ui-settings-session-log"]
pkg_client_ui_settings_shell["client-ui-settings-shell"]
pkg_client_ui_settings_subagent["client-ui-settings-subagent"]
@@ -312,6 +310,7 @@ flowchart TD
pkg_experimental_webworker_packer["experimental-webworker-packer"]
pkg_experimental_webworker_runtime["experimental-webworker-runtime"]
pkg_experimental_worktree["experimental-worktree"]
pkg_forge_gitlab["forge-gitlab"]
pkg_hook_protocol["hook-protocol"]
pkg_hooks_claude_code["hooks-claude-code"]
pkg_hooks_codex["hooks-codex"]
@@ -535,8 +534,6 @@ flowchart TD
pkg_credentials_local --> pkg_launch_environment
pkg_cua_mcp --> pkg_app_boot
pkg_cua_mcp --> pkg_attachment
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_webworker_runtime --> pkg_client_connection
pkg_experimental_webworker_runtime --> pkg_client_modules
pkg_experimental_webworker_runtime --> pkg_host_webserver
@@ -1282,6 +1279,9 @@ flowchart TD
pkg_experimental_claude_code_mods --> pkg_typert_protocol
pkg_experimental_claude_code_mods --> pkg_user_questions
pkg_experimental_claude_code_mods --> pkg_working_directory
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_experimental_forge_session
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_worktree --> pkg_agent
pkg_experimental_worktree --> pkg_error
pkg_experimental_worktree --> pkg_fs
@@ -1295,6 +1295,9 @@ flowchart TD
pkg_experimental_worktree --> pkg_subprocess
pkg_experimental_worktree --> pkg_working_directory
pkg_experimental_worktree --> pkg_workspace
pkg_forge_gitlab --> pkg_experimental_forge
pkg_forge_gitlab --> pkg_experimental_forge_session
pkg_forge_gitlab --> pkg_subprocess
pkg_tool_session_query --> pkg_agent
pkg_tool_session_query --> pkg_llm
pkg_tool_session_query --> pkg_session
@@ -1661,8 +1664,6 @@ flowchart TD
| [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — |
| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | — |
| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | — |
| [`client-ui-settings-plugin-inventory`](../packages/client/ui-settings-plugin-inventory) | `client` | — |
| [`client-ui-settings-plugins`](../packages/client/ui-settings-plugins) | `client` | — |
| [`client-ui-settings-session-log`](../packages/client/ui-settings-session-log) | `client` | — |
| [`client-ui-settings-shell`](../packages/client/ui-settings-shell) | `client` | — |
| [`client-ui-settings-subagent`](../packages/client/ui-settings-subagent) | `client` | — |
@@ -1755,7 +1756,6 @@ flowchart TD
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
| [`host-authentication-desktop`](../packages/host/authentication-desktop) | `host` | [`client-connection`](../packages/client/connection) |
| [`host-authentication-token`](../packages/host/authentication-token) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) |
@@ -1918,7 +1918,9 @@ flowchart TD
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
+9 -7
View File
@@ -204,8 +204,6 @@ flowchart TD
pkg_client_ui_settings_agent_loop["client-ui-settings-agent-loop"]
pkg_client_ui_settings_general["client-ui-settings-general"]
pkg_client_ui_settings_models["client-ui-settings-models"]
pkg_client_ui_settings_plugin_inventory["client-ui-settings-plugin-inventory"]
pkg_client_ui_settings_plugins["client-ui-settings-plugins"]
pkg_client_ui_settings_session_log["client-ui-settings-session-log"]
pkg_client_ui_settings_shell["client-ui-settings-shell"]
pkg_client_ui_settings_subagent["client-ui-settings-subagent"]
@@ -314,6 +312,7 @@ flowchart TD
pkg_experimental_webworker_packer["experimental-webworker-packer"]
pkg_experimental_webworker_runtime["experimental-webworker-runtime"]
pkg_experimental_worktree["experimental-worktree"]
pkg_forge_gitlab["forge-gitlab"]
pkg_hook_protocol["hook-protocol"]
pkg_hooks_claude_code["hooks-claude-code"]
pkg_hooks_codex["hooks-codex"]
@@ -537,8 +536,6 @@ flowchart TD
pkg_credentials_local --> pkg_launch_environment
pkg_cua_mcp --> pkg_app_boot
pkg_cua_mcp --> pkg_attachment
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_webworker_runtime --> pkg_client_connection
pkg_experimental_webworker_runtime --> pkg_client_modules
pkg_experimental_webworker_runtime --> pkg_host_webserver
@@ -1284,6 +1281,9 @@ flowchart TD
pkg_experimental_claude_code_mods --> pkg_typert_protocol
pkg_experimental_claude_code_mods --> pkg_user_questions
pkg_experimental_claude_code_mods --> pkg_working_directory
pkg_experimental_forge_github --> pkg_experimental_forge
pkg_experimental_forge_github --> pkg_experimental_forge_session
pkg_experimental_forge_github --> pkg_subprocess
pkg_experimental_worktree --> pkg_agent
pkg_experimental_worktree --> pkg_error
pkg_experimental_worktree --> pkg_fs
@@ -1297,6 +1297,9 @@ flowchart TD
pkg_experimental_worktree --> pkg_subprocess
pkg_experimental_worktree --> pkg_working_directory
pkg_experimental_worktree --> pkg_workspace
pkg_forge_gitlab --> pkg_experimental_forge
pkg_forge_gitlab --> pkg_experimental_forge_session
pkg_forge_gitlab --> pkg_subprocess
pkg_tool_session_query --> pkg_agent
pkg_tool_session_query --> pkg_llm
pkg_tool_session_query --> pkg_session
@@ -1663,8 +1666,6 @@ flowchart TD
| [`client-ui-settings-agent-loop`](../packages/client/ui-settings-agent-loop) | `client` | — |
| [`client-ui-settings-general`](../packages/client/ui-settings-general) | `client` | — |
| [`client-ui-settings-models`](../packages/client/ui-settings-models) | `client` | — |
| [`client-ui-settings-plugin-inventory`](../packages/client/ui-settings-plugin-inventory) | `client` | — |
| [`client-ui-settings-plugins`](../packages/client/ui-settings-plugins) | `client` | — |
| [`client-ui-settings-session-log`](../packages/client/ui-settings-session-log) | `client` | — |
| [`client-ui-settings-shell`](../packages/client/ui-settings-shell) | `client` | — |
| [`client-ui-settings-subagent`](../packages/client/ui-settings-subagent) | `client` | — |
@@ -1757,7 +1758,6 @@ flowchart TD
| [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) |
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) |
| [`host-authentication-desktop`](../packages/host/authentication-desktop) | `host` | [`client-connection`](../packages/client/connection) |
| [`host-authentication-token`](../packages/host/authentication-token) | `host` | [`client-connection`](../packages/client/connection), [`host-webserver`](../packages/host/webserver) |
@@ -1920,7 +1920,9 @@ flowchart TD
| [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-browser-use-runtime`](../packages/experimental/browser-use-runtime) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`error`](../packages/util/error), [`mcp-client`](../packages/mcp/mcp-client), [`scope`](../packages/core/scope), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) |
| [`experimental-claude-code-mods`](../packages/experimental/claude-code-mods) | `experimental` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`storage-domain`](../packages/storage/storage-domain), [`subprocess`](../packages/subprocess/subprocess), [`token-meter`](../packages/llm/token-meter), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`user-questions`](../packages/interaction/user-questions), [`working-directory`](../packages/session/working-directory) |
| [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
| [`experimental-worktree`](../packages/experimental/worktree) | `experimental` | [`agent`](../packages/core/agent), [`error`](../packages/util/error), [`fs`](../packages/fs/fs), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-query`](../packages/session-query/session-query), [`settings`](../packages/settings/settings), [`subprocess`](../packages/subprocess/subprocess), [`working-directory`](../packages/session/working-directory), [`workspace`](../packages/workspace/workspace) |
| [`forge-gitlab`](../packages/experimental/forge-gitlab) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`experimental-forge-session`](../packages/experimental/forge-session), [`subprocess`](../packages/subprocess/subprocess) |
| [`tool-session-query`](../packages/experimental/tool-session-query) | `experimental` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query), [`system-prompt`](../packages/core/system-prompt), [`timeout`](../packages/util/timeout), [`tools`](../packages/core/tools) |
| [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) |
| [`mcp-manager`](../packages/mcp/mcp-manager) | `mcp` | [`mcp-client`](../packages/mcp/mcp-client), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol), [`util-values`](../packages/util/values) |
+8 -8
View File
@@ -3,11 +3,11 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/subsystems/forge.md
/forges:
en: 3990a17e12c66a23
zh: 4170c33e49248f8f
en: 37c9cbfb3141702b
zh: c5fcbb7f4fda1dbc
/forges/providers-and-change-requests:
en: e5d807b29f553751
zh: e0b25d9e964f988e
en: 8df1bf8a6d294252
zh: 79ba96596739569f
/forges/status-polling:
en: 26ccfa2e342e3e67
zh: fe6cc2a622757c48
@@ -15,14 +15,14 @@
en: ae735fbdbdf2d870
zh: 9903fcc571104ad8
/forges/review-threads:
en: af729af6e59e915f
zh: 1b7d7671ec36a5b2
en: 6a4162560b1aa158
zh: 5349e9f25d08fd97
/forges/overview-and-viewed-marks:
en: fd5928603c9375b1
zh: 1a3bca55344ff385
/forges/session-bindings:
en: 13dfd36f2166bba0
zh: a369434f52f04d57
en: 74255d6005e1c9e8
zh: 252d0d552f1e26a1
/forges/panel:
en: 7dcefe2825490257
zh: 38cec4d1ae3b0d6e
+168 -22
View File
@@ -2,11 +2,11 @@
English | [中文](forge.zh.md)
The experimental forge capability seam reads change requests, meaning pull requests and merge requests, from code hosts. [`dsh-experimental-forge`](../../packages/experimental/forge/README.md) is the Service Definition and provides `ctx.forge`; [`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.md) is the Service Provider for GitHub hosts; [`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.md) is the Consumer that binds change requests to Sessions and provides `ctx.forgeSession`; [`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.md) is the GUI Consumer that provides `ctx.forgePanel`. The default-disabled [forge bundle](../../packages/experimental/forge-bundle/README.md) composes all four, with the [worktree model tool](../../packages/experimental/tool-worktree/README.md) and one shared [worktree service](../../packages/experimental/worktree/README.md), from the Plugins page; otherwise they load only through explicit composition.
The experimental forge capability seam reads change requests, meaning pull requests and merge requests, from code hosts. [`dsh-experimental-forge`](../../packages/experimental/forge/README.md) is the Service Definition and provides `ctx.forge`; [`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.md) and [`dsh-forge-gitlab`](../../packages/experimental/forge-gitlab/README.md) are the Service Providers for GitHub and GitLab hosts; [`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.md) is the Consumer that binds change requests to Sessions and provides `ctx.forgeSession`; [`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.md) is the GUI Consumer that provides `ctx.forgePanel`. The default-disabled [forge bundle](../../packages/experimental/forge-bundle/README.md) composes all five, with the [worktree model tool](../../packages/experimental/tool-worktree/README.md) and one shared [worktree service](../../packages/experimental/worktree/README.md), from the Plugins page; otherwise they load only through explicit composition.
## Providers and change requests
A provider serves one forge family, such as `github`. It maps Git remote URLs to repositories and change request URLs to references, builds canonical change request URLs, finds open change requests by head branch, and reads status in batches. `changeRequestKey` derives one case-insensitive key from a reference, so watchers of differently spelled URLs share one polling loop.
A provider serves one forge family, such as `github`, on the hosts it lists in `hosts`; no two registered providers may list the same host, so each remote and change request URL has at most one provider. It maps Git remote URLs to repositories and change request URLs to references, builds canonical change request URLs, finds open change requests by head branch, and reads status in batches. `changeRequestKey` derives one case-insensitive key from a reference, so watchers of differently spelled URLs share one polling loop.
```ts type-equiv
/** One repository on a code host, identified the way its provider addresses it. */
@@ -40,11 +40,20 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'>
```ts type-equiv
/**
* Host-specific access registered with `ctx.forge`. One provider serves one
* forge family; methods that take a signal must stop work when it aborts.
* forge family on the hosts it lists; methods that take a signal must stop work when it aborts.
*/
interface ForgeProvider {
/** Forge family name stored in every repository this provider returns. */
readonly forge: string
/**
* Lowercase host names this provider serves, such as `github.com`; `repositoryFromRemote` and `changeRequestFromUrl`
* return only these hosts, and no other registered provider may list one of them.
*/
readonly hosts: readonly string[]
/** Product name readers know this provider's hosts by, such as `GitHub`. */
readonly label: string
/** What this provider's hosts call a change request. */
readonly changeRequestNoun: ChangeRequestNoun
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
@@ -135,8 +144,10 @@ interface ForgeProvider {
reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure>
/**
* Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to
* undefined once the host accepted the update. Omission declares that the provider updates no branches, and its
* snapshots then offer no `branchUpdates`.
* undefined once the host accepted the update. A host whose update names the expected head checks it with the update;
* for one whose update cannot, the provider reads the head just before it, so a push between the read and the update
* is updated too. Omission declares that the provider updates no branches, and its snapshots then offer no
* `branchUpdates`.
*/
updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
}
@@ -179,6 +190,27 @@ interface ForgeReadiness {
readonly state: 'ready' | 'unauthenticated' | 'unavailable'
/** Human-readable detail, or null when ready. */
readonly message: string | null
/** Shell command the user runs on the host to sign in, while `unauthenticated`; null otherwise or when the provider names none. */
readonly signIn: { readonly command: string } | null
}
```
`ctx.forge.describe(forge)` names a registered family with the `label` and `changeRequestNoun` its provider declares, so readers can call the code host and its change requests what the host calls them.
```ts type-equiv
/** What the hosts of a forge family call a change request. */
type ChangeRequestNoun = 'pull-request' | 'merge-request'
```
```ts type-equiv
/** How readers name a forge family and its change requests. */
interface ForgeDescription {
/** Forge family name, such as `github`. */
readonly forge: string
/** Product name readers know the family's hosts by, such as `GitHub`. */
readonly label: string
/** What the family's hosts call a change request. */
readonly changeRequestNoun: ChangeRequestNoun
}
```
@@ -411,7 +443,7 @@ type ForgeReviewResult =
## Review threads
`ctx.forge.readReview(ref, headSha, signal)` reads the review threads of a change request at one head commit. The provider returns `ForgeReviewData` only when the read names `headSha` as the head; otherwise it returns `stale`, which polls a watched change request again at once, as a stale diff read does. For a provider without `readReview` the service returns `unsupported`, so consumers show no threads instead of a failure. A line thread has two positions: `original` on the commit it was written on, and `current` on the head of the read, which is null once the host no longer places the thread on that commit. A consumer that shows the head's diff places a thread at `current` and shows the others with their `diffHunk`; reading the file at `original.commit` through `fileText` shows the whole file the thread was written on. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) owns how GitHub's fields map onto these positions.
`ctx.forge.readReview(ref, headSha, signal)` reads the review threads of a change request at one head commit. The provider returns `ForgeReviewData` only when the read names `headSha` as the head; otherwise it returns `stale`, which polls a watched change request again at once, as a stale diff read does. For a provider without `readReview` the service returns `unsupported`, so consumers show no threads instead of a failure. A line thread has two positions: `original` on the commit it was written on, and `current` on the head of the read, which is null once the host no longer places the thread on that commit. A consumer that shows the head's diff places a thread at `current` and shows the others with their `diffHunk`; reading the file at `original.commit` through `fileText` shows the whole file the thread was written on. The [GitHub provider README](../../packages/experimental/forge-github/README.md#use-this-package) and the [GitLab provider README](../../packages/experimental/forge-gitlab/README.md#use-this-package) own how each host's fields map onto these positions; GitLab keeps only the last position a thread's lines were unchanged at, which becomes its `original`.
```ts type-equiv
/** Opaque host identity of one review thread. */
@@ -474,9 +506,9 @@ interface ForgeReviewComment {
```ts type-equiv
/**
* One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was
* written on, and `current` on the head commit of the read. `current` is null once the host no longer places the
* thread on the head commit, as after later commits changed its lines.
* One review thread on a file of a change request. A line thread has two positions: `original` on a commit whose file
* holds the thread's lines as they were written, and `current` on the head commit of the read. `current` is null once
* the host no longer places the thread on the head commit, as after later commits changed its lines.
*/
interface ForgeReviewThread {
/** Host identity of the thread. */
@@ -489,7 +521,11 @@ interface ForgeReviewThread {
readonly subject: 'line' | 'file'
/** Lines in the diff that ends at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */
readonly current: ForgeAnchor | null
/** Lines in the diff that ended at the commit the thread was written on; null for a file thread. */
/**
* Lines in the diff that ended at a commit whose file holds the lines as the thread was written on them: the commit
* the thread was written on, or a later one the host carried the thread to while the lines stayed unchanged; null for
* a file thread.
*/
readonly original: ForgeAnchor | null
/** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */
readonly diffHunk: string | null
@@ -525,6 +561,11 @@ interface ForgeReviewData {
* false for a provider without it.
*/
readonly viewerCanReview: boolean
/**
* Decisions the host lets the signed-in user record in a submitted review of this change request, such as only
* `comment` on their own pull request on GitHub; empty when `viewerCanReview` is false.
*/
readonly reviewEvents: readonly ForgeReviewEvent[]
}
```
@@ -711,15 +752,14 @@ interface ForgeViewedRequest {
## Session bindings
`ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they 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.
`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.
```ts type-equiv
/**
* How a change request became bound to a Session: `created` when a
* `gh pr create` result printed its URL, `referenced` when a `gh pr view`,
* `gh pr edit`, or `gh pr checkout` call named it or its result printed its
* own URL, `discovered` when a lookup found it for a branch the Session pushed
* or works on, `tracked` when a caller bound it by URL.
* How a change request became bound to a Session: `created` when the result of a command a registered rule names as a
* creation printed its URL, `referenced` when a command a rule names as a reference named it, its result printed its
* own URL, or a lookup for it found the URL, `discovered` when a lookup found it for a branch the Session pushed or
* works on, `tracked` when a caller bound it by URL.
*/
type BindingOrigin = 'created' | 'referenced' | 'discovered' | 'tracked'
```
@@ -729,7 +769,7 @@ type BindingOrigin = 'created' | 'referenced' | 'discovered' | 'tracked'
interface BindingRecord {
/**
* `track` binds or restores, `dismiss` hides, `discover` binds a branch lookup,
* and `reference` binds a CLI selector lookup without restoring dismissed entries.
* and `reference` binds a command lookup without restoring dismissed entries.
*/
readonly action: 'track' | 'dismiss' | 'discover' | 'reference'
/** Web URL of the change request. */
@@ -759,6 +799,84 @@ interface SessionChangeRequest {
type SessionChangeRequestsListener = (changeRequests: readonly SessionChangeRequest[]) => void
```
Providers register the commands of their CLI with `registerCommands`; the [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns how the projection folds with them.
```ts type-equiv
/**
* The shell commands of one forge family's CLI that bind change requests to the Session that ran them, registered
* with `ctx.forgeSession.registerCommands`. The `forgeChangeRequests` projection folds the Session log with the
* recognized rules and folds it again when a registration changes them, so a rule must classify the same input the
* same way every time: its members are fixed, and `select` reads only its arguments.
*/
interface ForgeCommandRule {
/** Stable name of the rule, such as `gh`; no two registered rules share one. */
readonly id: string
/** Positive integer the registrant raises whenever the rule classifies some command or output differently. */
readonly version: number
/** Executable word the rule classifies, such as `gh`; no two registered rules share one. */
readonly executable: string
/** Subcommand word sequences that create a change request and print its URL, such as `['pr', 'create']`. */
readonly creates: readonly (readonly string[])[]
/** Subcommands that act on one change request, which their words or their output name, such as `['pr', 'view']`. */
readonly references: ForgeCommandGroup
/**
* Subcommands that send a raw API request, such as `['api']`, whose words can name one change request. Their output
* is not read, since one request can list many change requests.
*/
readonly apiRequests: ForgeCommandGroup
/** Regular expression source matching a change request page path after the repository path, such as `\/pull\/\d+`. */
readonly changeRequestPath: string
/** JSON member names whose value is the URL of the change request a reference command prints, such as `url`. */
readonly urlMembers: readonly string[]
/**
* Find the change request that one literal reference or API request command names.
* @param command - the command's kind, subcommand, operands, and option values.
* @param environment - the variables the command assigns before the executable, the last assignment of a name winning.
* @returns the change request's URL when the command names its host; a lookup when it names the change request
* without one; undefined when it names no change request.
*/
select(command: ForgeCommandArguments, environment: Readonly<Record<string, string>>): ForgeCommandSelection | undefined
}
```
```ts type-equiv
/** Subcommands of one kind and the options they accept. */
interface ForgeCommandGroup {
/** Subcommand word sequences, such as `['pr', 'view']`; may be empty. */
readonly subcommands: readonly (readonly string[])[]
/**
* Options that take a value: the next word, the text after `=`, or for a one-letter option such as `-R`, the rest of
* the word.
*/
readonly valueOptions: readonly string[]
/** Options that take no value; a command with any other option names nothing. */
readonly flagOptions: readonly string[]
}
```
```ts type-equiv
/** The parsed words of one reference or API request command after its executable. */
interface ForgeCommandArguments {
/** Which group of the rule the subcommand belongs to. */
readonly kind: 'reference' | 'api-request'
/** The subcommand words, such as `['pr', 'view']`. */
readonly subcommand: readonly string[]
/** Words after the subcommand that are neither options nor option values. */
readonly operands: readonly string[]
/** Each value option as written, with its value, in command order. */
readonly values: readonly (readonly [option: string, value: string])[]
}
```
```ts type-equiv
/**
* The change request one command names: its URL, or a read-only command, starting with the executable, that prints
* exactly that URL. forge-session runs a lookup in the shell of the command that named it, with that command's
* variable assignments, and only while the command runs; replaying the Session log runs none.
*/
type ForgeCommandSelection = { readonly url: string } | { readonly lookup: readonly string[] }
```
## Panel
`ctx.forgePanel` is the Host Remote of the [forge panel](../../packages/experimental/client-ui-forge/README.md#use-this-package). Following a Session streams a `ForgePanelState`: a read-only Git inspection of the Session's current directory in its execution world, the code host recognized from the upstream remote or `origin`, the sign-in state of that host, the Session's bindings with their polled status and last snapshot, and its worktree request. Its actions list base branches, bind and hide URLs, refresh, mark a bound draft ready or merge a bound change request, request or withdraw a worktree, stop a running creation, and restore a removed worktree or leave it for the source checkout. A request is a `plugin:client-ui-forge/worktree` record. When a message enters a Session's inbox while its Agent is idle, the panel holds the message's turn with maintenance of the [Agent](../../packages/core/agent/README.md), started before the delivery wakes the Agent: it creates the worktree of an open request through `ctx.worktrees` and, after a failed or stopped attempt, waits for another attempt or the request's withdrawal; for a Session that works in its created worktree it checks that worktree and, when it is gone, waits until it is restored or left. The panel state names what a message waits for and the last failed attempt. The first step proposal creates the worktree for a message no hold took. Requests after the first turn starts are ignored. Changes to a Session's checkout run as maintenance of its Agent, so a message from another client waits for them.
@@ -932,6 +1050,8 @@ interface ForgePanelWorktree {
```ts type-equiv
/** One bound change request in the panel state. */
interface ForgePanelChangeRequest extends SessionChangeRequest {
/** How readers name the change request's code host and its change requests, or null when no provider serves its URL. */
readonly forge: ForgeDescription | null
/** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */
readonly snapshot: ChangeRequestSnapshot | null
/**
@@ -1332,21 +1452,28 @@ Registry of forge providers. Watchers of one change request share a single polli
* fiber. Watches of that forge receive an `unavailable` failure when the
* registration ends. Unregistering cancels and awaits its in-flight calls;
* results from the withdrawn registration are discarded.
* @param provider - provider to serve `provider.forge`.
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
* @returns the disposer that unregisters the provider and waits for its calls to finish.
* @throws when another provider already serves the same forge.
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
*/
register(provider: ForgeProvider): () => Promise<void>
/**
* Map a Git remote URL to a repository through the first provider that serves it.
* Name a forge family and its change requests for readers.
* @param forge - forge family name, such as `github`.
* @returns the registered provider's description, or undefined when no provider serves the family.
*/
describe(forge: string): ForgeDescription | undefined
/**
* Map a Git remote URL to a repository through the provider that serves its host.
* @param url - fetch or push URL as Git reports it.
* @returns the repository, or undefined when no provider serves the URL.
*/
repositoryFromRemote(url: string): ForgeRepository | undefined
/**
* Map a change request web URL through the first provider that serves it.
* Map a change request web URL through the provider that serves its host.
* @param url - web URL of a pull or merge request.
* @returns the change request, or undefined when no provider serves the URL.
*/
@@ -2066,9 +2193,28 @@ Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/ex
### `ctx.forgeSession` — `ForgeSessionService`
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from the results of the creation and reference commands that forge providers register through `registerCommands`, from `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
```ts cordis-catalog
/**
* Register the commands of one forge CLI as an effect on the calling fiber.
* A rule that changes the recognized rule set re-registers the
* `forgeChangeRequests` projection at the new set's state version, so every
* Session refolds its log with the new rules when next read, including
* commands that ran before the registration, and watchers receive the
* refolded bindings. Disposal does not change the recognized set: the rule
* keeps recognizing commands until the service restarts or another rule
* replaces its id or executable, so unloading a provider, including at
* shutdown, leaves the checkpointed state version unchanged. Only live
* registrations run reference lookups, so a disposed rule starts no CLI
* process; lookups that started before a change finish with the rules they
* started with.
* @param rule - the CLI's executable, subcommands, change request page path, and selection.
* @returns the disposer that ends the registration.
* @throws when the rule is malformed, or a live registration has its id or executable.
*/
registerCommands(rule: ForgeCommandRule): () => void
/**
* List the change requests bound to a Session and not dismissed.
* @param session - Session whose bindings are read.
+168 -22
View File
@@ -2,11 +2,11 @@
[English](forge.md) | 中文
实验性的 forge 能力 seam 从代码托管平台读取变更请求(change request,即 pull request 与 merge request)。[`dsh-experimental-forge`](../../packages/experimental/forge/README.zh.md) 是 Service Definition,提供 `ctx.forge`;[`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.zh.md) 是服务 GitHub 主机的 Service Provider;[`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.zh.md) 是把变更请求绑定到 Session 的 Consumer,提供 `ctx.forgeSession`;[`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.zh.md) 是提供 `ctx.forgePanel` 的 GUI Consumer。默认禁用的 [forge Bundle](../../packages/experimental/forge-bundle/README.zh.md) 可从插件页面组合这四个包,同时加载[工作树模型工具](../../packages/experimental/tool-worktree/README.zh.md),并为面板附带一个隔离的 [worktree 服务](../../packages/experimental/worktree/README.zh.md);除此之外,它们只能通过显式组合加载。
实验性的 forge 能力 seam 从代码托管平台读取变更请求(change request,即 pull request 与 merge request)。[`dsh-experimental-forge`](../../packages/experimental/forge/README.zh.md) 是 Service Definition,提供 `ctx.forge`;[`dsh-experimental-forge-github`](../../packages/experimental/forge-github/README.zh.md) 与 [`dsh-forge-gitlab`](../../packages/experimental/forge-gitlab/README.zh.md) 是服务 GitHub 与 GitLab 主机的 Service Provider;[`dsh-experimental-forge-session`](../../packages/experimental/forge-session/README.zh.md) 是把变更请求绑定到 Session 的 Consumer,提供 `ctx.forgeSession`;[`dsh-experimental-client-ui-forge`](../../packages/experimental/client-ui-forge/README.zh.md) 是提供 `ctx.forgePanel` 的 GUI Consumer。默认禁用的 [forge Bundle](../../packages/experimental/forge-bundle/README.zh.md) 可从插件页面组合这五个包,同时加载[工作树模型工具](../../packages/experimental/tool-worktree/README.zh.md),并为面板附带一个隔离的 [worktree 服务](../../packages/experimental/worktree/README.zh.md);除此之外,它们只能通过显式组合加载。
## 提供方与变更请求
一个提供方服务一个 forge 家族,例如 `github`。它把 Git 远端 URL 映射为仓库,把变更请求 URL 映射为引用,构造规范的变更请求 URL,按 head 分支查找打开状态的变更请求,并批量读取状态。`changeRequestKey` 从引用派生一个不区分大小写的键,因此 URL 拼写不同的监听方共享同一个轮询循环。
一个提供方在其 `hosts` 列出的主机上服务一个 forge 家族,例如 `github`;任意两个已注册的提供方不能列出同一主机,因此每个远端和变更请求 URL 至多对应一个提供方。它把 Git 远端 URL 映射为仓库,把变更请求 URL 映射为引用,构造规范的变更请求 URL,按 head 分支查找打开状态的变更请求,并批量读取状态。`changeRequestKey` 从引用派生一个不区分大小写的键,因此 URL 拼写不同的监听方共享同一个轮询循环。
```ts type-equiv
/** One repository on a code host, identified the way its provider addresses it. */
@@ -40,11 +40,20 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'>
```ts type-equiv
/**
* Host-specific access registered with `ctx.forge`. One provider serves one
* forge family; methods that take a signal must stop work when it aborts.
* forge family on the hosts it lists; methods that take a signal must stop work when it aborts.
*/
interface ForgeProvider {
/** Forge family name stored in every repository this provider returns. */
readonly forge: string
/**
* Lowercase host names this provider serves, such as `github.com`; `repositoryFromRemote` and `changeRequestFromUrl`
* return only these hosts, and no other registered provider may list one of them.
*/
readonly hosts: readonly string[]
/** Product name readers know this provider's hosts by, such as `GitHub`. */
readonly label: string
/** What this provider's hosts call a change request. */
readonly changeRequestNoun: ChangeRequestNoun
/** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */
submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise<ForgeReviewResult>
/**
@@ -135,8 +144,10 @@ interface ForgeProvider {
reviewerCandidates?(ref: ChangeRequestRef, query: string, signal: AbortSignal): Promise<readonly ForgeReviewerCandidate[] | ForgeFailure>
/**
* Bring the base branch's new commits into the head branch while its head is still `request.headSha`, resolving to
* undefined once the host accepted the update. Omission declares that the provider updates no branches, and its
* snapshots then offer no `branchUpdates`.
* undefined once the host accepted the update. A host whose update names the expected head checks it with the update;
* for one whose update cannot, the provider reads the head just before it, so a push between the read and the update
* is updated too. Omission declares that the provider updates no branches, and its snapshots then offer no
* `branchUpdates`.
*/
updateBranch?(ref: ChangeRequestRef, request: BranchUpdateRequest, signal: AbortSignal): Promise<ForgeActionFailure | undefined>
}
@@ -179,6 +190,27 @@ interface ForgeReadiness {
readonly state: 'ready' | 'unauthenticated' | 'unavailable'
/** Human-readable detail, or null when ready. */
readonly message: string | null
/** Shell command the user runs on the host to sign in, while `unauthenticated`; null otherwise or when the provider names none. */
readonly signIn: { readonly command: string } | null
}
```
`ctx.forge.describe(forge)` 用已注册家族的提供方声明的 `label` 与 `changeRequestNoun` 称呼该家族,读者因此可以按托管平台自己的叫法称呼平台及其变更请求。
```ts type-equiv
/** What the hosts of a forge family call a change request. */
type ChangeRequestNoun = 'pull-request' | 'merge-request'
```
```ts type-equiv
/** How readers name a forge family and its change requests. */
interface ForgeDescription {
/** Forge family name, such as `github`. */
readonly forge: string
/** Product name readers know the family's hosts by, such as `GitHub`. */
readonly label: string
/** What the family's hosts call a change request. */
readonly changeRequestNoun: ChangeRequestNoun
}
```
@@ -411,7 +443,7 @@ type ForgeReviewResult =
## 评审讨论
`ctx.forge.readReview(ref, headSha, signal)` 读取变更请求在某个 head 提交处的评审讨论。只有当读取时的 head 就是 `headSha` 时,提供方才返回 `ForgeReviewData`;否则返回 `stale`,并像 diff 读取遇到 `stale` 时一样,立即重新轮询被关注的变更请求。提供方没有实现 `readReview` 时,服务返回 `unsupported`,使用方据此不显示讨论,也不报错。行级讨论有两套位置:`original` 是写下讨论时所在提交上的行,`current` 是本次读取的 head 上的行;托管平台不再把讨论放在该提交上时,`current` 为 null。显示 head diff 的使用方把讨论放在 `current` 位置,其余讨论用 `diffHunk` 展示;用 `fileText` 读取 `original.commit` 上的文件,可以看到写下讨论时的完整文件。GitHub 各字段如何映射到这两套位置,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 说明。
`ctx.forge.readReview(ref, headSha, signal)` 读取变更请求在某个 head 提交处的评审讨论。只有当读取时的 head 就是 `headSha` 时,提供方才返回 `ForgeReviewData`;否则返回 `stale`,并像 diff 读取遇到 `stale` 时一样,立即重新轮询被关注的变更请求。提供方没有实现 `readReview` 时,服务返回 `unsupported`,使用方据此不显示讨论,也不报错。行级讨论有两套位置:`original` 是写下讨论时所在提交上的行,`current` 是本次读取的 head 上的行;托管平台不再把讨论放在该提交上时,`current` 为 null。显示 head diff 的使用方把讨论放在 `current` 位置,其余讨论用 `diffHunk` 展示;用 `fileText` 读取 `original.commit` 上的文件,可以看到写下讨论时的完整文件。各平台的字段如何映射到这两套位置,由 [GitHub 提供方 README](../../packages/experimental/forge-github/README.zh.md#use-this-package) 与 [GitLab 提供方 README](../../packages/experimental/forge-gitlab/README.zh.md#use-this-package) 说明;GitLab 只保留讨论所在行保持不变的最后一个位置,它即成为讨论的 `original`。
```ts type-equiv
/** Opaque host identity of one review thread. */
@@ -474,9 +506,9 @@ interface ForgeReviewComment {
```ts type-equiv
/**
* One review thread on a file of a change request. A line thread has two positions: `original` on the commit it was
* written on, and `current` on the head commit of the read. `current` is null once the host no longer places the
* thread on the head commit, as after later commits changed its lines.
* One review thread on a file of a change request. A line thread has two positions: `original` on a commit whose file
* holds the thread's lines as they were written, and `current` on the head commit of the read. `current` is null once
* the host no longer places the thread on the head commit, as after later commits changed its lines.
*/
interface ForgeReviewThread {
/** Host identity of the thread. */
@@ -489,7 +521,11 @@ interface ForgeReviewThread {
readonly subject: 'line' | 'file'
/** Lines in the diff that ends at the head commit of the read, whose `commit` is that head; null for an outdated or file thread. */
readonly current: ForgeAnchor | null
/** Lines in the diff that ended at the commit the thread was written on; null for a file thread. */
/**
* Lines in the diff that ended at a commit whose file holds the lines as the thread was written on them: the commit
* the thread was written on, or a later one the host carried the thread to while the lines stayed unchanged; null for
* a file thread.
*/
readonly original: ForgeAnchor | null
/** Diff hunk the host recorded when the thread was written, ending at its last line; null when it recorded none. */
readonly diffHunk: string | null
@@ -525,6 +561,11 @@ interface ForgeReviewData {
* false for a provider without it.
*/
readonly viewerCanReview: boolean
/**
* Decisions the host lets the signed-in user record in a submitted review of this change request, such as only
* `comment` on their own pull request on GitHub; empty when `viewerCanReview` is false.
*/
readonly reviewEvents: readonly ForgeReviewEvent[]
}
```
@@ -713,15 +754,14 @@ interface ForgeViewedRequest {
## Session 绑定
`ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`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)。
`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)。
```ts type-equiv
/**
* How a change request became bound to a Session: `created` when a
* `gh pr create` result printed its URL, `referenced` when a `gh pr view`,
* `gh pr edit`, or `gh pr checkout` call named it or its result printed its
* own URL, `discovered` when a lookup found it for a branch the Session pushed
* or works on, `tracked` when a caller bound it by URL.
* How a change request became bound to a Session: `created` when the result of a command a registered rule names as a
* creation printed its URL, `referenced` when a command a rule names as a reference named it, its result printed its
* own URL, or a lookup for it found the URL, `discovered` when a lookup found it for a branch the Session pushed or
* works on, `tracked` when a caller bound it by URL.
*/
type BindingOrigin = 'created' | 'referenced' | 'discovered' | 'tracked'
```
@@ -731,7 +771,7 @@ type BindingOrigin = 'created' | 'referenced' | 'discovered' | 'tracked'
interface BindingRecord {
/**
* `track` binds or restores, `dismiss` hides, `discover` binds a branch lookup,
* and `reference` binds a CLI selector lookup without restoring dismissed entries.
* and `reference` binds a command lookup without restoring dismissed entries.
*/
readonly action: 'track' | 'dismiss' | 'discover' | 'reference'
/** Web URL of the change request. */
@@ -761,6 +801,84 @@ interface SessionChangeRequest {
type SessionChangeRequestsListener = (changeRequests: readonly SessionChangeRequest[]) => void
```
提供方通过 `registerCommands` 注册其 CLI 的命令;投影如何据此折叠见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。
```ts type-equiv
/**
* The shell commands of one forge family's CLI that bind change requests to the Session that ran them, registered
* with `ctx.forgeSession.registerCommands`. The `forgeChangeRequests` projection folds the Session log with the
* recognized rules and folds it again when a registration changes them, so a rule must classify the same input the
* same way every time: its members are fixed, and `select` reads only its arguments.
*/
interface ForgeCommandRule {
/** Stable name of the rule, such as `gh`; no two registered rules share one. */
readonly id: string
/** Positive integer the registrant raises whenever the rule classifies some command or output differently. */
readonly version: number
/** Executable word the rule classifies, such as `gh`; no two registered rules share one. */
readonly executable: string
/** Subcommand word sequences that create a change request and print its URL, such as `['pr', 'create']`. */
readonly creates: readonly (readonly string[])[]
/** Subcommands that act on one change request, which their words or their output name, such as `['pr', 'view']`. */
readonly references: ForgeCommandGroup
/**
* Subcommands that send a raw API request, such as `['api']`, whose words can name one change request. Their output
* is not read, since one request can list many change requests.
*/
readonly apiRequests: ForgeCommandGroup
/** Regular expression source matching a change request page path after the repository path, such as `\/pull\/\d+`. */
readonly changeRequestPath: string
/** JSON member names whose value is the URL of the change request a reference command prints, such as `url`. */
readonly urlMembers: readonly string[]
/**
* Find the change request that one literal reference or API request command names.
* @param command - the command's kind, subcommand, operands, and option values.
* @param environment - the variables the command assigns before the executable, the last assignment of a name winning.
* @returns the change request's URL when the command names its host; a lookup when it names the change request
* without one; undefined when it names no change request.
*/
select(command: ForgeCommandArguments, environment: Readonly<Record<string, string>>): ForgeCommandSelection | undefined
}
```
```ts type-equiv
/** Subcommands of one kind and the options they accept. */
interface ForgeCommandGroup {
/** Subcommand word sequences, such as `['pr', 'view']`; may be empty. */
readonly subcommands: readonly (readonly string[])[]
/**
* Options that take a value: the next word, the text after `=`, or for a one-letter option such as `-R`, the rest of
* the word.
*/
readonly valueOptions: readonly string[]
/** Options that take no value; a command with any other option names nothing. */
readonly flagOptions: readonly string[]
}
```
```ts type-equiv
/** The parsed words of one reference or API request command after its executable. */
interface ForgeCommandArguments {
/** Which group of the rule the subcommand belongs to. */
readonly kind: 'reference' | 'api-request'
/** The subcommand words, such as `['pr', 'view']`. */
readonly subcommand: readonly string[]
/** Words after the subcommand that are neither options nor option values. */
readonly operands: readonly string[]
/** Each value option as written, with its value, in command order. */
readonly values: readonly (readonly [option: string, value: string])[]
}
```
```ts type-equiv
/**
* The change request one command names: its URL, or a read-only command, starting with the executable, that prints
* exactly that URL. forge-session runs a lookup in the shell of the command that named it, with that command's
* variable assignments, and only while the command runs; replaying the Session log runs none.
*/
type ForgeCommandSelection = { readonly url: string } | { readonly lookup: readonly string[] }
```
## 面板
`ctx.forgePanel` 是 [forge 面板](../../packages/experimental/client-ui-forge/README.zh.md#use-this-package)的宿主 Remote。跟随一个 Session 时,它以流的形式推送 `ForgePanelState`:在 Session 执行环境中对其当前目录进行的只读 Git 检查、从上游远端或 `origin` 识别出的代码托管平台、该平台的登录状态、Session 的绑定及其轮询状态与最近的快照,以及它的 worktree 请求。它的操作可以列出基准分支、绑定和隐藏 URL、刷新、把已绑定的草稿标记为可评审或合并已绑定的变更请求、请求或撤回 worktree、停止正在进行的创建,以及恢复已删除的 worktree 或离开它回到源检出。请求是一条 `plugin:client-ui-forge/worktree` 记录。消息在 Session 的 Agent 空闲时进入其收件箱,面板会在这次投递唤醒 [Agent](../../packages/core/agent/README.zh.md) 之前启动它的维护任务,暂留这条消息的这一轮:对未完成的请求,它通过 `ctx.worktrees` 创建 worktree,尝试失败或被停止后等待下一次尝试或请求被撤回;对在所创建 worktree 中工作的 Session,它检查该 worktree,已被删除时等待它被恢复或离开。面板状态说明消息在等待什么,以及最近一次失败的尝试。对于没有被暂留的消息,由第一个步骤提议创建 worktree。第一轮开始之后的请求会被忽略。对 Session 检出的改动以其 Agent 的维护任务运行,因此其他客户端发来的消息会等它们完成。
@@ -934,6 +1052,8 @@ interface ForgePanelWorktree {
```ts type-equiv
/** One bound change request in the panel state. */
interface ForgePanelChangeRequest extends SessionChangeRequest {
/** How readers name the change request's code host and its change requests, or null when no provider serves its URL. */
readonly forge: ForgeDescription | null
/** Latest snapshot a poll returned, kept while later polls fail, or null before the first successful poll. */
readonly snapshot: ChangeRequestSnapshot | null
/**
@@ -1334,21 +1454,28 @@ Registry of forge providers. Watchers of one change request share a single polli
* fiber. Watches of that forge receive an `unavailable` failure when the
* registration ends. Unregistering cancels and awaits its in-flight calls;
* results from the withdrawn registration are discarded.
* @param provider - provider to serve `provider.forge`.
* @param provider - provider to serve `provider.forge` on `provider.hosts`.
* @returns the disposer that unregisters the provider and waits for its calls to finish.
* @throws when another provider already serves the same forge.
* @throws when another provider already serves the same forge or one of the same hosts, compared without case.
*/
register(provider: ForgeProvider): () => Promise<void>
/**
* Map a Git remote URL to a repository through the first provider that serves it.
* Name a forge family and its change requests for readers.
* @param forge - forge family name, such as `github`.
* @returns the registered provider's description, or undefined when no provider serves the family.
*/
describe(forge: string): ForgeDescription | undefined
/**
* Map a Git remote URL to a repository through the provider that serves its host.
* @param url - fetch or push URL as Git reports it.
* @returns the repository, or undefined when no provider serves the URL.
*/
repositoryFromRemote(url: string): ForgeRepository | undefined
/**
* Map a change request web URL through the first provider that serves it.
* Map a change request web URL through the provider that serves its host.
* @param url - web URL of a pull or merge request.
* @returns the change request, or undefined when no provider serves the URL.
*/
@@ -2068,9 +2195,28 @@ Source: [`packages/experimental/client-ui-forge/src/index.ts`](../../packages/ex
### `ctx.forgeSession` — `ForgeSessionService`
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from `gh pr create`, `gh pr view`, `gh pr edit`, `gh pr checkout`, and `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
Session-scoped change request bindings. The `forgeChangeRequests` projection derives them from the results of the creation and reference commands that forge providers register through `registerCommands`, from `git push` results, including those of shell calls inside PTC programs, and from `plugin:forge-session/binding` records. After each push result, and when a caller reports the branch a Session works on, the service looks up open change requests whose head is that branch and records the unbound ones as discovered. Watching a Session polls its visible change requests through `ctx.forge`.
```ts cordis-catalog
/**
* Register the commands of one forge CLI as an effect on the calling fiber.
* A rule that changes the recognized rule set re-registers the
* `forgeChangeRequests` projection at the new set's state version, so every
* Session refolds its log with the new rules when next read, including
* commands that ran before the registration, and watchers receive the
* refolded bindings. Disposal does not change the recognized set: the rule
* keeps recognizing commands until the service restarts or another rule
* replaces its id or executable, so unloading a provider, including at
* shutdown, leaves the checkpointed state version unchanged. Only live
* registrations run reference lookups, so a disposed rule starts no CLI
* process; lookups that started before a change finish with the rules they
* started with.
* @param rule - the CLI's executable, subcommands, change request page path, and selection.
* @returns the disposer that ends the registration.
* @throws when the rule is malformed, or a live registration has its id or executable.
*/
registerCommands(rule: ForgeCommandRule): () => void
/**
* List the change requests bound to a Session and not dismissed.
* @param session - Session whose bindings are read.
@@ -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.3/forge-command-rules/guide.md
/:
en: 07b8a3b72e028278
zh: 3e976865cbeae2fa
/forge-providers-register-the-commands-that-bind-change-requests:
en: 1cd94d0f8b2f2419
zh: d78a94516aad67d2
/forge-providers-register-the-commands-that-bind-change-requests/change:
en: bdcd520b855a0b49
zh: 7c2237400cce6b4f
/forge-providers-register-the-commands-that-bind-change-requests/migration:
en: 36618d08e8647e63
zh: fa83f0c3ad6ed020
@@ -0,0 +1,22 @@
---
kind: upgrade-guide
description: "forge-session no longer recognizes gh commands by itself; forge providers register the commands that bind change requests, and existing forgeChangeRequests checkpoints fold again once."
---
# Forge providers register the commands that bind change requests
English | [中文](guide.zh.md)
## Change
`@deepseek-ai/dsh-experimental-forge-session` used to recognize `gh pr create`, `gh pr view`, `gh pr edit`, and `gh pr checkout` by itself. It now recognizes only the commands that forge providers register through `ctx.forgeSession.registerCommands(rule)`: `@deepseek-ai/dsh-experimental-forge-github` registers `gh`, and `@deepseek-ai/dsh-forge-gitlab` registers `glab`. A composition that loads forge-session without forge-github no longer binds pull requests from `gh` commands; `git push` discovery, `track`, and recorded bindings are unchanged. Once a rule registers, each Session's earlier commands bind as well.
The `forgeChangeRequests` projection's state version now derives from the registered rules, so every checkpointed row from an earlier release is discarded once: each Session folds its log again when next read, and until then the Session list shows no cached bindings for it. Bindings are not lost. The `gh` lookup for a number without a host now runs `gh pr view <number> --repo <repository> --json url --jq .url`.
This affects custom `cordis.yml` compositions and code that registers command rules. The forge bundle loads both providers and needs no change.
## Migration
1. In a composition that loads forge-session, also load `@deepseek-ai/dsh-experimental-forge-github` for `gh` commands, `@deepseek-ai/dsh-forge-gitlab` for `glab` commands, or both.
2. To bind the commands of another CLI, register a `ForgeCommandRule` with `ctx.forgeSession.registerCommands` from a plugin that injects `forgeSession`, as [`packages/experimental/forge-github/src/commands.ts`](../../../../packages/experimental/forge-github/src/commands.ts) does, and raise its `version` whenever it classifies any command differently.
3. Open a Session that ran `gh pr create`; the migration works when the forge panel lists the pull request that command printed.
@@ -0,0 +1,22 @@
---
kind: upgrade-guide
description: "forge-session 不再自行识别 gh 命令;由 forge 提供方注册绑定变更请求的命令,已有的 forgeChangeRequests 检查点会重新折叠一次。"
---
# Forge 提供方注册绑定变更请求的命令
[English](guide.md) | 中文
## 变更
`@deepseek-ai/dsh-experimental-forge-session` 过去自行识别 `gh pr create`、`gh pr view`、`gh pr edit` 与 `gh pr checkout`。现在它只识别 forge 提供方通过 `ctx.forgeSession.registerCommands(rule)` 注册的命令:`@deepseek-ai/dsh-experimental-forge-github` 注册 `gh`,`@deepseek-ai/dsh-forge-gitlab` 注册 `glab`。加载 forge-session 但不加载 forge-github 的组合,不再从 `gh` 命令绑定 pull request;`git push` 发现、`track` 与已记录的绑定不变。规则注册后,每个 Session 此前执行过的命令同样会绑定。
`forgeChangeRequests` 投影的状态版本现由已注册的规则派生,因此此前版本检查点中的每一行都会被丢弃一次:每个 Session 下次被读取时重新折叠其日志,在此之前 Session 列表不显示它的缓存绑定。绑定不会丢失。对未写明主机的编号,`gh` 查询现在执行 `gh pr view <number> --repo <repository> --json url --jq .url`。
受影响的是自定义 `cordis.yml` 组合与注册命令规则的代码。forge 套件会加载两个提供方,无需改动。
## 迁移
1. 在加载 forge-session 的组合中,同时加载 `@deepseek-ai/dsh-experimental-forge-github` 以识别 `gh` 命令、加载 `@deepseek-ai/dsh-forge-gitlab` 以识别 `glab` 命令,或两者都加载。
2. 若要绑定其他 CLI 的命令,像 [`packages/experimental/forge-github/src/commands.ts`](../../../../packages/experimental/forge-github/src/commands.ts) 那样,从注入 `forgeSession` 的插件中通过 `ctx.forgeSession.registerCommands` 注册一条 `ForgeCommandRule`,并在其对任何命令的分类发生变化时提高 `version`。
3. 打开一个执行过 `gh pr create` 的 Session;forge 面板列出该命令打印的 pull request 时,迁移即已生效。
@@ -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.3/forge-provider-hosts/guide.md
/:
en: 7a694c15b528d821
zh: bceb9c2829c09bf8
/forge-providers-declare-hosts-names-sign-in-and-review-decisions:
en: e876851b5e7ef5b5
zh: 50314894e615738b
/forge-providers-declare-hosts-names-sign-in-and-review-decisions/change:
en: 8795de8b80f1385c
zh: e1c7308d3c762198
/forge-providers-declare-hosts-names-sign-in-and-review-decisions/migration:
en: 7b2abf659941fc7f
zh: 9c934740f791f0f0
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "ForgeProvider must list its hosts and name itself, ForgeReadiness carries a sign-in command, and ForgeReviewData lists the review decisions the reader may submit."
---
# Forge providers declare hosts, names, sign-in, and review decisions
English | [中文](guide.zh.md)
## Change
`ForgeProvider` gains three required members: `hosts`, the lowercase host names the provider serves; `label`, the product name readers know those hosts by, such as `GitHub`; and `changeRequestNoun`, `'pull-request'` or `'merge-request'`. `ctx.forge.register` now throws when a provider lists a host, compared without case, that an already registered provider lists. `ctx.forge.describe(forge)` returns the `ForgeDescription` the panel uses to name the code host in its copy.
`ForgeReadiness` gains the required `signIn: { command } | null`. The forge panel shows that command in its sign-in banner instead of building `gh auth login` for the `github` family itself.
`ForgeReviewData` gains the required `reviewEvents`, the decisions the host lets the signed-in user record in a submitted review. The review dialog offers only these, replacing its own rule that the author of a pull request may only comment.
This affects third-party providers and code that builds these values. All types come from `@deepseek-ai/dsh-experimental-forge`. The GitHub provider sets `hosts` from its `hosts` setting, `label: 'GitHub'`, `changeRequestNoun: 'pull-request'`, `signIn` while `gh` is not signed in, and `['comment']` for the author of a pull request.
## Migration
1. Add `hosts`, `label`, and `changeRequestNoun` to each `ForgeProvider`. List every host whose remotes or change request URLs the provider maps, and make sure no other loaded provider lists one of them.
2. Return `signIn: null`, or `{ command }` with the shell command that signs the user in, from every `readiness` result.
3. Return `reviewEvents` from `readReview`: the decisions the signed-in user may submit, or `[]` when `viewerCanReview` is false.
4. Run your type check, then start a profile that loads your provider; it succeeds when the type check passes and `ctx.forge.register` does not throw.
@@ -0,0 +1,25 @@
---
kind: upgrade-guide
description: "ForgeProvider 必须列出所服务的主机并给出名称,ForgeReadiness 带有登录命令,ForgeReviewData 列出读者可提交的评审结论。"
---
# Forge 提供方声明主机、名称、登录方式与评审结论
[English](guide.md) | 中文
## 变更
`ForgeProvider` 新增三个必需成员:`hosts`,提供方服务的小写主机名;`label`,读者熟知的这些主机的产品名,例如 `GitHub`;`changeRequestNoun`,取值 `'pull-request'` 或 `'merge-request'`。提供方列出的主机(不区分大小写)已被另一个已注册的提供方列出时,`ctx.forge.register` 会抛出错误。`ctx.forge.describe(forge)` 返回 `ForgeDescription`,面板用它在文案中称呼代码托管平台。
`ForgeReadiness` 新增必需的 `signIn: { command } | null`。Forge 面板在登录提示中显示这条命令,不再自行为 `github` 家族拼出 `gh auth login`。
`ForgeReviewData` 新增必需的 `reviewEvents`,即托管平台允许当前用户在提交的评审中记录的结论。评审对话框只提供这些结论,取代它原先内置的规则:拉取请求的作者只能评论。
受影响的是第三方提供方,以及构造这些值的代码。所有类型都来自 `@deepseek-ai/dsh-experimental-forge`。GitHub 提供方按其 `hosts` 设置填写 `hosts`,`label` 为 `'GitHub'`,`changeRequestNoun` 为 `'pull-request'`,`gh` 未登录时给出 `signIn`,拉取请求的作者只得到 `['comment']`。
## 迁移
1. 为每个 `ForgeProvider` 添加 `hosts`、`label` 与 `changeRequestNoun`。列出提供方会映射其 remote 或变更请求 URL 的每个主机,并确认其他已加载的提供方没有列出其中任何一个。
2. 在每个 `readiness` 结果中返回 `signIn: null`,或带有登录 shell 命令的 `{ command }`。
3. 在 `readReview` 的结果中返回 `reviewEvents`:当前用户可以提交的结论;`viewerCanReview` 为 false 时返回 `[]`。
4. 运行类型检查,再启动加载你的提供方的 profile;类型检查通过且 `ctx.forge.register` 没有抛出错误即完成迁移。
@@ -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.3/settings-section-plugins-page/guide.md
/:
en: dab406781a6bcb3a
zh: 8d94c715bf9ec1b6
/built-in-plugins-section-removal:
en: 2483533f0eab34cf
zh: 9e7be97df303c363
/built-in-plugins-section-removal/change:
en: 513dfd0788a54e09
zh: 6b589f0dc07a85d7
/built-in-plugins-section-removal/migration:
en: b7d0c582c0bfd1cd
zh: ac670eb81450b9ef
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "Settings → Built-in plugins, its two packages, and the `settings.plugins.tab` slot are removed; plugin settings pages also appear on the Plugins page."
---
# Built-in plugins section removal
English | [中文](guide.zh.md)
## Change
**Settings → Built-in plugins** and its packages `@deepseek-ai/dsh-client-ui-settings-plugins` and `@deepseek-ai/dsh-client-ui-settings-plugin-inventory` are removed, together with the `settings.plugins.tab` slot and `SettingsPluginsTabOwnerProps`. **Settings → Plugins** opens the Plugins page instead. `settings.section` entries still appear in Settings. The Plugins page also shows an entry on the listed bundle row whose module is the registering package, or on that bundle's page, when the row or bundle registers no `plugins.row.config` or `plugins.bundle.config` of its own; there the entry's `close` returns to the view it was opened from instead of closing Settings. Both surfaces render entries through the `settings.section.view` Factory, which ui-settings-general registers and which declares `settings.section`.
## Migration
1. Remove both removed packages from profile manifests and from `cordis.yml` rows that name them.
2. Move any `settings.plugins.tab` contribution to a `settings.section` page or a Plugins page slot such as `plugins.bundle.config`.
3. A `settings.section` page whose `close()` call must leave Settings, such as after starting a Session, navigates there itself, because on the Plugins page `close()` only returns to the previous view.
4. Open the plugin's bundle on the Plugins page and confirm its settings page appears there, unless the row or bundle registers its own configuration, and in Settings.
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "删除「设置 → 内置插件」、它的两个包和 `settings.plugins.tab` slot;插件设置页同时出现在插件页面。"
---
# 删除内置插件分区
[English](guide.md) | 中文
## 变更
「设置 → 内置插件」及其包 `@deepseek-ai/dsh-client-ui-settings-plugins` 和 `@deepseek-ai/dsh-client-ui-settings-plugin-inventory` 已删除,`settings.plugins.tab` slot 和 `SettingsPluginsTabOwnerProps` 也一并删除。「设置 → 插件管理」改为打开插件页面。`settings.section` 条目仍显示在设置中。当模块与注册包相同的已列出 bundle 行、或该 bundle 本身没有注册自己的 `plugins.row.config` 或 `plugins.bundle.config` 时,插件页面也会在该行或该 bundle 页面上显示这个条目;在插件页面上,条目的 `close` 回到打开它的视图,而不是关闭设置。两处都通过 `settings.section.view` Factory 渲染条目,该 Factory 由 ui-settings-general 注册并声明 `settings.section`。
## 迁移
1. 从 profile manifest 和 `cordis.yml` 中删除指向这两个已删除包的条目。
2. 把 `settings.plugins.tab` 贡献改为 `settings.section` 页面,或 `plugins.bundle.config` 等插件页面 slot。
3. 调用 `close()` 后必须离开设置的 `settings.section` 页面(例如启动 Session 之后)需要自行导航,因为在插件页面上 `close()` 只回到上一个视图。
4. 在插件页面打开该插件的 bundle,确认其设置页出现在那里(该行或 bundle 注册了自己的配置时除外)和设置中。
+1
View File
@@ -309,6 +309,7 @@
"@deepseek-ai/dsh-experimental-tool-subagent-oar": "workspace:*",
"@deepseek-ai/dsh-experimental-forge": "workspace:*",
"@deepseek-ai/dsh-experimental-forge-github": "workspace:*",
"@deepseek-ai/dsh-forge-gitlab": "workspace:*",
"@deepseek-ai/dsh-experimental-forge-session": "workspace:*",
"@deepseek-ai/dsh-action-cards": "workspace:*"
}
@@ -15,8 +15,8 @@
en: 87679c51aa3693f5
zh: 11684a48a5806afb
/deepseek-ai-dsh-plugin-manager/use-this-package:
en: 9dba73eeabe9887f
zh: 19291d764da21077
en: ff51b012b845dd8a
zh: 1c6131057ff98844
/deepseek-ai-dsh-plugin-manager/use-this-package/version-compatibility-and-exemptions:
en: 483285658e267dd5
zh: 846bec2daac59a96
@@ -30,8 +30,8 @@
en: c224bfcb3eb3dbd2
zh: 8b9c96970a90dccc
/deepseek-ai-dsh-plugin-manager/further-exploration:
en: c6538243d8702a0d
zh: 04a82d923353c75f
en: b151a14acbf93f00
zh: f304e2ea5c7c7d0f
/deepseek-ai-dsh-plugin-manager/model-experience:
en: 215e7ba838619b7b
zh: a311da3843709f90
@@ -48,8 +48,8 @@
en: c29f60be7f3edc1a
zh: d9b9388b96ef95cc
/deepseek-ai-dsh-plugin-manager/known-limitations-and-deferred-work:
en: 89306b478cb75b3b
zh: f2f50c88114fec99
en: d8ea2d28e9e8c3e7
zh: 4efd7e073dde1b96
/deepseek-ai-dsh-plugin-manager/known-limitations-and-deferred-work/failure-behavior:
en: 3fde425e82bbd0f4
zh: 531e2365e7d67480
+2 -3
View File
@@ -28,7 +28,7 @@ Manage the current profile's plugins without editing configuration by hand. Enab
<a id="use-this-package"></a>
## Use this package
Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows; the Settings Plugin list stays read-only. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate.
Base-backed profiles provide the manager. In Web, the sidebar's **Plugins** page ([ui-plugin-manager](../../client/ui-plugin-manager/README.md)) manages the profile's bundles and their uniquely addressable rows. Agent-preset rows remain read-only. The `plugin_manager` tool exposes the same operations and is enabled in the Standard and Creator presets. Other Web presets keep it disabled by default. The full SDK profile enables it at profile scope in native/PTC mode; without HMR, saved changes return `restart-required` with `no-hmr` and apply after the runtime restarts. Every tool action requires `danger-full-access` or approval for that call. Under lower sandbox modes, `ask` requests approval; `never`, rejection, cancellation, or an unavailable approval channel prevents execution. An approval leaves the session permission mode unchanged. Profile changes persist across sessions, and installed Host code executes in-process outside the workspace sandbox. Dependency build-script approval remains separate.
For a deployment without agent presets other than the full SDK profile, enable the tool in the profile patch. Package installation/removal requires pnpm on `PATH` or an explicit `pnpmCommand`; a launcher-provided package manager takes precedence. Preset-backed sessions use their preset’s `tool-plugin-manager` entry.
@@ -143,7 +143,6 @@ The `@deepseek-ai/dsh-plugin-manager/diagnostic` entry supplies Desktop Host and
- [App boot](../app-boot/README.md) — profile layers and startup policy.
- [Plugin inventory](../../host/plugin-inventory/README.md) — current Loader and preset observations.
- [Plugin manager page](../../client/ui-plugin-manager/README.md) — the Web sidebar page over this service.
- [Plugin settings](../../client/ui-settings-plugin-inventory/README.md) — the read-only Web inventory.
<a id="model-experience"></a>
## Model Experience
@@ -178,7 +177,7 @@ Tool results append to the transcript. Enabling or disabling other tools can cha
- Startup-only profiles cannot remove packages used to start the current process; stop it and use `dsh plugin`.
- The manager cannot disable its own management components, change another profile, or edit an agent preset's composition.
- A failed removal may leave dependencies partially changed, and a failed or cancelled installation can leave downloaded files under `node_modules` or the pnpm store. Inactive dependencies with missing files remain removable. Diagnostic logs remain under the profile's `.plugin-manager/logs` directory.
- Management results describe Host activation. Browser synchronization failures appear separately in the Settings plugin list.
- Management results describe Host activation. Browser synchronization failures appear separately in the Plugins page's synchronization notice.
- Desktop package operations remain owned by the Desktop shell.
<a id="failure-behavior"></a>
+2 -3
View File
@@ -28,7 +28,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用本包
基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行;设置页的插件列表保持只读。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。
基于 base 的 profile 提供管理服务。在 Web 中,侧边栏的**插件**页([ui-plugin-manager](../../client/ui-plugin-manager/README.zh.md))管理 profile 的组合包及其能唯一定位的行。Agent 预设条目保持只读。`plugin_manager` 工具提供相同操作,在标准和 Creator 预设中启用。其他 Web 预设仍默认禁用。完整 SDK profile 在 profile 作用域为 native/PTC 模式启用此工具;没有 HMR 时,保存的变更返回 `restart-required` 和 `no-hmr`,在运行时重启后应用。每个工具操作都要求 `danger-full-access` 或本次调用的批准。在较低沙箱模式下,`ask` 会请求审批;`never`、拒绝、取消或审批渠道不可用时均不执行。批准不改变会话的权限模式。profile 变更跨会话持久化,已安装的 Host 代码在宿主进程内运行,不受工作区沙箱限制。依赖构建脚本仍需单独批准。
除完整 SDK profile 外,未使用 Agent 预设的部署在 profile patch 中启用工具;安装/移除包要求 PATH 中有 pnpm,或显式配置 `pnpmCommand`,启动器提供的包管理器优先;使用预设的会话由其预设中的 `tool-plugin-manager` 条目控制。
@@ -143,7 +143,6 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,
- [App boot](../app-boot/README.zh.md)——profile 配置层与启动策略。
- [Plugin inventory](../../host/plugin-inventory/README.zh.md)——当前 Loader 和预设状态。
- [插件管理页](../../client/ui-plugin-manager/README.zh.md)——基于本服务的 Web 侧边栏页面。
- [Plugin settings](../../client/ui-settings-plugin-inventory/README.zh.md)——只读的 Web 清单。
<a id="model-experience"></a>
## 模型体验
@@ -178,7 +177,7 @@ service 运行若在 `idleTimeoutMs` 内没有任何捕获输出即被终止,
- 仅启动时加载的 profile 不能删除当前进程启动时使用的包;停止进程后使用 `dsh plugin`。
- 管理器不能关闭自身所需的管理组件、修改其他 profile 或编辑 agent 预设组合。
- 失败的删除可能留下部分依赖改动,失败或被取消的安装可能在 `node_modules` 或 pnpm 缓存中留下已下载文件。文件缺失的未启用依赖仍可删除。诊断日志保留在 profile 的 `.plugin-manager/logs` 目录中。
- 管理结果描述 Host 激活状态。浏览器同步失败会在设置的插件列表中单独显示。
- 管理结果描述 Host 激活状态。浏览器同步失败会在插件页面的同步提示中单独显示。
- Desktop 包管理操作仍由 Desktop shell 负责。
<a id="failure-behavior"></a>
+6 -6
View File
@@ -15,14 +15,14 @@
en: 76368b6b1da79c80
zh: 52384aee991ac542
/deepseek-ai-dsh-plugin-market/use-this-package:
en: fef9850d643e327f
zh: c6e8cab773cf93b9
en: 1b4074faca2694e2
zh: f2d0007652139f26
/deepseek-ai-dsh-plugin-market/use-this-package/plugin-detail-documents:
en: 8a49fc923d4ebd95
zh: 44b9f020e8471458
/deepseek-ai-dsh-plugin-market/understand-the-implementation:
en: cb56b9191fc680a1
zh: eee0a1dfee9ea5bb
en: f349c9da02b42ff4
zh: a34e6e788fa20564
/deepseek-ai-dsh-plugin-market/model-experience:
en: 215e7ba838619b7b
zh: a311da3843709f90
@@ -39,8 +39,8 @@
en: 02cf6033092eb236
zh: cb928bfa6d39a7f7
/deepseek-ai-dsh-plugin-market/known-limitations-and-deferred-work:
en: a5f8aad8e45b333d
zh: bb84782c37db2574
en: 14b60333cd684bf2
zh: 7547d737eceb02ba
/deepseek-ai-dsh-plugin-market/known-limitations-and-deferred-work/dev-note:
en: e67f633dc6fe7773
zh: 3bb0c20c93f16f98
+15 -8
View File
@@ -28,20 +28,24 @@ The optional [custom plugin indexes bundle](../../experimental/plugin-market-bun
| Config | Default | Meaning |
|---|---|---|
| `indexes` | `[]` | Index URLs in display order. A usable URL is in canonical form and uses `http:` or `https:`, without credentials or fragment. The field is volatile: Discover, Settings, and `setIndexes` change it without remounting this service or `plugin-manager`. |
| `fetchTimeoutMs` | `15000` | Deadline for one index fetch, including its body. |
| `maxBytes` | `134217728` | Largest accepted index body. |
| `indexes` | `[]` | Canonical index source URLs in display order. Discover, Settings, and `setIndexes` change this field without remounting this service or `plugin-manager`. |
| `fetchTimeoutMs` | `15000` | Deadline for each HTTP(S) index or detail file request, including the response body. |
| `maxBytes` | `134217728` | Largest accepted index file. |
| `cacheTtlMs` | `600000` | Lifetime of a successfully read index document, a detail read result, and a repository's default-branch commit. |
| `detailMaxBytes` | `1048576` | Largest detail document, and largest locale file read for one. |
| `detailImageMaxBytes` | `5242880` | Largest image served beside a detail document. |
| `detailRepositoryMaxBytes` | `52428800` | Largest amount one Git command adds to a partial clone; a repository whose fetch adds more is not read. |
| `detailCacheMaxBytes` | `524288000` | Largest total size of the partial clones; least recently used ones are deleted beyond it after each fetch. |
| `detailCacheDir` | `.plugin-market/repositories` | Directory of the partial clones, relative to the profile directory; required, as an absolute path, when the service runs outside a dsh profile. |
| `detailGitTimeoutMs` | `60000` | Deadline of one Git command of the clone fallback. |
| `detailGitTimeoutMs` | `60000` | Deadline for a complete Git index file read, including queue and lock waits, and for each Git command used to read an index or detail file. |
| `detailNpmFileSources` | `['jsdelivr', 'unpkg', 'npmmirror']` | npm file CDNs read in order; a read's `npmFileSources` moves the CDNs it names first, and CDNs this list omits are not asked. |
| `detailGitlabHosts` | `['gitlab.com']` | Hosts whose GitLab repository files API serves public repositories, compared without letter case. |
Settings and profile files can store any http(s) string, so the service validates each URL when it lists or reads it. `listIndexes` reports an unusable URL with its refusal, `search` and `entry` refuse it, and no request is sent to it; a repeated URL is listed once.
An index source can be a direct JSON address such as `https://example.com/index.json` or a Git repository such as `git+https://github.com/acme/plugins.git` or `git+ssh://git@git.example.com/platform/plugins.git`. Direct JSON addresses use HTTP or HTTPS and exclude credentials and fragments. A Git source reads `index.json` at the repository root on the default branch. Add `?path=market%2Findex.json&ref=main` to select another repository-relative path or ref. The ref can be a branch name or a full lower-case SHA-1 commit ID.
Git uses the DSH Host user's Git credential helper for HTTPS or the user's SSH configuration and keys for SSH. Set up access on the machine running the Host before adding a private index. Git's `url.<base>.insteadOf` rules may rewrite the repository address to another HTTPS or SSH address. The Host reports a failed connection for the chosen address so you can correct the source or the Host's Git access.
The service validates each source when it lists or reads it. `listIndexes` reports an unusable URL with its refusal, and `search` and `entry` refuse to contact it. A repeated URL is listed once.
The Remote methods are:
@@ -87,7 +91,9 @@ The `plugin_market` tool lists the configured indexes, pages the plugins of one
<a id="understand-the-implementation"></a>
## Understand the implementation
The Host fetches with the process `fetch`, so the configured outbound proxy applies, and refuses redirects. The body is read up to `maxBytes`, then a fresh Worker Thread decodes it as strict UTF-8, parses it as JSON, and validates it; relative icon references resolve against the configured URL. The body's buffer moves to the Worker, and the validated index returns to the Host by structured clone. The Worker is the self-contained `lib/worker.cjs` bundle; disposal terminates it, and a Worker failure is reported as `plugin-market/fetch-failed`.
The Host uses the process `fetch` for direct JSON addresses, so the configured outbound proxy applies. It refuses redirects for these addresses. For Git sources, it reads the index from a partial clone kept apart from detail clones. The Git read defaults to refusing HTTPS redirects and does not retry with a different remote. A fresh index read fetches the default branch or the configured branch again and reuses a pinned commit when it is cached.
The index is read up to `maxBytes`. A fresh Worker Thread decodes the bytes as strict UTF-8, parses them as JSON, and validates the result. Relative icon references in a direct JSON source resolve against its URL. The buffer moves to the Worker, and the validated index returns to the Host by structured clone. Disposal terminates the self-contained `lib/worker.cjs` Worker. A Worker failure is reported as `plugin-market/fetch-failed`.
Concurrent reads of one URL share one fetch. A successful document is cached for `cacheTtlMs`; `refresh` bypasses the cache. Each fetched document gets a new `fetchedAt`, and the cached document stays answerable by its `fetchedAt` until a later fetch replaces it. A failed read records its message for `listIndexes` and keeps no document. A read that finishes after its URL left the configuration updates neither cache nor error. On `loader/volatile-update` the service drops state of removed URLs and emits `plugin-market/changed`. Disposal aborts in-flight fetches.
@@ -95,7 +101,7 @@ Filtering and ordering read only the document; installation status and compatibi
Compatibility is computed per version with `evaluatePluginCompatibility`, the version's `engines.dsh`, and the profile's version exemptions, the same check installation applies. A plugin's default version is its highest compatible version without a prerelease tag, or its highest compatible prerelease when it lists no version without one; a plugin with no compatible version has none. Installation status comes from `pluginManager.listBundles()` by package name, measured against the default version, or the highest version without one: `not-installed`, also for an on-demand catalog entry the profile has not installed; `installed` at that version; `update-available` when that version is greater; `different-version` when the installed version is unknown, not valid SemVer, or greater; and `provided` for a bundle the DSH installation ships. A version's `update` is true when it is newer than a copy `listBundles` marks `update: 'git'` and pins a commit of the repository and directory that copy pins, so the Plugins page can replace that copy with it through `pluginManager.updateBundle`; a registry copy's newer versions come from its registry instead.
Entry detail reads share one reader that the service owns; document selection and the npm file CDNs come from [`dsh-plugin-detail`](../../util/plugin-detail/README.md). Each partial clone is a bare repository under `detailCacheDir`, named by a hash of its URL, initialized in a staging directory and renamed into place, and fetched with `--depth 1 --filter=blob:none` so only commits and trees arrive; Git downloads a file's contents when it is read. Commands run without inherited `GIT_*` variables other than the ssh program, with hooks, the file-system monitor, submodule recursion, and every transport but https, http, and ssh disabled, and no working tree is created. The directory size is checked every 200 ms while Git downloads; growth past `detailRepositoryMaxBytes` within one command stops Git, and output keeps a file's final newline byte. A file read stops once its contents pass the read's limit, and an image read completes even when the browser abandons the request, so leaving a page never interrupts a clone. A ref under `refs/dsh/` records each fetched commit, so a commit is never fetched lazily without the size check. Operations on one repository run one at a time, also across processes that share `detailCacheDir`, such as Web and Desktop on one profile, through a lock file beside the repository; eviction deletes a repository only after them, enforces `detailCacheMaxBytes` after every fetch and every file read, and deletes the repository in use last, after its operation, when it alone exceeds the total; one that fails or is cancelled, for any reason but a file over its read's limit, deletes the repository, so the next read starts from a fresh clone. Eviction also removes staging directories older than `detailGitTimeoutMs`. Disposal stops Git and waits for it.
Entry detail reads share one reader that the service owns; document selection and the npm file CDNs come from [`dsh-plugin-detail`](../../util/plugin-detail/README.md). Each partial clone is a bare repository under `detailCacheDir`, named by a hash of its URL, initialized in a staging directory and renamed into place, and fetched with `--depth 1 --filter=blob:none` so only commits and trees arrive; Git downloads a file's contents when it is read. Commands run without inherited `GIT_*` variables other than the ssh program, with hooks, the file-system monitor, submodule recursion, and every transport but https, http, and ssh disabled, and no working tree is created. The directory size is checked every 200 ms while Git downloads; growth past `detailRepositoryMaxBytes` within one command stops Git, and output keeps a file's final newline byte. A file read stops once its contents pass the read's limit, and an image read completes even when the browser abandons the request, so leaving a page never interrupts a clone. A ref under `refs/dsh/` records each fetched commit, so a commit is never fetched lazily without the size check. Operations on one repository run one at a time, also across processes that share `detailCacheDir`, such as Web and Desktop on one profile, through a lock file beside the repository; eviction deletes a repository only after them, enforces `detailCacheMaxBytes` after every fetch and every file read, and deletes the repository in use last, after its operation, when it alone exceeds the total; a read that fails or is cancelled while holding the lock deletes the repository unless the file exceeds its read limit, so the next read starts from a fresh clone. Eviction also removes staging directories older than `detailGitTimeoutMs`. Disposal stops Git and waits for it.
`marketInstallTarget` builds install arguments: `name@version` with the version's registry for npm, and `git+<url>.git#<commit>` with `&path:/<path>` for a package directory in Git.
@@ -122,10 +128,11 @@ Append-only: results enter the conversation as ordinary tool results and do not
<a id="known-limitations-and-deferred-work"></a>
- **Git index icons** — use a base64 data URL or an absolute HTTPS URL that the browser can reach. Git credentials apply to the index file.
- **Git updates only** — only a copy installed from a Git commit updates to a newer index version, and only within the repository directory it came from; a copy installed from a registry updates from its registry, and one installed from another source, such as a local directory, a branch, or another repository, is uninstalled and installed again.
- **Unsigned indexes** — index content, including a Git entry's name and version, is the index's claim; the installed manifest decides what is installed.
- **Last write wins** — `setIndexes` replaces the whole list, so two windows editing sources at the same time can overwrite each other's change.
- **Redirects refused** — an index served only behind a redirect must be configured at its final URL.
- **Direct JSON redirects** — a direct JSON index served only behind a redirect must be configured at its final URL.
- **Whole-document reads** — the Host downloads and keeps each index up to `maxBytes` and builds its text index in memory; a synthetic index of 20,000 plugins took about 0.8 s of build time and 130 MiB of heap. Parsing runs in a Worker, but receiving the validated index still blocks the Host event loop while the clone is deserialized: about 35 ms for a synthetic 7.6 MiB index of 20,000 plugins and about 190 ms for 38 MiB and 100,000 plugins. Larger indexes need a server-side query protocol.
- **Default-branch READMEs** — a repository README is read at the default branch, which can differ from the listed version; npm records no commit the CDNs expose.
- **Private npm registries** — the public CDNs do not serve packages of other registries, so only the entry's repository can provide such a version's document.
+15 -8
View File
@@ -28,20 +28,24 @@ kind: "package-reference"
| 配置 | 默认值 | 含义 |
|---|---|---|
| `indexes` | `[]` | 按显示顺序排列的索引 URL。可用的 URL 采用规范形式,使用 `http:` 或 `https:`,不含凭据或片段。该字段是 volatile 字段:发现区、设置和 `setIndexes` 修改它时,不会重新挂载本服务或 `plugin-manager`。 |
| `fetchTimeoutMs` | `15000` | 单次索引获取(包括响应体)的时限。 |
| `maxBytes` | `134217728` | 接受的最大索引响应体。 |
| `indexes` | `[]` | 按显示顺序排列的规范索引源 URL。发现区、设置和 `setIndexes` 可修改此字段,无需重新挂载本服务或 `plugin-manager`。 |
| `fetchTimeoutMs` | `15000` | 单次通过 HTTP(S) 请求索引或详细介绍文件的时限,包括读取响应体。 |
| `maxBytes` | `134217728` | 接受的最大索引文件大小。 |
| `cacheTtlMs` | `600000` | 成功读取的索引文档、详细介绍的读取结果以及仓库默认分支提交的缓存时长。 |
| `detailMaxBytes` | `1048576` | 详细介绍文档的最大大小,以及为读取它而读取的 locale 文件的最大大小。 |
| `detailImageMaxBytes` | `5242880` | 与详细介绍文档一同提供的图片的最大大小。 |
| `detailRepositoryMaxBytes` | `52428800` | 单条 Git 命令向一个部分克隆增加的最大数据量;获取时增加的数据量超过该值的仓库不被读取。 |
| `detailCacheMaxBytes` | `524288000` | 所有部分克隆的最大总大小;每次获取后,超出时删除最近最少使用的部分克隆。 |
| `detailCacheDir` | `.plugin-market/repositories` | 部分克隆所在的目录,相对于 profile 目录;服务在 dsh profile 之外运行时必须以绝对路径配置。 |
| `detailGitTimeoutMs` | `60000` | 克隆回退方式中单条 Git 命令的时限。 |
| `detailGitTimeoutMs` | `60000` | 通过 Git 完整读取索引文件的时限(含排队和等待锁),以及读取索引或详细介绍文件时单条 Git 命令的时限。 |
| `detailNpmFileSources` | `['jsdelivr', 'unpkg', 'npmmirror']` | 按顺序读取的 npm 文件 CDN;一次读取的 `npmFileSources` 把其中列出的 CDN 移到最前,本列表未列出的 CDN 不会被请求。 |
| `detailGitlabHosts` | `['gitlab.com']` | 通过 GitLab 仓库文件 API 提供公开仓库的主机,比较时不区分大小写。 |
设置和 profile 文件可以存储任意 http(s) 字符串,因此服务在列出或读取每个 URL 时校验它。`listIndexes` 报告不可用的 URL 及其拒绝原因,`search` 和 `entry` 拒绝该 URL,且不会向它发送请求;重复的 URL 只列出一次。
索引源可以是直接返回 JSON 的地址,例如 `https://example.com/index.json`,也可以是 Git 仓库,例如 `git+https://github.com/acme/plugins.git` 或 `git+ssh://git@git.example.com/platform/plugins.git`。直接返回 JSON 的地址使用 HTTP 或 HTTPS,且不含凭据或片段。Git 源读取默认分支上仓库根目录的 `index.json`。添加 `?path=market%2Findex.json&ref=main` 可指定相对于仓库根目录的其他路径或引用。引用可以是分支名或完整的小写 SHA-1 提交 ID。
通过 HTTPS 读取时,Git 使用运行 DSH Host 的用户配置的 Git 凭据助手。通过 SSH 读取时,Git 使用该用户的 SSH 配置和密钥。添加私有索引前,请先在运行 Host 的机器上配置访问权限。Git 的 `url.<base>.insteadOf` 规则可将仓库地址改写为另一个 HTTPS 或 SSH 地址。如果所选地址连接失败,Host 会报告错误,你可以修正索引源或 Host 的 Git 访问设置。
服务在列出或读取索引源时校验地址。`listIndexes` 报告不可用的 URL 及其拒绝原因,`search` 和 `entry` 拒绝访问该 URL。重复的 URL 只列出一次。
Remote 方法如下:
@@ -88,7 +92,9 @@ Remote 方法如下:
<a id="understand-the-implementation"></a>
## 理解实现
Host 使用进程的 `fetch` 获取,因此配置的出站代理生效,并拒绝重定向。响应体最多读取 `maxBytes`,随后由一个新的 Worker Thread 按严格 UTF-8 解码、解析为 JSON 并校验;相对图标引用基于配置的 URL 解析。响应体的缓冲区转移给 Worker,校验后的索引通过 structured clone 返回 Host。Worker 是自包含的 `lib/worker.cjs` bundle;销毁时终止它,Worker 失败报告为 `plugin-market/fetch-failed`。
Host 使用进程的 `fetch` 读取直接返回 JSON 的地址,因此配置的出站代理生效。这类地址不接受重定向。对于 Git 源,Host 从与详细介绍分开缓存的部分克隆中读取索引。Git 读取默认拒绝 HTTPS 重定向,且不会换用另一个远端重试。重新读取索引时会再次获取默认分支或指定的分支,已缓存的固定提交则会复用。
索引最多读取 `maxBytes`。新的 Worker Thread 按严格 UTF-8 解码文件内容,将其解析为 JSON 并校验结果。直接返回 JSON 的源以其 URL 为基准解析相对图标引用。缓冲区转移给 Worker,校验后的索引通过 structured clone 返回 Host。销毁时终止自包含的 `lib/worker.cjs` Worker。Worker 失败报告为 `plugin-market/fetch-failed`。
对同一 URL 的并发读取共享一次获取。成功的文档缓存 `cacheTtlMs`;`refresh` 绕过缓存。每份获取到的文档都有新的 `fetchedAt`,缓存的文档在被之后的获取替换前,都可以按其 `fetchedAt` 回答。失败的读取为 `listIndexes` 记录错误消息,不保留文档。读取完成时其 URL 已不在配置中的,既不更新缓存也不更新错误。收到 `loader/volatile-update` 时,服务丢弃已移除 URL 的状态并发出 `plugin-market/changed`。销毁时中止进行中的获取。
@@ -96,7 +102,7 @@ Host 使用进程的 `fetch` 获取,因此配置的出站代理生效,并拒
兼容性按版本计算:使用 `evaluatePluginCompatibility`,传入该版本的 `engines.dsh` 和 profile 的版本豁免,与安装时执行的检查相同。插件的默认版本是其不带先行版本号的最高兼容版本;插件完全没有此类版本时,使用其最高兼容的先行版本;没有兼容版本的插件没有默认版本。安装状态按包名根据 `pluginManager.listBundles()` 计算,以默认版本为准,没有默认版本时以最高版本为准:`not-installed`(包括当前 profile 尚未安装的按需目录条目);版本相同时为 `installed`;该版本更高时为 `update-available`;已安装版本未知、不是有效的 SemVer 或更高时为 `different-version`;DSH 安装随附的组合包(bundle)为 `provided`。版本比 `listBundles` 标为 `update: 'git'` 的副本新,且固定到该副本所固定的仓库与目录中的一个提交时,其 `update` 为 true,插件页因此可以通过 `pluginManager.updateBundle` 用它替换该副本;注册表副本的新版本则来自其注册表。
条目详细介绍的读取共用服务拥有的一个读取器;文档选择和 npm 文件 CDN 来自 [`dsh-plugin-detail`](../../util/plugin-detail/README.zh.md)。每个部分克隆是 `detailCacheDir` 下的一个裸仓库,以其 URL 的哈希命名,先在暂存目录中初始化,再重命名到目标位置,并使用 `--depth 1 --filter=blob:none` 获取,因此只下载提交和树对象;读取文件时 Git 才下载其内容。命令运行时不继承除 ssh 程序之外的 `GIT_*` 变量,禁用 hook、文件系统监视器、子模块递归,以及 https、http 和 ssh 之外的所有传输协议,且不创建工作树。Git 下载期间每 200 毫秒检查一次目录大小;单条命令执行期间增长超过 `detailRepositoryMaxBytes` 时停止 Git,且输出保留文件末尾的换行字节。文件内容超过本次读取的限制时,读取即停止;浏览器放弃请求时,图片读取仍会完成,因此离开页面不会中断克隆。`refs/dsh/` 下的 ref 记录每个已获取的提交,因此不会在没有大小检查的情况下延迟获取提交。对同一仓库的操作逐个执行,共享 `detailCacheDir` 的多个进程(例如同一 profile 上的 Web 和 Desktop)之间也是如此,由仓库旁的一个锁文件实现;淘汰只在这些操作结束后删除该仓库,并在每次获取和每次文件读取后执行 `detailCacheMaxBytes` 总量限制;正在使用的仓库单独超过该总量时,淘汰最后删除它,并等到其操作结束后再删除;除文件超过本次读取的限制外,任何原因导致操作失败或被取消时,都删除该仓库,使下一次读取从新的克隆开始。淘汰时还会删除存在时间超过 `detailGitTimeoutMs` 的暂存目录。销毁时停止 Git 并等待其退出。
条目详细介绍的读取共用服务拥有的一个读取器;文档选择和 npm 文件 CDN 来自 [`dsh-plugin-detail`](../../util/plugin-detail/README.zh.md)。每个部分克隆是 `detailCacheDir` 下的一个裸仓库,以其 URL 的哈希命名,先在暂存目录中初始化,再重命名到目标位置,并使用 `--depth 1 --filter=blob:none` 获取,因此只下载提交和树对象;读取文件时 Git 才下载其内容。命令运行时不继承除 ssh 程序之外的 `GIT_*` 变量,禁用 hook、文件系统监视器、子模块递归,以及 https、http 和 ssh 之外的所有传输协议,且不创建工作树。Git 下载期间每 200 毫秒检查一次目录大小;单条命令执行期间增长超过 `detailRepositoryMaxBytes` 时停止 Git,且输出保留文件末尾的换行字节。文件内容超过本次读取的限制时,读取即停止;浏览器放弃请求时,图片读取仍会完成,因此离开页面不会中断克隆。`refs/dsh/` 下的 ref 记录每个已获取的提交,因此不会在没有大小检查的情况下延迟获取提交。对同一仓库的操作逐个执行,共享 `detailCacheDir` 的多个进程(例如同一 profile 上的 Web 和 Desktop)之间也是如此,由仓库旁的一个锁文件实现;淘汰只在这些操作结束后删除该仓库,并在每次获取和每次文件读取后执行 `detailCacheMaxBytes` 总量限制;正在使用的仓库单独超过该总量时,淘汰最后删除它,并等到其操作结束后再删除;持锁读取失败或被取消时删除该仓库,文件超过本次读取限制时除外,使下一次读取从新的克隆开始。淘汰时还会删除存在时间超过 `detailGitTimeoutMs` 的暂存目录。销毁时停止 Git 并等待其退出。
`marketInstallTarget` 构建安装参数:npm 为 `name@version` 加该版本的 registry,Git 为 `git+<url>.git#<commit>`,包位于子目录时追加 `&path:/<path>`。
@@ -123,10 +129,11 @@ Host 使用进程的 `fetch` 获取,因此配置的出站代理生效,并拒
<a id="known-limitations-and-deferred-work"></a>
- **Git 索引图标**——使用 base64 数据 URL 或浏览器可访问的 HTTPS 绝对地址。Git 凭据用于读取索引文件。
- **只支持 Git 更新**——只有从 Git 提交安装的副本会更新到索引中较新的版本,且只在其来源的仓库目录内更新;从注册表安装的副本从其注册表更新,从其他来源(例如本地目录、分支或其他仓库)安装的副本需要先卸载再安装。
- **索引没有签名**——索引内容(包括 Git 条目的名称和版本)是索引的声明;实际安装什么由已安装的 manifest(元数据清单)决定。
- **后写入者覆盖**——`setIndexes` 会替换整个列表,因此两个窗口同时编辑索引源时,可能互相覆盖对方的修改。
- **拒绝重定向**——只能经重定向访问的索引必须以其最终 URL 配置。
- **直接 JSON 地址的重定向**——只能经重定向访问的直接 JSON 索引必须以其最终 URL 配置。
- **读取整份文档**——Host 下载并保留每个不超过 `maxBytes` 的索引,并在内存中构建其文本索引;一个包含 20,000 个插件的合成索引构建用时约 0.8 秒,占用约 130 MiB 堆内存。解析在 Worker 中运行,但接收校验后的索引时,反序列化 clone 仍会阻塞 Host 事件循环:包含 20,000 个插件的 7.6 MiB 合成索引约 35 毫秒,包含 100,000 个插件的 38 MiB 索引约 190 毫秒。更大的索引需要服务端查询协议。
- **默认分支的 README**——仓库 README 读取的是默认分支上的文件,可能与列出的版本不一致;CDN 公开的 npm 数据不记录提交。
- **私有 npm 注册表**——公共 CDN 不提供其他注册表的包,因此此类版本的文档只能来自条目的仓库。
+10 -2
View File
@@ -1,14 +1,22 @@
/** Index source URL validation shared by `setIndexes` and the per-use check of configured sources. */
import { parseGitMarketIndexSource } from '@deepseek-ai/dsh-plugin-market-index/source'
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
/**
* Validate and normalize one index source URL.
* @param text - URL as configured or entered.
* @returns the URL's serialization.
* @throws {RemoteError} `plugin-market/invalid-index-url` for anything but an http(s) URL without credentials or
* fragment.
* @throws {RemoteError} `plugin-market/invalid-index-url` for an invalid HTTP(S) or Git index address.
*/
export function normalizeIndexUrl(text: string): string {
if (text.trimStart().startsWith('git+')) {
try {
return parseGitMarketIndexSource(text.trim()).url
} catch (error) {
const message = error instanceof Error && !(error instanceof TypeError) ? error.message : 'Use a valid Git repository address'
throw new RemoteError('plugin-market/invalid-index-url', message, { url: '', reason: 'git-source' })
}
}
let url: URL
try {
url = new URL(text.trim())
+42 -11
View File
@@ -6,6 +6,7 @@ import z from '@deepseek-ai/schemastery'
import semver from 'semver'
import { evaluatePluginCompatibility, getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
import { marketInstallTarget, type MarketIndex, type MarketPlugin, type MarketVersion } from '@deepseek-ai/dsh-plugin-market-index'
import { parseGitMarketIndexSource } from '@deepseek-ai/dsh-plugin-market-index/source'
import type { BundleInfo } from '@deepseek-ai/dsh-plugin-manager/types'
// Also declares the `pluginManager` service this one reads bundles from.
import { pinnedGitOrigin } from '@deepseek-ai/dsh-plugin-manager'
@@ -44,7 +45,7 @@ declare module '@deepseek-ai/cordis' {
export interface Config {
/** Index URLs in display order; Settings and `setIndexes` write this field without remounting the service. */
indexes: Volatile<string[]>
/** Deadline for one index fetch, including the body. */
/** Deadline for an HTTP index or detail file request, including its body. */
fetchTimeoutMs: number
/** Largest accepted index body in bytes. */
maxBytes: number
@@ -60,7 +61,7 @@ export interface Config {
detailCacheMaxBytes: number
/** Directory of the partial clones, relative to the profile directory; absent means `.plugin-market/repositories`. */
detailCacheDir?: string
/** Deadline of one Git command of the clone fallback. */
/** Deadline for a Git index read and for each Git command used to read an index or plugin details. */
detailGitTimeoutMs: number
/** npm file CDNs read in order; a read's `npmFileSources` moves the CDNs it names first. */
detailNpmFileSources: NpmFileSource[]
@@ -110,7 +111,7 @@ export default class PluginMarket extends TypertRemoteService {
static inject = ['pluginManager']
static Config = z.object({
indexes: z.array(z.string().pattern(/^https?:\/\/\S+$/u)).default([]).volatile(),
indexes: z.array(z.string().pattern(/^(?:https?|git\+(?:https|ssh)):\/\/\S+$/u)).default([]).volatile(),
fetchTimeoutMs: z.natural().min(1).max(MAX_TIMER_DELAY_MS).default(15000),
maxBytes: z.natural().min(1).default(128 * 1024 * 1024),
cacheTtlMs: z.natural().default(600000),
@@ -381,7 +382,7 @@ export default class PluginMarket extends TypertRemoteService {
/**
* The configured sources as written, each with the refusal that makes it unusable. Settings and profile files can
* write any http(s) string, so every use validates instead of the schema; an unusable source is listed with its error
* write a noncanonical address, so every use validates it. An unusable source is listed with its error
* and never fetched, and a repeated URL counts once.
*/
private sources(): { readonly url: string; readonly error?: string }[] {
@@ -423,9 +424,44 @@ export default class PluginMarket extends TypertRemoteService {
}
private async fetchIndex(url: string): Promise<MarketIndex> {
const signal = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(this.config.fetchTimeoutMs)])
const git = url.startsWith('git+')
const timeoutMs = git ? this.config.detailGitTimeoutMs : this.config.fetchTimeoutMs
const signal = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(timeoutMs)])
const failed = (reason: string, cause?: unknown): RemoteError =>
new RemoteError('plugin-market/fetch-failed', `Could not fetch ${url}: ${reason}`, { url, reason }, { cause })
const bytes = git ? await this.readGitIndex(url, signal, failed) : await this.fetchIndexBody(url, signal, failed)
const result = await parseIndexInWorker(bytes, url, this.lifetime.signal).catch((error: unknown) => {
throw failed(messageOf(error), error)
})
if (result.ok) return result.index
throw new RemoteError('plugin-market/invalid-index', `${url}: ${result.message}`, { url, path: result.path, reason: result.reason })
}
private async readGitIndex(url: string, signal: AbortSignal, failed: (reason: string) => RemoteError): Promise<Uint8Array> {
const { repository, ref, path } = parseGitMarketIndexSource(url)
let bytes: Uint8Array | undefined
try {
bytes = await this.repositories.readIndex(repository, ref, path, this.config.maxBytes, signal)
} catch (error) {
if (signal.aborted) throw failed(messageOf(signal.reason))
if (error instanceof DetailFailure) {
switch (error.reason) {
case 'denied': throw failed('Git could not read the repository. Check Host Git authentication, repository permissions, and the branch or commit')
case 'git-unavailable': throw failed('Git is unavailable on the Host')
case 'network': throw failed('Git could not connect to the repository')
case 'too-large': throw failed('The Git index file or repository exceeds its size limit')
default: break
}
}
throw failed('Git could not read the index file on the Host')
}
if (bytes === undefined) throw failed(`No regular index file at ${path}`)
return Uint8Array.from(bytes)
}
private async fetchIndexBody(
url: string, signal: AbortSignal, failed: (reason: string, cause?: unknown) => RemoteError,
): Promise<Uint8Array> {
let response: Response
try {
response = await fetch(url, { signal, redirect: 'error', headers: { accept: 'application/json' } })
@@ -436,12 +472,7 @@ export default class PluginMarket extends TypertRemoteService {
await response.body?.cancel()
throw failed(`HTTP ${String(response.status)}`)
}
const bytes = await this.readBody(response, failed)
const result = await parseIndexInWorker(bytes, url, this.lifetime.signal).catch((error: unknown) => {
throw failed(messageOf(error), error)
})
if (result.ok) return result.index
throw new RemoteError('plugin-market/invalid-index', `${url}: ${result.message}`, { url, path: result.path, reason: result.reason })
return await this.readBody(response, failed)
}
/** Read the whole body, refusing it as soon as it exceeds `maxBytes`. */
@@ -1,11 +1,11 @@
/**
* Cached partial clones for plugin detail documents of repositories that need the user's Git credentials or have no
* anonymous single-file API. Each repository is a bare repository fetched with depth 1 and without file contents; Git
* downloads a file's contents only when it is read. No working tree is created, so no checkout filter, hook, LFS
* download, or symbolic link takes effect. A repository whose operation fails or is cancelled is deleted, so an
* interrupted command never leaves a damaged clone behind.
* Cached partial clones for Git market indexes and plugin detail documents. Each repository is a bare repository
* fetched with depth 1 and without file contents. Git downloads a file's contents when it is read. No working tree
* is created, so no checkout filter, hook, LFS download, or symbolic link takes effect. Once a read starts under the
* lock, failure or cancellation deletes the repository, except when an individual file exceeds its read limit.
*/
import { createHash } from 'node:crypto'
import { addAbortListener } from 'node:events'
import { existsSync } from 'node:fs'
import { mkdir, mkdtemp, readdir, rename, rm, stat, utimes } from 'node:fs/promises'
import { join } from 'node:path'
@@ -22,7 +22,7 @@ const OPERATION_COMMANDS = 5
/** Limits, location, and transports of the clone cache. */
export interface RepositoryCacheOptions {
/** Directory holding one bare repository per repository URL. */
/** Directory holding bare repositories keyed by repository URL and read policy. */
readonly dir: string
/** Largest amount one command adds to a repository; a command that adds more is stopped and the repository deleted. */
readonly maxRepositoryBytes: number
@@ -30,9 +30,9 @@ export interface RepositoryCacheOptions {
readonly maxCacheBytes: number
/** Deadline of one Git command and of one anonymous accessibility check. */
readonly timeoutMs: number
/** How long a repository's default-branch commit and its anonymous accessibility are reused. */
/** How long a detail repository's default-branch commit and anonymous accessibility are reused. */
readonly ttlMs: number
/** Git transports Git may use, such as `https` and `ssh`; `url.<base>.insteadOf` in the user's configuration still applies. */
/** Transports allowed for detail reads. Index reads allow HTTPS and SSH. Git URL rewrites still apply. */
readonly transports: readonly string[]
/** Disposal of the owning service. */
readonly lifetime: AbortSignal
@@ -45,6 +45,19 @@ const NETWORK_FAILURE = new RegExp([
'Could not resolve host', 'Failed to connect', 'Connection (?:refused|reset)', 'timed out', 'Network is unreachable', 'SSL', 'TLS',
].join('|'), 'iu')
interface GitDirectory {
readonly dir: string
readonly policy: 'detail' | 'index'
}
interface CachedRepository extends GitDirectory {
readonly url: string
}
type GitRef = { readonly kind: 'head' }
| { readonly kind: 'branch'; readonly name: string }
| { readonly kind: 'commit'; readonly id: string }
/** One Git command's outcome. */
interface GitResult {
readonly stdout: Buffer
@@ -112,7 +125,16 @@ function gitEnv(): Record<string, string> {
}
}
/** Partial clones of detail repositories under one directory, owned by one service. */
/** Wait for the previous operation without making it responsible for this read's deadline. */
async function waitForTurn(previous: Promise<void>, signal: AbortSignal): Promise<void> {
signal.throwIfAborted()
const aborted = Promise.withResolvers<void>()
using _listener = addAbortListener(signal, () => { aborted.resolve() })
await Promise.race([previous, aborted.promise])
signal.throwIfAborted()
}
/** Partial clones of index and detail repositories under one size budget, owned by one service. */
export class RepositoryCache {
private readonly locks = new Map<string, Promise<void>>()
private readonly heads = new Map<string, Expiring<string>>()
@@ -175,10 +197,33 @@ export class RepositoryCache {
* @throws {DetailFailure} when Git cannot fetch the commit, the repository grows past its limit, or the file exceeds `maxBytes`.
*/
read(url: string, commit: string | undefined, path: string, maxBytes: number, signal: AbortSignal): Promise<Uint8Array | undefined> {
return this.locked(url, async (repository) => {
const resolved = await this.commit(repository, url, commit, signal)
return this.readFile(url, 'detail', commit === undefined ? { kind: 'head' } : { kind: 'commit', id: commit }, path, maxBytes, signal)
}
/**
* Read an index file from a clone isolated from detail reads. A branch or remote HEAD is fetched on every call.
* The read defaults to rejecting HTTPS redirects and does not retry with another remote.
* @param url - the validated HTTPS or SSH repository URL. Git URL rewrites between those transports apply.
* @param ref - a validated branch name, full lower-case SHA-1 commit id, or undefined for remote HEAD.
* @param path - `/`-separated path relative to the repository root.
* @param maxBytes - largest accepted index size.
* @param signal - cancellation of the read, including waits for the repository lock.
* @returns the bytes, or undefined if the resolved commit has no regular file at `path`.
* @throws {DetailFailure} as {@link read} does.
*/
readIndex(url: string, ref: string | undefined, path: string, maxBytes: number, signal: AbortSignal): Promise<Uint8Array | undefined> {
const target: GitRef = ref === undefined ? { kind: 'head' }
: /^[0-9a-f]{40}$/u.test(ref) ? { kind: 'commit', id: ref } : { kind: 'branch', name: ref }
return this.readFile(url, 'index', target, path, maxBytes, signal)
}
private readFile(
url: string, policy: GitDirectory['policy'], ref: GitRef, path: string, maxBytes: number, signal: AbortSignal,
): Promise<Uint8Array | undefined> {
return this.locked(url, policy, signal, async (repository) => {
const resolved = await this.commit(repository, ref, signal)
const blob = (await this.files(repository, resolved, path, signal)).get(path)
return blob === undefined ? undefined : await this.blob(repository, url, blob, path, maxBytes, signal)
return blob === undefined ? undefined : await this.blob(repository, blob, path, maxBytes, signal)
})
}
@@ -193,30 +238,34 @@ export class RepositoryCache {
* @throws {DetailFailure} as {@link read} does.
*/
readme(url: string, commit: string | undefined, dir: string, maxBytes: number, signal: AbortSignal): Promise<FoundFile | undefined> {
return this.locked(url, async (repository) => {
const resolved = await this.commit(repository, url, commit, signal)
return this.locked(url, 'detail', signal, async (repository) => {
const resolved = await this.commit(repository, commit === undefined ? { kind: 'head' } : { kind: 'commit', id: commit }, signal)
const files = await this.files(repository, resolved, dir === '' ? undefined : `${dir}/`, signal)
const prefix = dir === '' ? '' : `${dir}/`
const name = readmeName([...files.keys()].map(path => path.slice(prefix.length)))
if (name === undefined) return undefined
const path = `${prefix}${name}`
return { path, bytes: await this.blob(repository, url, files.get(path) as string, path, maxBytes, signal) }
return { path, bytes: await this.blob(repository, files.get(path) as string, path, maxBytes, signal) }
})
}
/** Wait until every running Git command has ended; the lifetime signal stops them. */
/** Wait for queued and running operations to settle and release their locks. */
async settled(): Promise<void> {
await Promise.allSettled([...this.running])
}
/**
* Serialize operations on one repository, so a fetch and the reads after it never interleave, and delete the
* repository when an operation fails or is cancelled for any reason but a file over its read's size.
* repository when a read holding the lock fails or is cancelled for any reason but a file over its read's size.
*/
private locked<T>(url: string, operation: (repository: string) => Promise<T>): Promise<T> {
const repository = join(this.options.dir, createHash('sha256').update(url).digest('hex').slice(0, 24))
return this.serialized(repository, () => operation(repository).catch(async (error: unknown) => {
if (!(error instanceof FileTooLarge)) await rm(repository, { recursive: true, force: true })
private locked<T>(
url: string, policy: GitDirectory['policy'], signal: AbortSignal, operation: (repository: CachedRepository) => Promise<T>,
): Promise<T> {
const key = policy === 'detail' ? url : `index\0${url}`
const dir = join(this.options.dir, createHash('sha256').update(key).digest('hex').slice(0, 24))
const cancellation = AbortSignal.any([signal, this.options.lifetime])
return this.serialized(dir, cancellation, () => operation({ dir, url, policy }).catch(async (error: unknown) => {
if (!(error instanceof FileTooLarge)) await rm(dir, { recursive: true, force: true })
throw error
}))
}
@@ -225,16 +274,16 @@ export class RepositoryCache {
* Run an operation after every earlier operation on the same repository directory has ended, in this service and in
* other processes that share the cache directory, such as Web and Desktop on one profile.
*/
private serialized<T>(repository: string, operation: () => Promise<T>): Promise<T> {
private serialized<T>(repository: string, signal: AbortSignal, operation: () => Promise<T>): Promise<T> {
const previous = this.locks.get(repository) ?? Promise.resolve()
const next = previous.then(async () => {
const next = waitForTurn(previous, signal).then(async () => {
await mkdir(this.options.dir, { recursive: true })
// An operation runs at most this many Git commands, each bounded by the Git deadline.
const waitMs = OPERATION_COMMANDS * this.options.timeoutMs
return await withFileLock(repository, operation, { waitMs, signal: this.options.lifetime })
return await withFileLock(repository, operation, { waitMs, signal })
})
// The caller receives the outcome; the lock and the settlement wait only for completion.
const tracked: Promise<void> = next.then(() => undefined, () => undefined).finally(() => {
// A cancelled waiter can settle before its predecessor. The queue still belongs to that predecessor.
const tracked = next.then(() => previous, () => previous).finally(() => {
if (this.locks.get(repository) === tracked) this.locks.delete(repository)
this.running.delete(tracked)
})
@@ -243,54 +292,56 @@ export class RepositoryCache {
return next
}
/** The commit to read: a fetched commit, fetching it or the default branch when necessary. */
private async commit(repository: string, url: string, commit: string | undefined, signal: AbortSignal): Promise<string> {
/** Resolve and record a commit before reads that could download missing objects. */
private async commit(repository: CachedRepository, ref: GitRef, signal: AbortSignal): Promise<string> {
const { dir, url, policy } = repository
if (!this.gitStarts) {
// `git version <release>` is one short line.
await this.run(this.options.dir, ['--version'], signal, 1024).catch((error: unknown) => {
await this.run({ dir: this.options.dir, policy }, ['--version'], signal, 1024).catch((error: unknown) => {
throw new DetailFailure('git-unavailable', (error as Error).message, { cause: error })
})
this.gitStarts = true
}
if (!existsSync(repository)) {
if (!existsSync(dir)) {
// A repository appears complete or not at all: it is initialized beside its final name, then renamed.
const staging = await mkdtemp(join(this.options.dir, STAGING_PREFIX))
const staging = { dir: await mkdtemp(join(this.options.dir, STAGING_PREFIX)), policy }
try {
await this.run(staging, ['init', '--quiet', '--bare', '--template='], signal)
for (const [key, value] of [['remote.origin.url', url], ['remote.origin.promisor', 'true'], ['remote.origin.partialclonefilter', 'blob:none']]) {
await this.run(staging, ['config', key as string, value as string], signal)
}
await rename(staging, repository)
await rename(staging.dir, dir)
} finally {
await rm(staging, { recursive: true, force: true })
await rm(staging.dir, { recursive: true, force: true })
}
}
await utimes(repository, new Date(), new Date())
await utimes(dir, new Date(), new Date())
// An object lookup would fetch a missing commit lazily from the promisor remote, without the size watch; a ref
// written after a completed fetch records the commit instead, and eviction removes it with the repository.
const head = this.heads.get(url)
const detailHead = policy === 'detail' && ref.kind === 'head'
const head = detailHead ? this.heads.get(url) : undefined
const commit = ref.kind === 'commit' ? ref.id : undefined
const known = commit ?? (head !== undefined && head.expiresAt > Date.now() ? head.value : undefined)
if (known !== undefined && !(await this.git(['show-ref', '--verify', '--quiet', `refs/dsh/${known}`], repository, signal)).failed) return known
await this.fetch(repository, commit ?? 'HEAD', signal)
if (known !== undefined && !(await this.git(repository, ['show-ref', '--verify', '--quiet', `refs/dsh/${known}`], signal)).failed) return known
await this.fetch(repository, ref.kind === 'branch' ? `refs/heads/${ref.name}` : commit ?? 'HEAD', signal)
const fetched = commit ?? (await this.run(repository, ['rev-parse', 'FETCH_HEAD'], signal)).toString('utf8').trim()
await this.run(repository, ['update-ref', `refs/dsh/${fetched}`, fetched], signal)
if (commit === undefined) this.heads.set(url, { value: fetched, expiresAt: Date.now() + this.options.ttlMs })
if (detailHead) this.heads.set(url, { value: fetched, expiresAt: Date.now() + this.options.ttlMs })
return fetched
}
/**
* Fetch one commit without file contents. When Git refuses an http(s) URL, the clone's remote switches to the SSH form
* of that URL and the fetch runs again, so a user with only SSH credentials for the host can read it; later reads of
* the clone keep that remote. A failed SSH fetch reports both diagnostics, as `network` or `too-large` when it failed
* for that reason and as `denied` otherwise.
* Fetch one commit without file contents. A detail clone that Git refuses over HTTP(S) retries and retains the SSH
* form of its remote. A failed SSH retry reports both failures unless the repository exceeded its size limit.
*/
private async fetch(repository: string, target: string, signal: AbortSignal): Promise<void> {
const args = ['fetch', '--quiet', '--depth', '1', '--filter=blob:none', '--no-tags', 'origin', target]
private async fetch(repository: CachedRepository, target: string, signal: AbortSignal): Promise<void> {
const args = ['fetch', '--quiet', '--depth', '1', '--filter=blob:none', '--no-tags', '--', 'origin', target]
// The remote is the URL this cache wrote or its SSH form; 64 KiB holds any such URL.
const remote = (await this.run(repository, ['config', 'remote.origin.url'], signal, 64 * 1024)).toString('utf8').trim()
try {
await this.watched(repository, remote, args, signal, `${remote}: git fetch`)
} catch (error) {
if (repository.policy === 'index') throw error
const ssh = sshUrlOf(remote)
if (ssh === undefined || !(error instanceof DetailFailure) || error.reason !== 'denied') throw error
await this.run(repository, ['config', 'remote.origin.url', ssh], signal)
@@ -300,7 +351,7 @@ export class RepositoryCache {
: sshError
})
}
await this.evict(repository)
await this.evict(repository.dir)
}
/**
@@ -308,24 +359,24 @@ export class RepositoryCache {
* command; the caller's lock then deletes the repository.
*/
private async watched(
repository: string, url: string, args: readonly string[], signal: AbortSignal, label: string,
repository: CachedRepository, url: string, args: readonly string[], signal: AbortSignal, label: string,
maxBuffer = this.options.maxRepositoryBytes,
): Promise<GitResult> {
const limit = this.options.maxRepositoryBytes
// The limit applies to what one command adds, so a clone that earlier reads filled stays usable.
const before = await sizeOf(repository)
const before = await sizeOf(repository.dir)
const oversized = new AbortController()
const timer = setInterval(() => {
void sizeOf(repository).then((size) => { if (size - before > limit) oversized.abort() }, /* v8 ignore next -- Git renamed or
void sizeOf(repository.dir).then((size) => { if (size - before > limit) oversized.abort() }, /* v8 ignore next -- Git renamed or
deleted a file during the walk, which no test can time; the next tick measures again */ (_racing: unknown) => {})
}, this.options.sizePollMs)
let result: GitResult
try {
result = await this.git(args, repository, signal, oversized.signal, maxBuffer)
result = await this.git(repository, args, signal, oversized.signal, maxBuffer)
} finally {
clearInterval(timer)
}
if (oversized.signal.aborted || (!result.failed && await sizeOf(repository) - before > limit)) {
if (oversized.signal.aborted || (!result.failed && await sizeOf(repository.dir) - before > limit)) {
throw new DetailFailure('too-large', `${url}: one fetch adds more than ${String(limit)} bytes`)
}
if (result.failed && !result.overflowed) throw remoteFailureOf(result, label)
@@ -357,9 +408,8 @@ export class RepositoryCache {
// The repository in use goes last: it is deleted only when it alone exceeds the cache, after its operation ends.
for (const entry of entries.sort((a, b) => Number(a.path === kept) - Number(b.path === kept) || a.used - b.used)) {
if (total <= this.options.maxCacheBytes) return
void this.serialized(entry.path, () => rm(entry.path, { recursive: true, force: true })).catch(/* v8 ignore next -- a
forced recursive delete fails only on file permissions no test sets; the repository stays and is measured again
after the next fetch */ (_unremovable: unknown) => {})
void this.serialized(entry.path, this.options.lifetime, () => rm(entry.path, { recursive: true, force: true }))
.catch(/* v8 ignore next -- a failed eviction leaves the entry for the next size check */ (_error: unknown) => {})
total -= entry.size
}
}
@@ -368,7 +418,9 @@ export class RepositoryCache {
* The regular files directly below a tree path, or the file at a path, with their blob ids; listing reads only trees,
* so it fetches no file contents.
*/
private async files(repository: string, commit: string, path: string | undefined, signal: AbortSignal): Promise<Map<string, string>> {
private async files(
repository: CachedRepository, commit: string, path: string | undefined, signal: AbortSignal,
): Promise<Map<string, string>> {
const listing = (await this.run(repository, ['ls-tree', '-z', commit, ...path === undefined ? [] : ['--', path]], signal)).toString('utf8')
const files = new Map<string, string>()
for (const line of listing.split('\0')) {
@@ -381,13 +433,13 @@ export class RepositoryCache {
/** Read a blob, fetching its contents under the repository size limit when the clone does not hold them yet. */
private async blob(
repository: string, url: string, blob: string, path: string, maxBytes: number, signal: AbortSignal,
repository: CachedRepository, blob: string, path: string, maxBytes: number, signal: AbortSignal,
): Promise<Uint8Array> {
// The buffer stops Git once the contents pass `maxBytes`, so an oversized file never enters memory whole.
const result = await this.watched(repository, url, ['cat-file', 'blob', blob], signal, `git cat-file ${path}`, maxBytes)
const result = await this.watched(repository, repository.url, ['cat-file', 'blob', blob], signal, `git cat-file ${path}`, maxBytes)
if (result.overflowed) throw new FileTooLarge(path, maxBytes)
// Reading a blob can download it, so the cache total is enforced after every read as after every fetch.
await this.evict(repository)
await this.evict(repository.dir)
return result.stdout
}
@@ -395,8 +447,8 @@ export class RepositoryCache {
* Run a Git command on local objects and return its output. A failure, such as a missing Git, a full disk, or a timeout,
* is a plain error: it says nothing about the repository, so no read caches it.
*/
private async run(repository: string, args: readonly string[], signal: AbortSignal, maxBuffer?: number): Promise<Buffer> {
const result = await this.git(args, repository, signal, undefined, maxBuffer)
private async run(repository: GitDirectory, args: readonly string[], signal: AbortSignal, maxBuffer?: number): Promise<Buffer> {
const result = await this.git(repository, args, signal, undefined, maxBuffer)
if (result.failed) throw new Error(`git ${args[0] as string}: ${result.diagnostic}`)
return result.stdout
}
@@ -406,16 +458,21 @@ export class RepositoryCache {
* Cancellation by `signal` or the lifetime rejects with its reason; `stop` ends Git with a failed result.
*/
private async git(
args: readonly string[], cwd: string, signal: AbortSignal, stop?: AbortSignal, maxBuffer = this.options.maxRepositoryBytes,
{ dir, policy }: GitDirectory, args: readonly string[], signal: AbortSignal, stop?: AbortSignal,
maxBuffer = this.options.maxRepositoryBytes,
): Promise<GitResult> {
const env = gitEnv()
// The allowlist also applies after Git rewrites the URL and to lazy object downloads.
if (policy === 'index') env.GIT_ALLOW_PROTOCOL = 'https:ssh'
const safety = [
// An empty `core.askPass` ends Git's askpass lookup where Windows drops the empty `GIT_ASKPASS`, so no dialog opens.
'core.askPass=', 'core.hooksPath=/dev/null', 'core.fsmonitor=false', 'submodule.recurse=false', 'gc.auto=0', 'maintenance.auto=false',
'protocol.allow=never', ...this.options.transports.map(transport => `protocol.${transport}.allow=always`),
...policy === 'index' ? ['http.followRedirects=false'] : [],
].flatMap(setting => ['-c', setting])
const result = await execa('git', [...safety, ...args], {
// A blob's last byte may be a newline, so the output is kept exactly as Git wrote it.
cwd, env: gitEnv(), extendEnv: false, stdin: 'ignore', encoding: 'buffer', stripFinalNewline: false, reject: false,
cwd: dir, env, extendEnv: false, stdin: 'ignore', encoding: 'buffer', stripFinalNewline: false, reject: false,
maxBuffer: { stdout: maxBuffer, stderr: this.options.maxRepositoryBytes },
timeout: this.options.timeoutMs, cancelSignal: AbortSignal.any([signal, this.options.lifetime, ...stop === undefined ? [] : [stop]]),
killDescendants: true, killSignal: 'SIGKILL',
Loaded 100 of 395 files, more files were not shown because too many files have changed in this diff. Show more