From b6aa7b437c8ac319f9ded5ad7c8fcf462b6c29fd Mon Sep 17 00:00:00 2001 From: LegGasai Date: Tue, 3 Nov 2026 18:45:19 +0800 Subject: [PATCH] feat(working-directory): route sandbox, file views, and discovery through the Session workspace root Every consumer that describes the project to the user or draws the write boundary reads rootOf(session) instead of the header directory: the sandbox workspace-write policy, the workspace file service and desktop file drag, the change recorder, the client Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, @ file candidates, the skill catalog, project-instruction discovery, and the LSP workspace. The model's relative paths keep resolving from the current directory. The sandbox policy derives a linked checkout's Git administration directory and common directory from its .git pointer and grants them as extra writable roots; tool executions wait for that derivation through prepare(), and Session creation and directory changes start it early. Windows ACL confinement grants each extra root a standing ACE through a repeatable --writable runner argument instead of refusing the policy. Refs #2658 --- ...-09-13-session-working-directory.i18n.yaml | 4 +- .../2026-09-13-session-working-directory.md | 6 +- ...2026-09-13-session-working-directory.zh.md | 6 +- ...026-11-03-session-workspace-root.i18n.yaml | 11 +- .../2026-11-03-session-workspace-root.md | 10 +- .../2026-11-03-session-workspace-root.zh.md | 10 +- apps/desktop-host/package.json | 3 +- apps/desktop-host/src/file-drag.ts | 15 +- apps/desktop-host/tsconfig.json | 1 + docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 23 +- docs/capability-seams.zh.md | 23 +- docs/config-catalog.md | 20 +- docs/config-catalog.zh.md | 20 +- docs/event-producer-consumer.md | 6 +- docs/event-producer-consumer.zh.md | 6 +- docs/subsystems/deliverables.md | 8 +- docs/subsystems/deliverables.zh.md | 8 +- docs/subsystems/sandbox.md | 28 +- docs/subsystems/sandbox.zh.md | 28 +- docs/subsystems/working-directory.i18n.yaml | 4 +- docs/subsystems/working-directory.md | 2 +- docs/subsystems/working-directory.zh.md | 2 +- docs/subsystems/workspace.md | 4 +- docs/subsystems/workspace.zh.md | 4 +- docs/subsystems/worktrees.i18n.yaml | 4 +- docs/subsystems/worktrees.md | 2 +- docs/subsystems/worktrees.zh.md | 2 +- .../guide.i18n.yaml | 16 ++ .../guide.md | 24 ++ .../guide.zh.md | 24 ++ .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 + packages/api/session-controller/README.zh.md | 2 + packages/api/session-controller/package.json | 4 + .../src/client/sessions/directories.ts | 59 +++++ .../session-controller/src/skill-catalog.ts | 7 +- .../tests/session-skills.host.spec.ts | 23 +- .../api/terminal-controller/README.i18n.yaml | 4 +- packages/api/terminal-controller/README.md | 2 +- packages/api/terminal-controller/README.zh.md | 2 +- packages/api/terminal-controller/src/index.ts | 10 +- packages/api/terminal-controller/src/types.ts | 2 +- .../tests/controller.spec.ts | 24 +- packages/api/workspace-files/README.i18n.yaml | 8 +- packages/api/workspace-files/README.md | 4 +- packages/api/workspace-files/README.zh.md | 4 +- packages/api/workspace-files/package.json | 8 +- packages/api/workspace-files/src/index.ts | 52 ++-- .../api/workspace-files/tests/scope.spec.ts | 53 +++- .../api/workspace-files/tsconfig.host.json | 6 + packages/api/workspace-files/tsconfig.json | 6 + packages/client/tsdown.client.ts | 2 +- packages/client/ui-chat/src/client/apply.ts | 6 +- .../client/ui-chat/src/client/file-path.ts | 8 +- .../src/client/ChangedFiles.tsx | 13 +- .../src/client/Deliverables.tsx | 7 +- .../src/client/PresentedFileCard.tsx | 6 +- .../ui-deliverables/src/client/ReviewTab.tsx | 6 +- .../ui-deliverables/src/present-open.ts | 15 +- .../tests/changed-files-hover.client.spec.tsx | 2 +- .../tests/changes-open.host.spec.ts | 2 +- .../tests/present-open.host.spec.ts | 14 +- .../tests/presented-file-card.client.spec.tsx | 6 +- .../src/client/context-menus.tsx | 7 +- .../client/ui-open-in-app/src/client/index.ts | 12 +- .../src/client/session-reveal.tsx | 3 +- .../tests/context-menu-actions.client.spec.ts | 6 +- .../tests/context-menus.client.spec.ts | 2 +- .../client/ui-reference/src/client/index.ts | 10 +- .../client/ui-sidebar-files/README.i18n.yaml | 8 +- packages/client/ui-sidebar-files/README.md | 4 +- packages/client/ui-sidebar-files/README.zh.md | 4 +- packages/client/ui-sidebar-files/package.json | 9 +- .../src/client/FileNavigator.tsx | 13 +- .../ui-sidebar-files/src/client/FilesBody.tsx | 13 +- .../src/client/NavigatorToggle.tsx | 5 +- .../ui-sidebar-files/tests/mount.client.tsx | 2 +- .../client/ui-sidebar-files/tsconfig.json | 3 + .../ui-tool/src/client/tool/file-menu.ts | 8 +- .../client/ui-workspace/src/client/tree.ts | 7 +- .../agent-instructions/README.i18n.yaml | 4 +- packages/context/agent-instructions/README.md | 2 +- .../context/agent-instructions/README.zh.md | 2 +- .../context/agent-instructions/src/index.ts | 4 +- .../file-reference-local/README.i18n.yaml | 4 +- .../context/file-reference-local/README.md | 4 +- .../context/file-reference-local/README.zh.md | 4 +- .../context/file-reference-local/src/index.ts | 4 +- .../tests/service.spec.ts | 6 +- .../workspace-changes/README.i18n.yaml | 8 +- .../deliverables/workspace-changes/README.md | 6 +- .../workspace-changes/README.zh.md | 6 +- .../workspace-changes/package.json | 23 +- .../workspace-changes/src/index.ts | 25 +- .../workspace-changes/src/paths.ts | 6 +- .../workspace-changes/src/recorder.ts | 66 +++-- .../workspace-changes/src/types.ts | 8 +- .../tests/current-directory.spec.ts | 2 +- .../workspace-changes/tests/git.spec.ts | 10 +- .../tests/loader-composition.spec.ts | 2 +- .../workspace-changes/tests/plugin.spec.ts | 6 +- .../workspace-changes/tests/worktree.spec.ts | 91 +++++++ .../workspace-changes/tsconfig.json | 3 + .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 3 +- .../experimental/client-ui-forge/README.zh.md | 3 +- .../experimental/client-ui-forge/src/panel.ts | 4 +- .../tests/controller.host.spec.ts | 34 ++- .../experimental/worktree/README.i18n.yaml | 4 +- packages/experimental/worktree/README.md | 2 +- packages/experimental/worktree/README.zh.md | 2 +- packages/experimental/worktree/src/index.ts | 16 +- .../worktree/tests/sandbox.spec.ts | 16 +- .../extensions/tool-cordis/src/api-catalog.ts | 20 +- packages/lsp/tool-lsp/README.i18n.yaml | 4 +- packages/lsp/tool-lsp/README.md | 2 +- packages/lsp/tool-lsp/README.zh.md | 2 +- packages/lsp/tool-lsp/src/index.ts | 2 +- .../sandbox/sandbox-local/README.i18n.yaml | 8 +- packages/sandbox/sandbox-local/README.md | 3 +- packages/sandbox/sandbox-local/README.zh.md | 3 +- packages/sandbox/sandbox-local/src/index.ts | 38 ++- .../sandbox-local/tests/acl-grants.spec.ts | 28 ++ .../sandbox/sandbox-local/tests/local.spec.ts | 13 +- .../sandbox/sandbox-policy/README.i18n.yaml | 16 +- packages/sandbox/sandbox-policy/README.md | 10 +- packages/sandbox/sandbox-policy/README.zh.md | 10 +- packages/sandbox/sandbox-policy/package.json | 18 +- packages/sandbox/sandbox-policy/src/index.ts | 171 ++++++++++-- .../sandbox-policy}/tests/admission.spec.ts | 0 .../tests/workspace-root.spec.ts | 246 ++++++++++++++++++ packages/sandbox/sandbox-policy/tsconfig.json | 9 + .../sandbox/sandbox-windows-acl/README.md | 2 +- .../sandbox/sandbox-windows-acl/README.zh.md | 2 +- .../sandbox/sandbox-windows-acl/src/runner.ts | 15 +- .../session/working-directory/package.json | 2 - packages/skill/tool-skill/README.i18n.yaml | 4 +- packages/skill/tool-skill/README.md | 2 +- packages/skill/tool-skill/README.zh.md | 2 +- packages/skill/tool-skill/src/index.ts | 6 +- .../src/working-directory-fixture.ts | 3 + pnpm-lock.yaml | 39 ++- scripts/client-bundle-purity.spec.ts | 2 + scripts/gen-doc-graphs.ts | 4 +- tsconfig.base.json | 1 + 146 files changed, 1426 insertions(+), 466 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.zh.md create mode 100644 packages/api/session-controller/src/client/sessions/directories.ts create mode 100644 packages/deliverables/workspace-changes/tests/worktree.spec.ts rename packages/{session/working-directory => sandbox/sandbox-policy}/tests/admission.spec.ts (100%) create mode 100644 packages/sandbox/sandbox-policy/tests/workspace-root.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml index 5a1a0d4b5a..fa8fc32465 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.i18n.yaml @@ -9,8 +9,8 @@ en: 31fba384d90ce7d2 zh: f8b814868f3280c3 /agent-note-session-working-directory/decision: - en: f8af193899e790ad - zh: b3df4a59727ff3a3 + en: 6456081e9e73dbd2 + zh: 78a46fb83a4f0868 /agent-note-session-working-directory/alternatives-considered: en: f0995feb9b6bcce8 zh: 97417085fd17f70f diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md index bec052f9ec..2ab63673a7 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.md @@ -16,11 +16,11 @@ The `dsh-base` composition mounts `working_directory({ cd? })` globally. The too Required user-context snapshots carry the current value; each committed change attempts to queue a notice through the ordinary Agent inbox. Cancellation or disposal may discard unadmitted notices while the directory event survives for subsequent requests. The original project is the recovery destination when the selected directory disappears. Missing recovery destinations produce an error. Write permissions remain independent. -Subagents capture the parent's current directory or an explicit override and commit their selected directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. Project instructions, skills, and completion follow the effective directory without changing Session identity, grouping, or runtime composition. +Subagents capture the parent's current directory or an explicit override and commit their selected directory after inherited history. Existing processes, terminals, and persistent shells keep their process-local directory. The model's file and process tools follow the effective directory; project instructions, skills, completion, and the sandbox boundary follow the [workspace root](2026-11-03-session-workspace-root.md) without changing Session identity, grouping, or runtime composition. -Live Session skill catalogs and file completion validate through the same directory owner. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directory. Cold skill catalogs read the recorded projection without activating an Agent. +Live Session skill catalogs and file completion validate through the same directory owner, then read the workspace root. These reads can commit recovery and queue its notice before discovery, keeping discovered files and subsequent operations tied to the committed Session directories. Cold skill catalogs read the recorded root projection without activating an Agent. -Web sidebar terminal environment lookup reads the effective directory without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning; the process keeps that directory independently of later Session changes. +Web sidebar terminal environment lookup reads the workspace root without filesystem validation or recovery, so a missing directory does not prevent reconnecting to a retained terminal. New terminal creation validates and recovers through the directory owner before spawning in the workspace root; the process keeps that directory independently of later Session changes. Playwright MCP and Chrome DevTools MCP validate the effective directory when acquiring a Session's MCP connection and use it to launch the server. Later directory changes do not restart the retained server or change its process directory. diff --git a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md index e5254d9525..5c44e98d3f 100644 --- a/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-13-session-working-directory.zh.md @@ -16,11 +16,11 @@ Status: implemented 必需的用户上下文快照携带当前值;每次已提交变更都会尝试通过普通 Agent 收件箱排入通知。取消或销毁可能丢弃尚未进入请求的通知,但目录事件仍然保留,供后续请求使用。所选目录消失时恢复到原始项目。恢复目录也消失时返回错误。写权限保持独立。 -子代理捕获父代理当前目录或显式覆盖值,并在继承历史之后提交选定目录。已有进程、终端和持久 shell 保留进程局部目录。项目指令、技能和补全跟随有效目录,不改变 Session 身份、归属或运行时组合。 +子代理捕获父代理当前目录或显式覆盖值,并在继承历史之后提交选定目录。已有进程、终端和持久 shell 保留进程局部目录。模型的文件与进程工具跟随有效目录;项目指令、技能、补全和沙箱边界跟随[工作区根](2026-11-03-session-workspace-root.zh.md),不改变 Session 身份、归属或运行时组合。 -活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的投影,不激活 Agent。 +活跃 Session 的技能目录与文件补全通过同一个目录 owner 验证目录,再读取工作区根。这些读取可在发现操作之前提交恢复并排入通知,使发现的文件与后续操作关联到已提交的 Session 目录。冷态技能目录读取已记录的根投影,不激活 Agent。 -Web 侧栏终端的环境查询读取有效目录,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录;后续 Session 目录变更不会改变该进程的目录。 +Web 侧栏终端的环境查询读取工作区根,不验证文件系统或执行恢复,因此目录缺失不会阻止重新连接保留的终端。新终端在创建进程前通过目录 owner 验证和恢复目录,并在工作区根中启动;后续 Session 目录变更不会改变该进程的目录。 Playwright MCP 和 Chrome DevTools MCP 在获取 Session 的 MCP 连接时验证有效目录,并在该目录启动服务器。后续目录变更不会重启保留的服务器,也不会改变其进程目录。 diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml index ac78e9858c..a8bf18961e 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.i18n.yaml @@ -11,12 +11,9 @@ /agent-note-session-workspace-root/decision: en: 2aa85360b92e618d zh: 079b815ab1e6ece4 -/agent-note-session-workspace-root/deferred: - en: d8167590081dfa4e - zh: 208630aac853773b /agent-note-session-workspace-root/alternatives-considered: - en: 9d267bf955897821 - zh: 45b7d2cddd34a811 + en: d41da217dfc05ac5 + zh: 3b4a17c255c2c5ae /agent-note-session-workspace-root/consequences: - en: 9a6bdd11a719b7ea - zh: 9350f11c1097804b + en: 726aa3a9da3295c8 + zh: 569cb4c99d644fd2 diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md index 7572674a37..0e9a97e3cc 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.md @@ -16,10 +16,6 @@ Each Session has three directories with one owner each. `header.cwd` remains the Worktree creation enters the checkout through `relocate`; leaving it is the existing `set` back into the original project, which the anchor rule turns into a root change. A child subagent keeps the parent's original project in its header; when the parent's root is another checkout and the child starts inside it, the child relocates into that root, so its root matches the parent's. The user-context snapshot adds a `Workspace root` line while the cursor differs from the root, and a change notice ends with the new root when the change selects another root. The SDK working-directory methods return `{ cwd, root }`, and `getWorkspaceRoot` (`get_workspace_root` in Python) reads the root. -## Deferred - -The sandbox write boundary, the workspace file service, desktop file drag, the change recorder, and the client file tree, deliverables, open-in-app actions, and Session rows still read `header.cwd`. The sidebar terminal, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace still read the current directory although they belong to the root. Until those consumers move, they behave as they did before this decision, and a worktree outside the original project is writable only where the original project's boundary already allows it. - ## Alternatives considered **Rewrite the header on relocation.** The header is identity metadata for storage, grouping, and permission roots; the [working-directory note](2026-09-13-session-working-directory.md) rejected rewriting it, and every peer product keeps an immutable origin. @@ -32,6 +28,10 @@ The sandbox write boundary, the workspace file service, desktop file drag, the c **One new Session per worktree, never a relocation.** The model-facing worktree tool already continues one Session in the new checkout; forge's new-Session worktree path and that tool both resolve to the same relocation. +The consumers divide by who perceives the directory. The model's file, search, and process tools resolve relative paths from the current directory. Everything the user sees or that describes the project reads the workspace root: the sandbox `workspace-write` boundary, the workspace file service and desktop file drag, the change recorder, the Files tree, deliverables, open-in-app actions and Session rows, new sidebar terminals, `@` file candidates, the skill catalog, project-instruction discovery, and the LSP workspace. The user context names the root beside the current directory while they differ, so the model can resolve a user's root-relative `@` reference. + +The sandbox policy derives the Git administration directories of a linked checkout from the root's `.git` pointer and `commondir` through the execution-world filesystem, keeps them per root for the process lifetime, and adds them to the resolved extra writable roots; tool executions wait for that derivation, and Session creation and directory changes start it early. Windows ACL confinement grants each extra root a standing ACE under the workspace SID instead of refusing the policy. After a relocation the original project is writable only through the Git administration directories, not as a whole. + ## Consequences -Consumers can ask the directory service three questions with three answers: where the Session started, which checkout it works in, and where relative paths resolve. Existing logs change meaning for no reader: they hold no anchor, so the root is the original project. Anchors compare as recorded, so a header recorded through a symlink or with different casing never contains the canonical paths later changes record; the root then stays on the original project. The worktree snapshot fixture and the directory notices carry the root text. Moving the consumers listed under Deferred is a separate change. +Consumers can ask the directory service three questions with three answers: where the Session started, which checkout it works in, and where relative paths resolve. Existing logs change meaning for no reader: they hold no anchor, so the root is the original project. Anchors compare as recorded, so a header recorded through a symlink or with different casing never contains the canonical paths later changes record; the root then stays on the original project. A Session opened inside a linked worktree can run `git commit` under `workspace-write`, and the shared `.git`, including its hooks and configuration, is writable from that Session as it already is from a Session in the main checkout. A `cd` inside the root no longer reloads the project-instruction baseline or the skill catalog. The worktree snapshot fixture and the directory notices carry the root text. diff --git a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md index 3603197c8e..0d89538b91 100644 --- a/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-03-session-workspace-root.zh.md @@ -16,10 +16,6 @@ Status: implemented 工作树创建通过 `relocate` 进入检出目录;离开它就是既有的 `set` 回到原始项目,锚规则将其变为根的变化。子代理在 header 中保留父级的原始项目;当父级的根是另一个检出目录且子级在其中启动时,子级迁入该根,因此子级的根与父级一致。光标与根不同时,用户上下文快照增加一行 `Workspace root`,选中另一个根的变更在通知末尾给出新根。SDK 的工作目录方法返回 `{ cwd, root }`,`getWorkspaceRoot`(Python 中为 `get_workspace_root`)读取根。 -## Deferred - -沙箱写边界、工作区文件服务、桌面文件拖拽、变更记录器,以及客户端的文件树、交付物、在应用中打开操作和 Session 行仍读取 `header.cwd`。侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区仍读取当前目录,尽管它们属于根。在这些消费方迁移之前,它们的行为与本决策之前相同,原始项目之外的工作树仅在原始项目的边界已经允许之处可写。 - ## Alternatives considered **迁移时改写 header。** header 是用于存储、分组和权限根的身份元数据;[工作目录记录](2026-09-13-session-working-directory.zh.md)否决了改写它,所有同类产品也都保留不可变的起点。 @@ -32,6 +28,10 @@ Status: implemented **每个工作树一个新 Session,从不迁移。** 面向模型的工作树工具已经让同一个 Session 在新检出目录中继续;forge 的新 Session 工作树路径与该工具最终都落到同一种迁移。 +消费方按感知目录的对象划分。模型的文件、搜索与进程工具从当前目录解析相对路径。用户看到的、以及描述项目的一切都读取工作区根:沙箱 `workspace-write` 边界、工作区文件服务与桌面文件拖拽、变更记录器、文件树、交付物、在应用中打开操作与 Session 行、新开的侧栏终端、`@` 文件候选、技能目录、项目指令发现和 LSP 工作区。光标与根不同时,用户上下文在当前目录旁给出根,使模型能够解析用户以根为基准的 `@` 引用。 + +沙箱策略通过执行环境的文件系统,从根的 `.git` 指针与 `commondir` 推导出链接检出目录的 Git 管理目录,在进程生命周期内按根保留,并加入解析出的额外可写根;工具执行等待该推导完成,会话创建与目录变更提前启动它。Windows ACL 限制为每个额外根添加一条工作区 SID 的常驻 ACE,而不是拒绝该策略。迁移之后,原始项目只能通过 Git 管理目录写入,不再整体可写。 + ## Consequences -消费方可以向目录服务提出三个问题并得到三个答案:Session 从哪里开始、在哪个检出目录中工作、相对路径从哪里解析。既有日志对任何读者的含义都不变:它们没有锚,因此根就是原始项目。锚按记录原样比较,因此通过符号链接或以不同大小写记录的 header 永远不包含后续变更记录的规范路径;此时根停留在原始项目上。工作树快照夹具与目录通知携带根的文本。迁移 Deferred 中列出的消费方是另一次变更。 +消费方可以向目录服务提出三个问题并得到三个答案:Session 从哪里开始、在哪个检出目录中工作、相对路径从哪里解析。既有日志对任何读者的含义都不变:它们没有锚,因此根就是原始项目。锚按记录原样比较,因此通过符号链接或以不同大小写记录的 header 永远不包含后续变更记录的规范路径;此时根停留在原始项目上。在链接工作树内打开的 Session 可以在 `workspace-write` 下运行 `git commit`,共享的 `.git`(包括其钩子与配置)对该 Session 可写,正如它对主检出目录中的 Session 一样。根内部的 `cd` 不再重新加载项目指令基线或技能目录。工作树快照夹具与目录通知携带根的文本。 diff --git a/apps/desktop-host/package.json b/apps/desktop-host/package.json index 9e4d9cc0f4..7b993b86cc 100644 --- a/apps/desktop-host/package.json +++ b/apps/desktop-host/package.json @@ -39,6 +39,7 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@deepseek-ai/dsh-brand": "workspace:*", - "@deepseek-ai/dsh-tool-executor-native": "workspace:*" + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-api-workspace-files": "workspace:*" } } diff --git a/apps/desktop-host/src/file-drag.ts b/apps/desktop-host/src/file-drag.ts index 473ab67e56..f7cf2b8072 100644 --- a/apps/desktop-host/src/file-drag.ts +++ b/apps/desktop-host/src/file-drag.ts @@ -1,9 +1,9 @@ /** Resolve desktop-only file references through the active Host filesystem and Session. */ import { createHash } from 'node:crypto' import type { Context } from '@deepseek-ai/cordis' +import { resolveWorkspaceFileScope } from '@deepseek-ai/dsh-api-workspace-files' import type {} from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-session' -import type {} from '@deepseek-ai/dsh-session-persistence' import type {} from '@deepseek-ai/dsh-sandbox-policy' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { parseFileAddress } from '@deepseek-ai/dsh-util-workspace-path' @@ -17,6 +17,7 @@ export interface LocalDragResource { /** * Authorize an unmodified local file through the composed filesystem's actual read operations. + * Relative paths resolve from the same workspace root the workspace file service uses for the Session. * @param ctx - booted Desktop Host. * @param address - Session-scoped resource reference. * @param cancellation - caller cancellation, combined with the read deadline. @@ -25,17 +26,13 @@ export interface LocalDragResource { export async function localDragResource(ctx: Context, address: string, cancellation?: AbortSignal): Promise { const resource = parseFileAddress(address) if (resource?.scope !== 'session') throw new Error('File drag requires a Session resource') - const sessions = ctx.get('sessions') - const persistence = ctx.get('sessionPersistence') const fs = ctx.get('fs') - const policy = ctx.get('sandboxPolicy') - if (fs === undefined || sessions === undefined || policy === undefined) throw new Error('File access unavailable') - const sessionId = resource.sessionId as SessionId - const header = sessions.get(sessionId)?.header ?? (await persistence?.stat(sessionId))?.header - if (header === undefined) throw new Error('File drag Session unavailable') + if (fs === undefined || ctx.get('sessions') === undefined || ctx.get('sandboxPolicy') === undefined) throw new Error('File access unavailable') const signal = cancellation === undefined ? AbortSignal.timeout(10_000) : AbortSignal.any([cancellation, AbortSignal.timeout(10_000)]) signal.throwIfAborted() - const cwd = header.cwd ?? policy.workspaceRoot + const scope = await resolveWorkspaceFileScope(ctx, resource.sessionId as SessionId, signal) + if (scope === undefined) throw new Error('File drag Session unavailable') + const cwd = scope.workspaceRoot const entry = await fs.lstat(resource.path, { cwd }, signal) if (entry?.type !== 'file') return null const target = await fs.resolve(resource.path, { cwd, signal }) diff --git a/apps/desktop-host/tsconfig.json b/apps/desktop-host/tsconfig.json index 7b88b7a2e8..c255a0f3e2 100644 --- a/apps/desktop-host/tsconfig.json +++ b/apps/desktop-host/tsconfig.json @@ -10,6 +10,7 @@ "references": [ { "path": "../../vendor/cordis" }, { "path": "../../packages/core/agent" }, + { "path": "../../packages/api/workspace-files/tsconfig.host.json" }, { "path": "../../packages/jobs/jobs" }, { "path": "../../packages/schedule/schedule" }, { "path": "../../packages/workspace/workspace" }, diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 1fd6462010..2f4073151b 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: 55650614a3f15f6a - zh: 5c61a3b1085a700e + en: 2a8998fb919f4e2e + zh: eb7d61cb7c66d38c diff --git a/docs/capability-seams.md b/docs/capability-seams.md index e9710bc473..b40a12dbb2 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -54,6 +54,14 @@ flowchart LR pkg_tool_pwsh["tool-pwsh"] pkg_subagent["subagent"] pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"] + pkg_sandbox_policy["sandbox-policy"] + pkg_workspace_files["workspace-files"] + pkg_terminal_controller["terminal-controller"] + pkg_workspace_changes["workspace-changes"] + pkg_file_reference_local["file-reference-local"] + pkg_tool_skill["tool-skill"] + pkg_agent_instructions["agent-instructions"] + pkg_tool_lsp["tool-lsp"] pkg_mcp_resources["mcp-resources"] svc_mcpResources["ctx.mcpResources
Scoped MCP resource access"] pkg_mcp_client["mcp-client"] @@ -112,7 +120,6 @@ flowchart LR svc_settingsController["ctx.settingsController
Host settings-surface Remote controller"] pkg_api_workspace_files["api-workspace-files"] svc_workspaceFiles["ctx.workspaceFiles
Host workspace file Remote service"] - pkg_workspace_changes["workspace-changes"] svc_workspaceChanges["ctx.workspaceChanges
Host per-turn changed-file summaries"] pkg_api_terminal_controller["api-terminal-controller"] svc_terminalController["ctx.terminalController
Session interactive terminal Remote controller"] @@ -170,7 +177,6 @@ flowchart LR pkg_tool_session_query["tool-session-query"] pkg_file_reference["file-reference"] svc_fileReferences["ctx.fileReferences
File reference discovery"] - pkg_file_reference_local["file-reference-local"] svc_sessionReferenceResolver["ctx.sessionReferenceResolver
Cross-session snapshot preparation"] pkg_session_title["session-title"] svc_sessionTitle["ctx.sessionTitle
Log-backed session titles"] @@ -184,7 +190,6 @@ flowchart LR svc_tools["ctx.tools
Scoped tool registry and executor selection"] pkg_tool_ask_user["tool-ask-user"] pkg_tool_cordis["tool-cordis"] - pkg_tool_skill["tool-skill"] pkg_tool_todo["tool-todo"] pkg_user_questions["user-questions"] svc_userQuestions["ctx.userQuestions
Human question/answer seam"] @@ -241,7 +246,6 @@ flowchart LR pkg_sandbox["sandbox"] svc_sandbox["ctx.sandbox
Process-sandbox seam"] pkg_sandbox_local["sandbox-local"] - pkg_sandbox_policy["sandbox-policy"] svc_sandboxPolicy["ctx.sandboxPolicy
Sandbox policy home"] pkg_fs_sandbox["fs-sandbox"] pkg_user_approval["user-approval"] @@ -309,7 +313,6 @@ flowchart LR pkg_webhook_github["webhook-github"] pkg_lsp["lsp"] svc_lsp["ctx.lsp
Language-server navigation seam"] - pkg_tool_lsp["tool-lsp"] pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] @@ -635,12 +638,20 @@ flowchart LR svc_webhookRuntime --> pkg_webhook_github svc_workflowEngine --> pkg_tool_ralph svc_workflowEngine --> pkg_tool_workflow + svc_workingDirectory --> pkg_agent_instructions + svc_workingDirectory --> pkg_file_reference_local + svc_workingDirectory --> pkg_sandbox_policy svc_workingDirectory --> pkg_sdk_jsonrpc_server svc_workingDirectory --> pkg_subagent + svc_workingDirectory --> pkg_terminal_controller svc_workingDirectory --> pkg_tool_bash svc_workingDirectory --> pkg_tool_fs + svc_workingDirectory --> pkg_tool_lsp svc_workingDirectory --> pkg_tool_pwsh + svc_workingDirectory --> pkg_tool_skill svc_workingDirectory --> pkg_tool_working_directory + svc_workingDirectory --> pkg_workspace_changes + svc_workingDirectory --> pkg_workspace_files svc_workspaceRegistry --> pkg_api_session_controller svc_workspaceRegistry --> pkg_api_workspace_controller svc_worktrees --> pkg_experimental_tool_worktree @@ -664,7 +675,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | A Session projection derives bindings from shell results and binding records and publishes their URLs without status to clients; push results trigger head-branch discovery, and Session watchers poll bound change requests through the forge registry. | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | Streams one panel state per followed Session: Git inspection using Session permissions, the recognized code host and its sign-in, and the bound change requests with polled status. | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | Explicit experimental creation from a pinned local commit. Existing write permissions govern checkout and shared Git metadata; the working-directory service owns the resulting Session directory. | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed. | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), `workspace-files`, `terminal-controller`, [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes and user context reports them; model tools follow the directory while the sandbox boundary, file views, and discovery follow the root, and original metadata stays fixed. | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | Connection-owned providers serve shared resource tools in the calling agent scope. | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API. | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index fa32d4784b..1e4f82b24d 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -56,6 +56,14 @@ flowchart LR pkg_tool_pwsh["tool-pwsh"] pkg_subagent["subagent"] pkg_sdk_jsonrpc_server["sdk-jsonrpc-server"] + pkg_sandbox_policy["sandbox-policy"] + pkg_workspace_files["workspace-files"] + pkg_terminal_controller["terminal-controller"] + pkg_workspace_changes["workspace-changes"] + pkg_file_reference_local["file-reference-local"] + pkg_tool_skill["tool-skill"] + pkg_agent_instructions["agent-instructions"] + pkg_tool_lsp["tool-lsp"] pkg_mcp_resources["mcp-resources"] svc_mcpResources["ctx.mcpResources
Scoped MCP resource access"] pkg_mcp_client["mcp-client"] @@ -114,7 +122,6 @@ flowchart LR svc_settingsController["ctx.settingsController
Host settings-surface Remote controller"] pkg_api_workspace_files["api-workspace-files"] svc_workspaceFiles["ctx.workspaceFiles
Host workspace file Remote service"] - pkg_workspace_changes["workspace-changes"] svc_workspaceChanges["ctx.workspaceChanges
Host per-turn changed-file summaries"] pkg_api_terminal_controller["api-terminal-controller"] svc_terminalController["ctx.terminalController
Session interactive terminal Remote controller"] @@ -172,7 +179,6 @@ flowchart LR pkg_tool_session_query["tool-session-query"] pkg_file_reference["file-reference"] svc_fileReferences["ctx.fileReferences
File reference discovery"] - pkg_file_reference_local["file-reference-local"] svc_sessionReferenceResolver["ctx.sessionReferenceResolver
Cross-session snapshot preparation"] pkg_session_title["session-title"] svc_sessionTitle["ctx.sessionTitle
Log-backed session titles"] @@ -186,7 +192,6 @@ flowchart LR svc_tools["ctx.tools
Scoped tool registry and executor selection"] pkg_tool_ask_user["tool-ask-user"] pkg_tool_cordis["tool-cordis"] - pkg_tool_skill["tool-skill"] pkg_tool_todo["tool-todo"] pkg_user_questions["user-questions"] svc_userQuestions["ctx.userQuestions
Human question/answer seam"] @@ -243,7 +248,6 @@ flowchart LR pkg_sandbox["sandbox"] svc_sandbox["ctx.sandbox
Process-sandbox seam"] pkg_sandbox_local["sandbox-local"] - pkg_sandbox_policy["sandbox-policy"] svc_sandboxPolicy["ctx.sandboxPolicy
Sandbox policy home"] pkg_fs_sandbox["fs-sandbox"] pkg_user_approval["user-approval"] @@ -311,7 +315,6 @@ flowchart LR pkg_webhook_github["webhook-github"] pkg_lsp["lsp"] svc_lsp["ctx.lsp
Language-server navigation seam"] - pkg_tool_lsp["tool-lsp"] pkg_cordis_host_runner["cordis-host-runner"] svc_dynamicCordisRunner["ctx.dynamicCordisRunner
Dynamic Cordis package host runner"] svc_cordisInspect["ctx.cordisInspect
Dynamic Cordis inspect registry"] @@ -637,12 +640,20 @@ flowchart LR svc_webhookRuntime --> pkg_webhook_github svc_workflowEngine --> pkg_tool_ralph svc_workflowEngine --> pkg_tool_workflow + svc_workingDirectory --> pkg_agent_instructions + svc_workingDirectory --> pkg_file_reference_local + svc_workingDirectory --> pkg_sandbox_policy svc_workingDirectory --> pkg_sdk_jsonrpc_server svc_workingDirectory --> pkg_subagent + svc_workingDirectory --> pkg_terminal_controller svc_workingDirectory --> pkg_tool_bash svc_workingDirectory --> pkg_tool_fs + svc_workingDirectory --> pkg_tool_lsp svc_workingDirectory --> pkg_tool_pwsh + svc_workingDirectory --> pkg_tool_skill svc_workingDirectory --> pkg_tool_working_directory + svc_workingDirectory --> pkg_workspace_changes + svc_workingDirectory --> pkg_workspace_files svc_workspaceRegistry --> pkg_api_session_controller svc_workspaceRegistry --> pkg_api_workspace_controller svc_worktrees --> pkg_experimental_tool_worktree @@ -666,7 +677,7 @@ flowchart LR | `ctx.forgeSession` | `service` | [`experimental-forge-session`](../packages/experimental/forge-session) | - | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | Session 投影从 shell 结果与绑定记录派生绑定,并把不含状态的 URL 发布给客户端;推送结果触发按 head 分支的发现,Session 监听方通过 forge 注册表轮询已绑定的变更请求。 | | `ctx.forgePanel` | `service` | [`experimental-client-ui-forge`](../packages/experimental/client-ui-forge) | - | - | - | 为每个被跟随的 Session 推送一份面板状态:使用 Session 权限进行的 Git 检查、识别出的代码托管平台及其登录状态,以及带轮询状态的已绑定变更请求。 | | `ctx.worktrees` | `seam` | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-worktree`](../packages/experimental/worktree) | [`experimental-tool-worktree`](../packages/experimental/tool-worktree) | - | 显式实验组合从固定的本地提交创建工作树。检出目录与共享 Git 元数据受现有写权限约束;工作目录服务拥有创建后的 Session 目录。 | -| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server) | - | 两个 Session 投影拥有有效执行目录及其所在的工作区根。文件系统验证变更,用户上下文报告目录信息,原始元数据与写入授权保持不变。 | +| `ctx.workingDirectory` | `seam` | [`working-directory`](../packages/session/working-directory) | [`working-directory`](../packages/session/working-directory) | [`tool-working-directory`](../packages/session/tool-working-directory), [`tool-fs`](../packages/fs/tool-fs), [`tool-bash`](../packages/shell/tool-bash), [`tool-pwsh`](../packages/shell/tool-pwsh), [`subagent`](../packages/subagent/subagent), [`sdk-jsonrpc-server`](../packages/sdk/server), [`sandbox-policy`](../packages/sandbox/sandbox-policy), `workspace-files`, `terminal-controller`, [`workspace-changes`](../packages/deliverables/workspace-changes), [`file-reference-local`](../packages/context/file-reference-local), [`tool-skill`](../packages/skill/tool-skill), [`agent-instructions`](../packages/context/agent-instructions), [`tool-lsp`](../packages/lsp/tool-lsp) | - | 两个 Session 投影拥有有效执行目录及其所在的工作区根。文件系统验证变更并由用户上下文报告;模型工具跟随当前目录,而沙箱边界、文件视图与发现跟随根,原始元数据保持不变。 | | `ctx.mcpResources` | `seam` | [`mcp-resources`](../packages/mcp/mcp-resources) | [`mcp-client`](../packages/mcp/mcp-client) | [`mcp-resources`](../packages/mcp/mcp-resources) | - | 连接所有者提供的操作在调用 agent 的作用域内服务于共享资源工具。 | | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 Session 拥有自己的工具与浏览器资源;共享服务不提供浏览器操作 API。 | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7a775425b4..ed6e315f61 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -362,7 +362,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-files` - `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert` -- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts) +- `source`: [`packages/api/workspace-files/src/index.ts:101`](../packages/api/workspace-files/src/index.ts) ```ts config-catalog /** Deployment caps on one page or one listing. */ @@ -2960,7 +2960,7 @@ export interface Config { - `inject`: `sessionProjections` - `refs`: [`SandboxMode`](subsystems/sandbox.md) -- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:94`](../packages/sandbox/sandbox-policy/src/index.ts) +- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:119`](../packages/sandbox/sandbox-policy/src/index.ts) ```ts config-catalog /** @@ -2974,16 +2974,18 @@ export interface Config { /** File-sandbox mode a session starts from (default: `read-only`). */ mode?: SandboxMode /** - * Absolute fallback root for agentless calls and sessions without a cwd (default: - * `process.cwd()`). Normal agent calls use their session cwd instead. + * Absolute fallback root for agentless calls and sessions without a recorded + * directory (default: `process.cwd()`). Normal agent calls use their + * session's workspace root instead. */ workspaceRoot?: string /** * Extra physical absolute directories that `workspace-write` may also write under - * (default: none). The supervisor names them explicitly; there is no - * automatic repository or gitfile discovery. Entries are execution-world - * paths: this service validates absoluteness and detaches the list, while - * the enforcing host rejects missing, non-directory, or symlinked paths. They grant nothing under + * (default: none). The supervisor names them explicitly; the Git + * administration directories of a linked checkout are derived separately + * and need no entry here. Entries are execution-world paths: this service + * validates absoluteness and detaches the list, while the enforcing host + * rejects missing, non-directory, or symlinked paths. They grant nothing under * `read-only`. */ additionalWritableRoots?: string[] @@ -4859,7 +4861,7 @@ export interface Config { ## `@deepseek-ai/dsh-workspace-changes` - `inject`: `subprocess` · `fs` -- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts) +- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts) ```ts config-catalog /** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index f55feb6b61..377113bb9e 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -364,7 +364,7 @@ export interface Config { ## `@deepseek-ai/dsh-api-workspace-files` - `inject`: `fs` · `sandboxPolicy` · `sessions` · `typert` -- `source`: [`packages/api/workspace-files/src/index.ts:70`](../packages/api/workspace-files/src/index.ts) +- `source`: [`packages/api/workspace-files/src/index.ts:101`](../packages/api/workspace-files/src/index.ts) ```ts config-catalog /** Deployment caps on one page or one listing. */ @@ -2962,7 +2962,7 @@ export interface Config { - `inject`: `sessionProjections` - `refs`: [`SandboxMode`](subsystems/sandbox.zh.md) -- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:94`](../packages/sandbox/sandbox-policy/src/index.ts) +- `source`: [`packages/sandbox/sandbox-policy/src/index.ts:119`](../packages/sandbox/sandbox-policy/src/index.ts) ```ts config-catalog /** @@ -2976,16 +2976,18 @@ export interface Config { /** File-sandbox mode a session starts from (default: `read-only`). */ mode?: SandboxMode /** - * Absolute fallback root for agentless calls and sessions without a cwd (default: - * `process.cwd()`). Normal agent calls use their session cwd instead. + * Absolute fallback root for agentless calls and sessions without a recorded + * directory (default: `process.cwd()`). Normal agent calls use their + * session's workspace root instead. */ workspaceRoot?: string /** * Extra physical absolute directories that `workspace-write` may also write under - * (default: none). The supervisor names them explicitly; there is no - * automatic repository or gitfile discovery. Entries are execution-world - * paths: this service validates absoluteness and detaches the list, while - * the enforcing host rejects missing, non-directory, or symlinked paths. They grant nothing under + * (default: none). The supervisor names them explicitly; the Git + * administration directories of a linked checkout are derived separately + * and need no entry here. Entries are execution-world paths: this service + * validates absoluteness and detaches the list, while the enforcing host + * rejects missing, non-directory, or symlinked paths. They grant nothing under * `read-only`. */ additionalWritableRoots?: string[] @@ -4861,7 +4863,7 @@ export interface Config { ## `@deepseek-ai/dsh-workspace-changes` - `inject`: `subprocess` · `fs` -- `source`: [`packages/deliverables/workspace-changes/src/index.ts:34`](../packages/deliverables/workspace-changes/src/index.ts) +- `source`: [`packages/deliverables/workspace-changes/src/index.ts:35`](../packages/deliverables/workspace-changes/src/index.ts) ```ts config-catalog /** Snapshot, capture, and comparison bounds. Invalid values fail plugin load. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index d344748ffd..6f0744ffc9 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -71,9 +71,9 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`sandbox-policy`](../packages/sandbox/sandbox-policy), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`sandbox-policy`](../packages/sandbox/sandbox-policy), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -86,7 +86,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | | `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes`, `server` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index cee3960282..6d803cc9f9 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -73,9 +73,9 @@ | `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` | | `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` | | `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`sandbox-policy`](../packages/sandbox/sandbox-policy), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) | | `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`sandbox-policy`](../packages/sandbox/sandbox-policy), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) | | `settings/document-updated` | `emit` | [`packages/settings/settings/src/types.ts:75`](../packages/settings/settings/src/types.ts) | [`settings`](../packages/settings/settings) (`emit`) | `remotes` | | `skills/change` | `emit` | [`packages/skill/skill/src/index.ts:296`](../packages/skill/skill/src/index.ts) | [`skill`](../packages/skill/skill) (`events.dispatch`) | - | @@ -88,7 +88,7 @@ | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | | `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | -| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | | `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes`, `server` | diff --git a/docs/subsystems/deliverables.md b/docs/subsystems/deliverables.md index b1e97daa44..2724f285c5 100644 --- a/docs/subsystems/deliverables.md +++ b/docs/subsystems/deliverables.md @@ -25,10 +25,10 @@ interface PresentedFile { ```ts type-equiv /** One file changed during a turn, with line counts from git or from the whole-file captures around its file-tool edits. */ interface WorkspaceChangedFile { - /** Path relative to the Session working directory, or an absolute Host path outside it. */ + /** Path relative to the Session workspace root, or an absolute Host path outside it. */ path: string /** - * Sort key and label: the relative path inside the working directory, a + * Sort key and label: the relative path inside the workspace root, a * `../` path for repository files above it, a `~` path under the home * directory, otherwise the absolute path. Always slash-separated. */ @@ -51,8 +51,8 @@ interface WorkspaceChangedFile { interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ - cwd: string + /** The Session workspace root `path` values are relative to, as it stood when the turn started. */ + root: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] /** Complete changed-file count, including files omitted by the cap. */ diff --git a/docs/subsystems/deliverables.zh.md b/docs/subsystems/deliverables.zh.md index 396b7d8137..e7a8fd05d7 100644 --- a/docs/subsystems/deliverables.zh.md +++ b/docs/subsystems/deliverables.zh.md @@ -25,10 +25,10 @@ interface PresentedFile { ```ts type-equiv /** One file changed during a turn, with line counts from git or from the whole-file captures around its file-tool edits. */ interface WorkspaceChangedFile { - /** Path relative to the Session working directory, or an absolute Host path outside it. */ + /** Path relative to the Session workspace root, or an absolute Host path outside it. */ path: string /** - * Sort key and label: the relative path inside the working directory, a + * Sort key and label: the relative path inside the workspace root, a * `../` path for repository files above it, a `~` path under the home * directory, otherwise the absolute path. Always slash-separated. */ @@ -51,8 +51,8 @@ interface WorkspaceChangedFile { interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ - cwd: string + /** The Session workspace root `path` values are relative to, as it stood when the turn started. */ + root: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] /** Complete changed-file count, including files omitted by the cap. */ diff --git a/docs/subsystems/sandbox.md b/docs/subsystems/sandbox.md index 1b8c843049..17e3e1011c 100644 --- a/docs/subsystems/sandbox.md +++ b/docs/subsystems/sandbox.md @@ -76,7 +76,7 @@ interface SandboxExecutionPolicy { ```ts type-equiv /** Inputs that select the sandbox policy for one capability call. */ interface SandboxPolicyRequest { - /** Calling session; its immutable cwd becomes the workspace boundary. */ + /** Calling session; its workspace root becomes the workspace boundary. */ session?: Session /** Explicit approved mode override, which outranks session policy. */ mode?: SandboxMode @@ -200,17 +200,21 @@ Source: [`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox ### `ctx.sandboxPolicy` — `SandboxPolicyService` -The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session's mode log and immutable cwd travel together to every enforcing capability. +The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session's mode log and workspace root travel together to every enforcing capability. + +A session's workspace root comes from the working-directory service when it is mounted: the checkout the Session works in, which a worktree relocation moves. A linked checkout keeps its Git administration directory and the repository's common directory outside that root; prepare derives them through the execution-world filesystem once per root, and `resolve` adds the derived directories to `additionalWritableRoots`. Tool executions await that derivation in `tools/pre-execute`; Session creation and every directory change start it early. ```ts cordis-catalog /** * Resolve the complete policy for one capability call. An approved explicit * mode outranks the session's last `sandbox/mode` event, which outranks the - * deployment default. A session cwd is its workspace-write boundary; the + * deployment default. A session's workspace root is its workspace-write + * boundary, and the Git administration directories {@link prepare} derived + * for that root join the configured extra writable directories; the * configured root is the fallback for agentless calls and sessions without a - * cwd. + * recorded directory. * @param request - optional session and approved mode override. - * @returns the fully resolved per-call mode and absolute workspace root. + * @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy @@ -220,6 +224,20 @@ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy * @returns the last logged mode, or `undefined` without one. */ overrideOf(session: Session): SandboxMode | undefined + +/** + * Derive the Git administration directories of the session's workspace root + * so the next {@link resolve} grants them: a linked checkout's `.git` file + * names its administration directory, whose `commondir` names the + * repository's common directory. Directories inside the root, missing + * directories, and a root without a `.git` entry add nothing. One derivation + * runs per root; its result is kept once the root's `.git` entry was read, + * and a failed read is logged and retried on the next call. + * @param session - session whose workspace root is inspected. + * @param signal - caller cancellation, checked before and after the shared derivation. + * @returns the derived directories outside the root, canonical in the execution world. + */ +async prepare(session: Session, signal?: AbortSignal): Promise ``` Types: [Session](session.md) diff --git a/docs/subsystems/sandbox.zh.md b/docs/subsystems/sandbox.zh.md index 8141d365c0..a2e46c40dc 100644 --- a/docs/subsystems/sandbox.zh.md +++ b/docs/subsystems/sandbox.zh.md @@ -76,7 +76,7 @@ interface SandboxExecutionPolicy { ```ts type-equiv /** Inputs that select the sandbox policy for one capability call. */ interface SandboxPolicyRequest { - /** Calling session; its immutable cwd becomes the workspace boundary. */ + /** Calling session; its workspace root becomes the workspace boundary. */ session?: Session /** Explicit approved mode override, which outranks session policy. */ mode?: SandboxMode @@ -200,17 +200,21 @@ Source: [`packages/sandbox/sandbox/src/index.ts`](../../packages/sandbox/sandbox ### `ctx.sandboxPolicy` — `SandboxPolicyService` -The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session's mode log and immutable cwd travel together to every enforcing capability. +The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session's mode log and workspace root travel together to every enforcing capability. + +A session's workspace root comes from the working-directory service when it is mounted: the checkout the Session works in, which a worktree relocation moves. A linked checkout keeps its Git administration directory and the repository's common directory outside that root; prepare derives them through the execution-world filesystem once per root, and `resolve` adds the derived directories to `additionalWritableRoots`. Tool executions await that derivation in `tools/pre-execute`; Session creation and every directory change start it early. ```ts cordis-catalog /** * Resolve the complete policy for one capability call. An approved explicit * mode outranks the session's last `sandbox/mode` event, which outranks the - * deployment default. A session cwd is its workspace-write boundary; the + * deployment default. A session's workspace root is its workspace-write + * boundary, and the Git administration directories {@link prepare} derived + * for that root join the configured extra writable directories; the * configured root is the fallback for agentless calls and sessions without a - * cwd. + * recorded directory. * @param request - optional session and approved mode override. - * @returns the fully resolved per-call mode and absolute workspace root. + * @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy @@ -220,6 +224,20 @@ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy * @returns the last logged mode, or `undefined` without one. */ overrideOf(session: Session): SandboxMode | undefined + +/** + * Derive the Git administration directories of the session's workspace root + * so the next {@link resolve} grants them: a linked checkout's `.git` file + * names its administration directory, whose `commondir` names the + * repository's common directory. Directories inside the root, missing + * directories, and a root without a `.git` entry add nothing. One derivation + * runs per root; its result is kept once the root's `.git` entry was read, + * and a failed read is logged and retried on the next call. + * @param session - session whose workspace root is inspected. + * @param signal - caller cancellation, checked before and after the shared derivation. + * @returns the derived directories outside the root, canonical in the execution world. + */ +async prepare(session: Session, signal?: AbortSignal): Promise ``` Types: [Session](session.zh.md) diff --git a/docs/subsystems/working-directory.i18n.yaml b/docs/subsystems/working-directory.i18n.yaml index dd96f83e3c..3511bc83e2 100644 --- a/docs/subsystems/working-directory.i18n.yaml +++ b/docs/subsystems/working-directory.i18n.yaml @@ -6,8 +6,8 @@ en: 0882d8b4c09c2890 zh: a75af7ce19f661fa /working-directory/directory-selection: - en: d0461ccad1bf9474 - zh: f503835eb2937e3e + en: d98d6c3190ad2245 + zh: ddce20f8bf6f491e /working-directory/model-context: en: 2c27d5dfe7abbd4c zh: 4e6dc26dff03edad diff --git a/docs/subsystems/working-directory.md b/docs/subsystems/working-directory.md index d583fbd69e..66feeb6425 100644 --- a/docs/subsystems/working-directory.md +++ b/docs/subsystems/working-directory.md @@ -10,7 +10,7 @@ A Session's active directory is owned by [`dsh-working-directory`](../../package `rootOf(session)` reads the workspace root: the longest registered anchor that contains the current directory. The anchors are the original project and every checkout `relocate(agent, root, { cwd? })` entered; that operation validates the root and the directory inside it, then records both in one `working-directory/change` whose `anchor` names the root. `anchorsOf(session)` lists them. A `set` inside the root moves only the current directory; a `set` into another anchor selects that anchor as the root; a `set` outside every anchor leaves the root unchanged. Recovery to the original project selects it as the root again. Anchors are compared as recorded. -Changes are local to one Session. Relative filesystem operations, newly started processes, instruction discovery, skills, and file completion use the active directory. Existing terminals and persistent shells retain their own directories. Sandbox writable roots and project membership remain anchored to the original project. +Changes are local to one Session. The model's relative filesystem operations and the processes its tools start use the current directory. What the user sees follows the workspace root: the sandbox `workspace-write` boundary, the Files tree and directory listings, the change summaries, new sidebar terminals, `@` file completion, the skill catalog, project-instruction discovery, and the LSP workspace. Existing terminals and persistent shells retain their own directories. Project membership remains anchored to the original project. ## Model context diff --git a/docs/subsystems/working-directory.zh.md b/docs/subsystems/working-directory.zh.md index fc6cf9ef72..6fc100466c 100644 --- a/docs/subsystems/working-directory.zh.md +++ b/docs/subsystems/working-directory.zh.md @@ -10,7 +10,7 @@ Session 的当前目录由 [`dsh-working-directory`](../../packages/session/work `rootOf(session)` 读取工作区根:包含当前目录的最长已登记锚。锚是原始项目以及 `relocate(agent, root, { cwd? })` 进入过的每个检出目录;该操作验证根及其内部的目录,然后用一条 `anchor` 指向该根的 `working-directory/change` 同时记录两者。`anchorsOf(session)` 列出这些锚。根内部的 `set` 只移动当前目录;进入另一个锚的 `set` 把该锚选为根;所有锚之外的 `set` 不改变根。恢复到原始项目时再次把它选为根。锚按记录的原样比较。 -变更仅影响一个 Session。相对路径文件系统操作、新启动的进程、指令发现、技能和文件补全使用当前目录。已有终端和持久 shell 保留自己的目录。沙箱可写根目录与项目归属继续绑定原始项目。 +变更仅影响一个 Session。模型的相对路径文件系统操作以及其工具启动的进程使用当前目录。用户看到的内容跟随工作区根:沙箱 `workspace-write` 边界、文件树与目录列举、变更摘要、新开的侧栏终端、`@` 文件补全、技能目录、项目指令发现和 LSP 工作区。已有终端和持久 shell 保留自己的目录。项目归属继续绑定原始项目。 ## 模型上下文 diff --git a/docs/subsystems/workspace.md b/docs/subsystems/workspace.md index b363ba184d..665dc1011c 100644 --- a/docs/subsystems/workspace.md +++ b/docs/subsystems/workspace.md @@ -236,10 +236,10 @@ Typed Remote control of transient Session-owned terminal processes. ```ts cordis-catalog /** - * Read the Session's current directory and terminal limits without filesystem validation or shell lookup. + * Read the Session's workspace root and terminal limits without filesystem validation or shell lookup. * @param agent - Session owner supplied by the Gateway. * @param signal - request cancellation. - * @returns the logged current directory and terminal limits; retained terminals keep their own process directories. + * @returns the logged workspace root and terminal limits; retained terminals keep their own process directories. */ @Remote environment(agent: Agent, signal: AbortSignal): TerminalEnvironment diff --git a/docs/subsystems/workspace.zh.md b/docs/subsystems/workspace.zh.md index c04a05c97d..84c7ee7a62 100644 --- a/docs/subsystems/workspace.zh.md +++ b/docs/subsystems/workspace.zh.md @@ -236,10 +236,10 @@ Typed Remote control of transient Session-owned terminal processes. ```ts cordis-catalog /** - * Read the Session's current directory and terminal limits without filesystem validation or shell lookup. + * Read the Session's workspace root and terminal limits without filesystem validation or shell lookup. * @param agent - Session owner supplied by the Gateway. * @param signal - request cancellation. - * @returns the logged current directory and terminal limits; retained terminals keep their own process directories. + * @returns the logged workspace root and terminal limits; retained terminals keep their own process directories. */ @Remote environment(agent: Agent, signal: AbortSignal): TerminalEnvironment diff --git a/docs/subsystems/worktrees.i18n.yaml b/docs/subsystems/worktrees.i18n.yaml index 5e1792d9c3..1c814fd63d 100644 --- a/docs/subsystems/worktrees.i18n.yaml +++ b/docs/subsystems/worktrees.i18n.yaml @@ -6,8 +6,8 @@ en: 60090e418482277a zh: 65db84704ed19c2d /git-worktrees/creation-and-retention: - en: 195894ced2e675dc - zh: 5ed3a6ff729496c2 + en: 8658dff762819f6b + zh: 01f84a68b7ff9c59 /git-worktrees/request-and-result: en: fbab866bf824d6e0 zh: 73d2a1ee350e1434 diff --git a/docs/subsystems/worktrees.md b/docs/subsystems/worktrees.md index 5b40b70298..556437f4af 100644 --- a/docs/subsystems/worktrees.md +++ b/docs/subsystems/worktrees.md @@ -8,7 +8,7 @@ The experimental [`dsh-experimental-worktree`](../../packages/experimental/workt The calling Session's current directory selects the source repository. Creation pins the requested local commit, branch, or tag before allocating the checkout; omission selects `HEAD`. Each name must identify a new branch and an unused checkout path. The operation neither fetches missing objects nor copies staged, unstaged, untracked, or ignored files from the source checkout. -The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s existing sandbox policy must permit writes to the destination and shared Git administration directory. Successful Git setup precedes the working-directory relocation. +The default destination is `/.agents/worktrees/`. `repositoryRoot` is the top-level directory of the caller’s current checkout; a linked checkout therefore contains its own pool. The service writes a `.gitignore` containing `*` and a trailing newline only when its allocation creates the configured pool directory. Existing files and ignore rules are preserved. The calling Session’s resolved sandbox policy must permit writes to the destination and shared Git administration directory; for a linked checkout the [sandbox policy](sandbox.md) grants that directory before creation writes. Successful Git setup precedes the working-directory relocation. Leaving through `working_directory({ cd: path })` retains the checkout and branch. Cancellation or failure can also retain partial artifacts; the error identifies their location. The service aborts and drains pending operations on disposal. The [package README](../../packages/experimental/worktree/README.md) owns configuration and Git requirements. diff --git a/docs/subsystems/worktrees.zh.md b/docs/subsystems/worktrees.zh.md index bb9e3a4721..842813aa3e 100644 --- a/docs/subsystems/worktrees.zh.md +++ b/docs/subsystems/worktrees.zh.md @@ -8,7 +8,7 @@ 调用方 Session 的当前目录决定源仓库。创建操作在分配检出目录前,将请求的本地提交、分支或标签固定为具体提交;省略时选择 `HEAD`。每个名称必须对应新分支与未使用的检出路径。操作既不获取缺失对象,也不复制源检出目录中的暂存、未暂存、未跟踪或被忽略文件。 -默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 的现有沙箱策略必须允许写入目标目录与共享 Git 管理目录。Git 初始化成功后才迁移工作目录。 +默认目标为 `/.agents/worktrees/`。`repositoryRoot` 是调用方当前检出目录的顶层目录;因此,链接检出目录会在自身内部保存工作树父目录。仅当服务的分配操作创建了配置指定的父目录时,服务才会写入内容为 `*` 加换行符的 `.gitignore`。已有文件与忽略规则保持不变。调用方 Session 解析后的沙箱策略必须允许写入目标目录与共享 Git 管理目录;对于链接检出目录,[沙箱策略](sandbox.zh.md)会在创建写入之前授权该目录。Git 初始化成功后才迁移工作目录。 通过 `working_directory({ cd: path })` 离开时,会保留检出目录与分支。取消或失败也可能留下部分产物;错误会指出它们的位置。服务销毁时会中止待完成操作并等待它们结束。[包 README](../../packages/experimental/worktree/README.zh.md)拥有配置与 Git 要求。 diff --git a/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.i18n.yaml new file mode 100644 index 0000000000..68e44ac54c --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.md +/: + en: f131cda0e3227062 + zh: 5572dc4578fee32c +/the-workspace-write-boundary-follows-the-session-s-workspace-root: + en: ec12813704224d37 + zh: eaa9928729aa7b2b +/the-workspace-write-boundary-follows-the-session-s-workspace-root/change: + en: e2598f5769c9c133 + zh: efaac55c356b43b5 +/the-workspace-write-boundary-follows-the-session-s-workspace-root/migration: + en: 6f499a1dca41de9b + zh: 76c99218e0832771 diff --git a/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.md b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.md new file mode 100644 index 0000000000..df0753d0e0 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: "The workspace-write boundary follows the Session's workspace root instead of its original project, and a linked worktree's Git directories become writable." +--- +# The `workspace-write` boundary follows the Session's workspace root + +English | [中文](guide.zh.md) + +## Change + +`ctx.sandboxPolicy.resolve({ session })` returns the Session's workspace root as `workspaceRoot`: the checkout the Session works in. Before, it returned the original project recorded in the Session header for the whole Session. A Session that enters a worktree through `create_worktree` or the forge New worktree option can now write only inside that worktree; the original project is no longer writable as a whole, and a `cd` inside the root does not move the boundary. + +For a linked worktree, the policy derives the checkout's Git administration directory and the repository's common directory from its `.git` pointer and `commondir`, and adds them to `additionalWritableRoots`, so `git commit` and `git checkout` work inside a worktree under `workspace-write`. That grant also covers the shared `.git/hooks` and `.git/config`, as a Session in the main checkout already had. Windows ACL confinement accepts additional writable roots instead of failing with `SANDBOX_UNSUPPORTED_POLICY`. + +The Files tree, directory listings and watches, deliverables and change summaries, new sidebar terminals, `@` file completion, the skill catalog, project-instruction discovery, and the LSP workspace read the same root. `WorkspaceChangesSummary.cwd` is replaced by `root`, and `TerminalEnvironment.cwd` names the root. + +Who observes it: operators who relied on a worktree Session still writing its original project, deployments that granted a worktree's `.git` through `additionalWritableRoots`, and Host plugins that read `WorkspaceChangesSummary.cwd`. + +## Migration + +1. Remove `additionalWritableRoots` entries that only named a linked worktree's `.git/worktrees/` or common `.git` directory from `cordis.yml`; keep entries for unrelated directories. +2. Where a task must write the original project after entering a worktree, change back with `working_directory({ cd: "" })` or keep the Session in the original project; the boundary follows that change. +3. Replace reads of `WorkspaceChangesSummary.cwd` with `root` in Host plugins that consume `ctx.workspaceChanges.summary`. +4. Confirm: in a Session opened inside a linked worktree, `git commit` succeeds under `workspace-write`, and the runtime context shows `Additional writable directories` naming the repository's `.git`; after `create_worktree`, a write to the original project outside the worktree is denied. diff --git a/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.zh.md new file mode 100644 index 0000000000..6cba140a36 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.3/workspace-write-boundary-follows-root/guide.zh.md @@ -0,0 +1,24 @@ +--- +kind: upgrade-guide +description: "workspace-write 边界跟随 Session 的工作区根而不是原始项目,链接 worktree 的 Git 目录变为可写。" +--- +# `workspace-write` 边界跟随 Session 的工作区根 + +[English](guide.md) | 中文 + +## 变更 + +`ctx.sandboxPolicy.resolve({ session })` 返回的 `workspaceRoot` 是 Session 的工作区根,即它所在的检出目录。此前整个 Session 期间返回的都是 Session header 记录的原始项目。通过 `create_worktree` 或 forge 的"新建工作树"选项进入 worktree 的 Session 现在只能在该 worktree 内写入;原始项目不再整体可写,根内部的 `cd` 不会移动边界。 + +对于链接 worktree,策略从其 `.git` 指针与 `commondir` 推导出检出目录的 Git 管理目录和仓库公共目录,并加入 `additionalWritableRoots`,因此在 `workspace-write` 下可以在 worktree 内运行 `git commit` 与 `git checkout`。该授权也覆盖共享的 `.git/hooks` 与 `.git/config`,与主检出目录中的 Session 此前拥有的权限相同。Windows ACL 限制接受额外可写根目录,不再以 `SANDBOX_UNSUPPORTED_POLICY` 失败。 + +文件树、目录列举与监听、交付物与变更摘要、新开的侧栏终端、`@` 文件补全、技能目录、项目指令发现和 LSP 工作区读取同一个根。`WorkspaceChangesSummary.cwd` 由 `root` 取代,`TerminalEnvironment.cwd` 表示该根。 + +受影响者:依赖 worktree Session 仍可写入原始项目的运维人员、通过 `additionalWritableRoots` 授权 worktree `.git` 的部署,以及读取 `WorkspaceChangesSummary.cwd` 的 Host 插件。 + +## 迁移 + +1. 从 `cordis.yml` 中删除只为链接 worktree 的 `.git/worktrees/` 或公共 `.git` 目录而设置的 `additionalWritableRoots` 条目;保留无关目录的条目。 +2. 任务在进入 worktree 后仍需写入原始项目时,用 `working_directory({ cd: "<原始项目>" })` 切换回去,或让 Session 留在原始项目中;边界跟随该变更。 +3. 在消费 `ctx.workspaceChanges.summary` 的 Host 插件中,把对 `WorkspaceChangesSummary.cwd` 的读取改为 `root`。 +4. 确认:在链接 worktree 内打开的 Session 中,`workspace-write` 下 `git commit` 成功,运行时上下文的 `Additional writable directories` 列出仓库的 `.git`;`create_worktree` 之后,对 worktree 之外原始项目的写入被拒绝。 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 38ebd48e01..582a112b0e 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -18,8 +18,8 @@ en: 300f02be359a3170 zh: ac7fb4abbe78eddf /session-controller/client-references: - en: e8979a803ec3e194 - zh: c567efcd971728ba + en: 361c7b7c797c9d2b + zh: b66b5c926760bfc0 /session-controller/session-media-references: en: 954923654eebe2dc zh: 6bd9a7d2ea965aed diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index 960c9bde1f..8fb3e472a4 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -85,6 +85,8 @@ The controller composes `ArchivedSessionGate` through `ctx.plugin`: it loads onc References keep local Session data, scoped Contexts, and history streams alive, not Host Agents. Ordinary Session retention never adds a catalog row. Retained subagents with a known direct-parent address keep a fallback row and notify list readers even before the parent catalog arrives; these rows do not join Host-list membership. Fork-title assignment sends rename directly and applies the returned title projection without retaining the child or opening its history. Final release withdraws the generation before teardown; later acquisition can create a new generation with the same id. `binding(id)` and `scope(id)` only borrow an existing generation. `retainInfo(id)` observes stable read-only source counts independently of catalog membership and performs no history I/O. Consumer source keys are declaration-merge extensible; navigation and completion acknowledgement belong to UI consumers, not this Controller. See [Client Session references](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.md) for ownership and teardown rules. An unknown-mode subagent address permits history reads with direct-parent consistency validation; access is checked separately on the child Session. Successful descriptor restoration determines the displayed mode; failures remain local to the child. Control requests carry only the target id, and the Host checks continuation availability. Client snapshots retain only the subagent address; runtime admission owns continuation availability. +`@deepseek-ai/dsh-api-session-controller/client/directories` exports the import-free directory readers client plugins inline instead of importing this plugin's bundle: `selectSessionRoot(state, sessionId)` selects a Session's workspace root from a list snapshot (the projected `workspaceRoot`, else the row's header directory) for `useSessions` selectors, and `sessionDirectories(sessions, sessionId)` reads the original project, the workspace root, and the current directory at gesture time from the connected Session's projection faces before the list snapshot. File views, address bases, and open-in-app actions read the root; only the model's relative paths follow the current directory. + ## Session media references diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 5b18b4aa38..8545e21422 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -85,6 +85,8 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 引用保活本地会话数据、作用域 Context 和历史流,不保活 Host Agent。普通 Session 不因保留引用而添加目录行。已保留且具有明确直接父子地址的 subagent 即使尚未收到父目录,也会保留兜底行并通知列表读取方;这些行不加入 Host 列表成员集合。Fork 标题设置直接发送 rename 并应用返回的标题投影,不 retain 子会话,也不打开其历史。最后一个引用释放时,generation 先退出可访问映射,再执行清理;后续获取可以为同一 id 创建新 generation。`binding(id)` 和 `scope(id)` 只借用已有 generation。`retainInfo(id)` 独立于目录成员关系观察稳定的只读来源计数,不执行历史 I/O。消费方来源键可通过声明合并扩展;导航和完成确认属于 UI 消费方,不属于本控制器。所有权与清理规则见 [Client 会话引用](../../../.agents/notes/implemented/architecture/2026-09-15-client-session-references.zh.md)。 模式未知的子代理地址允许读取历史,但仍校验直接父级的一致性;访问权单独按子 Session 检查。成功恢复 descriptor 后确定展示模式;失败只影响该子会话。控制请求仅携带目标 id,由 Host 检查是否支持继续执行。Client 快照仅保留子代理地址;是否能接收续接输入由运行时校验。 +`@deepseek-ai/dsh-api-session-controller/client/directories` 导出无运行时导入的目录读取函数,客户端插件内联它们而不是导入本插件的 bundle:`selectSessionRoot(state, sessionId)` 从列表快照选出 Session 的工作区根(投影的 `workspaceRoot`,否则为该行的 header 目录),供 `useSessions` 选择器使用;`sessionDirectories(sessions, sessionId)` 在手势发生时先读已连接 Session 的投影面、再读列表快照,返回原始项目、工作区根与当前目录。文件视图、地址基准与在应用中打开操作读取根;只有模型的相对路径跟随当前目录。 + ## 会话媒体引用 diff --git a/packages/api/session-controller/package.json b/packages/api/session-controller/package.json index 30e143744e..b8bcc1e0e9 100644 --- a/packages/api/session-controller/package.json +++ b/packages/api/session-controller/package.json @@ -30,6 +30,10 @@ "types": "./lib/types/client/index.d.ts", "default": "./lib/client.js" }, + "./client/directories": { + "types": "./lib/types/client/sessions/directories.d.ts", + "default": "./lib/types/client/sessions/directories.js" + }, "./typert": { "types": "./lib/typert.host.d.ts", "default": "./lib/typert.host.js" diff --git a/packages/api/session-controller/src/client/sessions/directories.ts b/packages/api/session-controller/src/client/sessions/directories.ts new file mode 100644 index 0000000000..f476cdea0b --- /dev/null +++ b/packages/api/session-controller/src/client/sessions/directories.ts @@ -0,0 +1,59 @@ +/** + * The directories of one Session as the Client knows them: the list row's + * header directory and the projected root and cursor. Pure reads with + * type-only imports, so client plugins inline this module instead of + * requesting a module-table row this package does not publish. + * @module @deepseek-ai/dsh-api-session-controller/client/directories + */ +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { ISessions } from '../contract/sessions.ts' +import type { SessionListState } from './service.ts' + +/** Where a Session started, which checkout it works in, and where its relative paths resolve. */ +export interface SessionDirectories { + /** The original project the Session header records; undefined for a row without one. */ + readonly original: string | undefined + /** + * The workspace root: the checkout the Session works in, which file views and address bases use; + * the original project before any relocation. + */ + readonly root: string | undefined + /** The current directory the model's relative paths resolve from; the root while the Session reports none. */ + readonly cwd: string | undefined +} + +/** A projected string value by key, from a values object whose keys the Client compilation does not declare. */ +function projectedString(values: object | undefined, key: string): string | undefined { + if (values === undefined) return undefined + const value: unknown = Reflect.get(values, key) + return typeof value === 'string' ? value : undefined +} + +/** + * Select a Session's workspace root from a list snapshot, for `useSessions` selectors. + * @param state - the sessions list snapshot. + * @param sessionId - the Session whose root is selected. + * @returns the projected `workspaceRoot`, else the header directory, else undefined for an unknown row. + */ +export function selectSessionRoot(state: SessionListState, sessionId: SessionId): string | undefined { + return projectedString(state.projectionsBySession[sessionId]?.values, 'workspaceRoot') + ?? projectedString(state.byId[sessionId]?.projectionValues, 'workspaceRoot') + ?? state.byId[sessionId]?.cwd +} + +/** + * Read a Session's directories at gesture time: the connected Session's projection faces first, then the list snapshot. + * @param sessions - the sessions service. + * @param sessionId - the Session whose directories are read. + * @returns the original project, the workspace root, and the current directory, each undefined when unknown. + */ +export function sessionDirectories(sessions: ISessions, sessionId: SessionId): SessionDirectories { + const state = sessions.list.getSnapshot() + const original = state.byId[sessionId]?.cwd + const projections = sessions.binding(sessionId)?.session.projections + const liveRoot: unknown = projections?.faceOf('workspaceRoot').getSnapshot() + const root = (typeof liveRoot === 'string' ? liveRoot : undefined) ?? selectSessionRoot(state, sessionId) ?? original + const liveCwd: unknown = projections?.faceOf('workingDirectory').getSnapshot() + const cwd = (typeof liveCwd === 'string' ? liveCwd : undefined) ?? root + return { original, root, cwd } +} diff --git a/packages/api/session-controller/src/skill-catalog.ts b/packages/api/session-controller/src/skill-catalog.ts index c9865b0e6b..d3570c6101 100644 --- a/packages/api/session-controller/src/skill-catalog.ts +++ b/packages/api/session-controller/src/skill-catalog.ts @@ -42,12 +42,15 @@ export class SessionSkillCatalog extends TypertRemoteService { if (observation.projections === undefined) { throw new Error('skill catalog requires a projected Session observation') } - cwd = observation.projections.values.workingDirectory + cwd = observation.projections.values.workspaceRoot ?? observation.header.cwd ?? this.ctx.workingDirectory.defaultDirectory agentPreset = observation.projections.values.agentPreset ?? undefined const live = this.ctx.agents.get(sessionId) - if (live !== undefined) cwd = await this.ctx.workingDirectory.ensure(live, signal) + if (live !== undefined) { + await this.ctx.workingDirectory.ensure(live, signal) + cwd = this.ctx.workingDirectory.rootOf(live.session) + } } catch (error: unknown) { if (error instanceof SessionQueryError && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') { diff --git a/packages/api/session-controller/tests/session-skills.host.spec.ts b/packages/api/session-controller/tests/session-skills.host.spec.ts index 5181f37c7b..abda13f220 100644 --- a/packages/api/session-controller/tests/session-skills.host.spec.ts +++ b/packages/api/session-controller/tests/session-skills.host.spec.ts @@ -11,7 +11,7 @@ import { SessionSkillCatalog } from '../src/skill-catalog.ts' function observation( sessionId: SessionId, - options: { readonly cwd?: string; readonly workingDirectory?: string | null; readonly agentPreset?: string } = {}, + options: { readonly cwd?: string; readonly workspaceRoot?: string | null; readonly agentPreset?: string } = {}, ): SessionObservation { const events = Object.freeze([]) const lease = (): SessionObservation => ({ @@ -30,7 +30,7 @@ function observation( asOfSeq: -1, values: { ...options.agentPreset === undefined ? {} : { agentPreset: options.agentPreset }, - ...options.workingDirectory === undefined ? {} : { workingDirectory: options.workingDirectory }, + ...options.workspaceRoot === undefined ? {} : { workspaceRoot: options.workspaceRoot }, }, }, retain: lease, @@ -49,10 +49,10 @@ async function context(): Promise { } describe('SessionSkillCatalog', () => { - it('reads a moved cold Session catalog from its recorded current directory without resuming an Agent', async () => { + it('reads a moved cold Session catalog from its recorded workspace root without resuming an Agent', async () => { const ctx = await context() const sessionId = SessionId('cold-skills') - const observed = observation(sessionId, { cwd: '/cold/original', workingDirectory: '/cold/project' }) + const observed = observation(sessionId, { cwd: '/cold/original', workspaceRoot: '/cold/project' }) const dispose = vi.spyOn(observed, Symbol.dispose) const observeSession = vi.fn(() => Promise.resolve(observed)) ctx.provide('sessionQuery', { observeSession } as never) @@ -93,18 +93,18 @@ describe('SessionSkillCatalog', () => { }) it.each([ - { cwd: undefined, workingDirectory: '/cold/current', expected: '/cold/current' }, - { cwd: '/cold/original', workingDirectory: null, expected: '/cold/original' }, - { cwd: undefined, workingDirectory: null, expected: '/catalog/default' }, - { cwd: undefined, workingDirectory: undefined, expected: '/catalog/default' }, - ])('resolves cold directory metadata $cwd / $workingDirectory to $expected without filesystem checks', async ({ cwd, workingDirectory, expected }) => { + { cwd: undefined, workspaceRoot: '/cold/current', expected: '/cold/current' }, + { cwd: '/cold/original', workspaceRoot: null, expected: '/cold/original' }, + { cwd: undefined, workspaceRoot: null, expected: '/catalog/default' }, + { cwd: undefined, workspaceRoot: undefined, expected: '/catalog/default' }, + ])('resolves cold directory metadata $cwd / $workspaceRoot to $expected without filesystem checks', async ({ cwd, workspaceRoot, expected }) => { const ctx = await context() try { const sessionId = SessionId('cold-directory-fallback') ctx.provide('sessionQuery', { observeSession: () => Promise.resolve(observation(sessionId, { ...cwd === undefined ? {} : { cwd }, - ...workingDirectory === undefined ? {} : { workingDirectory }, + ...workspaceRoot === undefined ? {} : { workspaceRoot }, })), } as never) const list = vi.fn(() => Promise.resolve([])) @@ -150,7 +150,8 @@ describe('SessionSkillCatalog', () => { modelInvocable: false, }], }) - expect(scopedList).toHaveBeenCalledWith({ cwd: '/live/current', scope: agent }) + // The live catalog reads the Session's workspace root after the directory was validated, not the validated cursor. + expect(scopedList).toHaveBeenCalledWith({ cwd: '/live/project', scope: agent }) expect(ensureDirectory).toHaveBeenCalledWith(agent, expect.any(AbortSignal)) expect(session.header.cwd).toBe('/live/project') expect(acquireScope).not.toHaveBeenCalled() diff --git a/packages/api/terminal-controller/README.i18n.yaml b/packages/api/terminal-controller/README.i18n.yaml index c7bad45785..1d38ab9332 100644 --- a/packages/api/terminal-controller/README.i18n.yaml +++ b/packages/api/terminal-controller/README.i18n.yaml @@ -9,8 +9,8 @@ en: d5eb7912c65b4e26 zh: 7deb2a8167a82c90 /deepseek-ai-dsh-api-terminal-controller/summary: - en: afcf6f0d2f899ecc - zh: e38e2c0830e42ac9 + en: b894229b0a468b8c + zh: cd55581c0db30bb4 /deepseek-ai-dsh-api-terminal-controller/table-of-contents: en: d152484eb41ac6b4 zh: 1fa9a72d1ee045cc diff --git a/packages/api/terminal-controller/README.md b/packages/api/terminal-controller/README.md index d4f4f7ac0c..523955baaa 100644 --- a/packages/api/terminal-controller/README.md +++ b/packages/api/terminal-controller/README.md @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -Open the execution environment's default shell in the Session's current working directory from the Web sidebar. Reconnect to existing processes and close their complete provider-owned process ranges. Terminal output stays outside the Agent transcript. Keeping a terminal open retains its process and a bounded screen buffer. +Open the execution environment's default shell in the Session's workspace root from the Web sidebar. Reconnect to existing processes and close their complete provider-owned process ranges. Terminal output stays outside the Agent transcript. Keeping a terminal open retains its process and a bounded screen buffer. ## Table of Contents diff --git a/packages/api/terminal-controller/README.zh.md b/packages/api/terminal-controller/README.zh.md index 92374aa4b8..ff1307f1fc 100644 --- a/packages/api/terminal-controller/README.zh.md +++ b/packages/api/terminal-controller/README.zh.md @@ -9,7 +9,7 @@ kind: "package-reference" ## 概述 -从 Web 侧栏在 Session 当前工作目录打开执行环境的默认 shell。重新连接已有进程,并关闭 provider 管理的完整进程范围。终端输出不进入 Agent 对话记录。保留终端会占用进程和有界屏幕缓存。 +从 Web 侧栏在 Session 工作区根打开执行环境的默认 shell。重新连接已有进程,并关闭 provider 管理的完整进程范围。终端输出不进入 Agent 对话记录。保留终端会占用进程和有界屏幕缓存。 ## 目录 diff --git a/packages/api/terminal-controller/src/index.ts b/packages/api/terminal-controller/src/index.ts index 75f454d77d..83f1c9d0cf 100644 --- a/packages/api/terminal-controller/src/index.ts +++ b/packages/api/terminal-controller/src/index.ts @@ -110,16 +110,16 @@ export class TerminalController extends TypertRemoteService { } /** - * Read the Session's current directory and terminal limits without filesystem validation or shell lookup. + * Read the Session's workspace root and terminal limits without filesystem validation or shell lookup. * @param agent - Session owner supplied by the Gateway. * @param signal - request cancellation. - * @returns the logged current directory and terminal limits; retained terminals keep their own process directories. + * @returns the logged workspace root and terminal limits; retained terminals keep their own process directories. */ @Remote environment(agent: Agent, signal: AbortSignal): TerminalEnvironment { signal.throwIfAborted() const { workingDirectory } = this.execution(agent) - return { cwd: workingDirectory.get(agent.session), + return { cwd: workingDirectory.rootOf(agent.session), maxInputBytes: this.config.maxInputBytes, maxBufferedBytes: this.config.maxBufferedBytes, maxCols: this.config.maxCols, maxRows: this.config.maxRows, scrollback: this.config.scrollback } } @@ -312,7 +312,9 @@ export class TerminalController extends TypertRemoteService { private async spawn(agent: Agent, owner: OwnedSession, request: TerminalCreateRequest, signal: AbortSignal): Promise { const { subprocess, workingDirectory } = this.execution(agent) - const cwd = await workingDirectory.ensure(agent, signal) + // A user terminal starts in the checkout the Session works in, not at the model's cursor. + await workingDirectory.ensure(agent, signal) + const cwd = workingDirectory.rootOf(agent.session) const shell = request.shellPath === undefined ? await resolveShell(subprocess, this.config.shell, signal) : (await this.shells(agent, signal)).find(candidate => candidate.path === request.shellPath) diff --git a/packages/api/terminal-controller/src/types.ts b/packages/api/terminal-controller/src/types.ts index 7c0eba8ff2..a94b2e8a3a 100644 --- a/packages/api/terminal-controller/src/types.ts +++ b/packages/api/terminal-controller/src/types.ts @@ -30,7 +30,7 @@ export interface TerminalShell { /** Current Session directory and terminal limits; retained terminals keep their own process directories. */ export interface TerminalEnvironment { - /** Logged current directory, read without filesystem validation. */ + /** Logged workspace root a new terminal starts in, read without filesystem validation. */ readonly cwd: string readonly maxInputBytes: number /** Maximum complete encoded Client input bytes retained until acknowledgement. */ diff --git a/packages/api/terminal-controller/tests/controller.spec.ts b/packages/api/terminal-controller/tests/controller.spec.ts index dc4af520bc..2d4e457bcf 100644 --- a/packages/api/terminal-controller/tests/controller.spec.ts +++ b/packages/api/terminal-controller/tests/controller.spec.ts @@ -34,6 +34,7 @@ function fixture(overrides: Partial = {}) { const sandboxPolicy = { defaultMode: 'danger-full-access', workspaceRoot: '/workspace', resolve: vi.fn((): SandboxExecutionPolicy => ({ mode: 'danger-full-access', workspaceRoot: '/workspace' })) } const workingDirectory = { get: vi.fn<(session: Agent['session']) => string>(session => session.header.cwd ?? '/workspace'), + rootOf: vi.fn<(session: Agent['session']) => string>(session => session.header.cwd ?? '/workspace'), ensure: vi.fn<(agent: Agent, signal?: AbortSignal) => Promise>(async agent => agent.session.header.cwd ?? '/workspace'), } ctx.provide('sandboxPolicy', sandboxPolicy as never) @@ -107,15 +108,17 @@ describe('TerminalController', () => { expect(sandboxPolicy.resolve).not.toHaveBeenCalled() }) - it('uses the current directory for new user terminals while retaining earlier directories and permissions', async () => { + it('uses the workspace root for new user terminals while retaining earlier directories and permissions', async () => { const { ctx, controller, agent, subprocess, sandboxPolicy, workingDirectory } = fixture() const policy: SandboxExecutionPolicy = { mode: 'workspace-write', workspaceRoot: '/workspace', sessionId: agent.id } sandboxPolicy.resolve.mockReturnValue(policy) const confine = vi.fn(async (argv: readonly string[], _policy: SandboxExecutionPolicy) => ({ argv: [...argv] })) ctx.provide('sandbox', { confine } as never) const first = await controller.create(agent, request, signal()) - workingDirectory.get.mockReturnValue('/workspace/selected') - workingDirectory.ensure.mockResolvedValue('/workspace/selected') + // The Session relocates into a worktree: its root moves while the model's cursor may sit deeper inside it. + workingDirectory.rootOf.mockReturnValue('/workspace/selected') + workingDirectory.get.mockReturnValue('/workspace/selected/packages') + workingDirectory.ensure.mockResolvedValue('/workspace/selected/packages') expect(controller.environment(agent, signal()).cwd).toBe('/workspace/selected') expect(workingDirectory.ensure).toHaveBeenCalledOnce() @@ -131,8 +134,9 @@ describe('TerminalController', () => { expect(controller.list(agent.id).map(terminal => terminal.cwd)).toEqual(['/workspace', '/workspace/selected']) }) - it('captures the validated directory before a delayed shell lookup', async () => { + it('captures the validated root before a delayed shell lookup', async () => { const { controller, agent, subprocess, workingDirectory } = fixture() + workingDirectory.rootOf.mockReturnValue('/workspace/starting') workingDirectory.ensure.mockResolvedValue('/workspace/starting') const entered = Promise.withResolvers() const release = Promise.withResolvers() @@ -144,7 +148,7 @@ describe('TerminalController', () => { const creating = controller.create(agent, request, signal()) try { await entered.promise - workingDirectory.get.mockReturnValue('/workspace/later') + workingDirectory.rootOf.mockReturnValue('/workspace/later') workingDirectory.ensure.mockResolvedValue('/workspace/later') release.resolve(undefined) expect((await creating).cwd).toBe('/workspace/starting') @@ -158,8 +162,12 @@ describe('TerminalController', () => { it('uses recovered directory values for new creation and leaves environment reads unvalidated', async () => { const { controller, agent, subprocess, workingDirectory } = fixture() - workingDirectory.get.mockReturnValue('/missing') - workingDirectory.ensure.mockResolvedValue('/workspace/recovered') + workingDirectory.rootOf.mockReturnValue('/missing') + // Recovery commits the original project as the root again before the directory is handed back. + workingDirectory.ensure.mockImplementation(async () => { + workingDirectory.rootOf.mockReturnValue('/workspace/recovered') + return '/workspace/recovered' + }) expect(controller.environment(agent, signal()).cwd).toBe('/missing') expect(workingDirectory.ensure).not.toHaveBeenCalled() @@ -169,7 +177,7 @@ describe('TerminalController', () => { expect(workingDirectory.ensure).toHaveBeenCalledWith(agent, expect.any(AbortSignal)) expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/workspace/recovered' })) workingDirectory.ensure.mockRejectedValue(new Error('original directory is unavailable')) - expect(controller.environment(agent, signal()).cwd).toBe('/missing') + expect(controller.environment(agent, signal()).cwd).toBe('/workspace/recovered') expect(await controller.create(agent, request, signal())).toBe(created) await expect(controller.create(agent, { ...request, id: 'unavailable' as WebTerminalId }, signal())) .rejects.toThrow('original directory is unavailable') diff --git a/packages/api/workspace-files/README.i18n.yaml b/packages/api/workspace-files/README.i18n.yaml index 0dbb9b3f71..9a6a12b99b 100644 --- a/packages/api/workspace-files/README.i18n.yaml +++ b/packages/api/workspace-files/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-api-workspace-files/use-this-package: - en: 874054ed5e950973 - zh: e8b55d62939c4c2f + en: 0dcc561a32c95842 + zh: af6355823a56bbf0 /deepseek-ai-dsh-api-workspace-files/use-this-package/addressing-and-paths: en: b9565cfa7a1da451 zh: fc4078a58322fc7f @@ -45,8 +45,8 @@ en: 42b15ac6321706aa zh: ce1d25bffb6948cd /deepseek-ai-dsh-api-workspace-files/understand-the-implementation/design-concept: - en: c3a8852c33dcc0e9 - zh: d24fd47da7faaa29 + en: 97a9235f16708751 + zh: 43551f0115b408d1 /deepseek-ai-dsh-api-workspace-files/understand-the-implementation/source-map: en: 596a75f43bfafda3 zh: 3cb267a0946cd75e diff --git a/packages/api/workspace-files/README.md b/packages/api/workspace-files/README.md index 9ceb0105fa..16ba112760 100644 --- a/packages/api/workspace-files/README.md +++ b/packages/api/workspace-files/README.md @@ -25,7 +25,7 @@ Use this package to preview files readable through a Session's filesystem from t ## Use this package -Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session header or uses persistence `stat` for a cold Session; it does not activate an Agent, read the event body, or borrow a parent Session's root. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. +Mount the package beside `dsh-fs`, `dsh-sandbox-policy`, the Session store, and the Typert Gateway; the bundle does so right after the Session Controller. Every method takes the Session identity on the wire, so a Client calls `remote.workspaceFiles.read(sessionId, path, range, signal)`, `stat(sessionId, path, signal)`, `readBytes(sessionId, path, options, signal)`, `list(sessionId, path, signal)`, or `changes(sessionId, path, signal)` and never names a root itself. The Host reads a live Session's workspace root from the working-directory service, or a cold Session's recorded root from the projection cache beside its persisted header, falling back to the header directory; it does not activate an Agent, read the event body, or borrow a parent Session's root. `resolveWorkspaceFileScope(ctx, sessionId, signal)` exports that resolution for other Host services that open the same `session//` addresses. Session persistence is optional for live reads, but without it a cold Session cannot resolve and the Gateway returns `gateway/lookup-not-found`. | Method | Returns | Purpose | |---|---|---| @@ -92,7 +92,7 @@ One supervised `changes` stream serves each Session and requested path; consumer ### Design concept -Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session header or the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports. +Reads through `ctx.fs` use the backend's read authority; the sandboxing backend fences writes and edits, not reads. A Typert lookup derives `WorkspaceFileScope` from a live Session's workspace root or a stored Session's cached root beside the persistence service's header-only `stat`, so cold subagent Sessions need neither Agent activation nor event-body reads. The service adds regular-file checks and bounded transfer, while workspace containment belongs only to directory listing and directory watching. A page is cut from `streamText`, which decodes and rejects non-UTF-8 chunk by chunk: the cutter counts lines before the window without keeping them, admits each in-window segment against the byte cap before buffering it, and returns at the first character past the window. One `stat` before the stream names the version and size the page reports. Complete-file reads delegate size enforcement to `fs.readBytes` and return raw bytes through the binary Remote. diff --git a/packages/api/workspace-files/README.zh.md b/packages/api/workspace-files/README.zh.md index e1f0e0000d..c00d30a60d 100644 --- a/packages/api/workspace-files/README.zh.md +++ b/packages/api/workspace-files/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 读取 live Session header,cold Session 则使用持久层 `stat`;它不会激活 Agent、读取事件正文或借用父 Session 的根。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 +把本包与 `dsh-fs`、`dsh-sandbox-policy`、Session store 和 Typert Gateway 一起挂载;bundle 把它紧随 Session Controller 之后挂载。每个方法都在线路上携带 Session 身份,Client 调用 `remote.workspaceFiles.read(sessionId, path, range, signal)`、`stat(sessionId, path, signal)`、`readBytes(sessionId, path, options, signal)`、`list(sessionId, path, signal)` 或 `changes(sessionId, path, signal)`,从不自己指定根。Host 从工作目录服务读取 live Session 的工作区根,cold Session 则读取持久化 header 旁投影缓存中记录的根,再回退到 header 目录;它不会激活 Agent、读取事件正文或借用父 Session 的根。`resolveWorkspaceFileScope(ctx, sessionId, signal)` 把这一解析导出给打开同一种 `session//` 地址的其他 Host 服务。live 读取不要求挂载 Session persistence;未挂载时 cold Session 无法解析,Gateway 返回 `gateway/lookup-not-found`。 | 方法 | 返回 | 用途 | |---|---|---| @@ -92,7 +92,7 @@ kind: "package-reference" ### 设计概念 -经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session header 或持久层的 header-only `stat` 导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。 +经 `ctx.fs` 的读取使用后端的读取权限;沙箱后端限制写与编辑,而不限制读取。Typert lookup 从 live Session 的工作区根,或 stored Session 在持久层 header-only `stat` 旁缓存的根导出 `WorkspaceFileScope`,所以 cold subagent Session 不需要激活 Agent 或读取事件正文。本服务增加普通文件检查与有界传输,工作区包含要求只属于目录列举与目录监听。页从 `streamText` 切出,后者逐块解码并拒绝非 UTF-8:切页器对窗口之前的行只计数不保留,对窗口内的每个片段先按字节上限验收再缓冲,并在窗口之后的第一个字符处返回。流之前的一次 `stat` 给出页所报告的版本与大小。 完整文件读取将大小上限检查交给 `fs.readBytes`,并通过二进制 Remote 返回原始字节。 diff --git a/packages/api/workspace-files/package.json b/packages/api/workspace-files/package.json index 5e0761a952..5f807c3f19 100644 --- a/packages/api/workspace-files/package.json +++ b/packages/api/workspace-files/package.json @@ -59,7 +59,9 @@ "zod": "4.4.3" }, "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~" + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -73,7 +75,9 @@ "@deepseek-ai/dsh-sandbox-policy": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-session-persistence": "workspace:*", - "@deepseek-ai/dsh-util-workspace-path": "workspace:*" + "@deepseek-ai/dsh-session-projection-cache": "workspace:*", + "@deepseek-ai/dsh-util-workspace-path": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "files": [ "locale/*.json", diff --git a/packages/api/workspace-files/src/index.ts b/packages/api/workspace-files/src/index.ts index d6ecbc68c1..427f5f8295 100644 --- a/packages/api/workspace-files/src/index.ts +++ b/packages/api/workspace-files/src/index.ts @@ -4,9 +4,9 @@ * `workspaceFiles`. * * File reads follow the composed filesystem's read access, including paths - * outside the workspace. The selected Session header supplies the base for - * relative paths, with the sandbox policy root as its no-cwd fallback, not a - * read-containment restriction. Directory listings and change observations + * outside the workspace. The selected Session's workspace root supplies the + * base for relative paths, with the header directory and then the sandbox + * policy root as fallbacks, not a read-containment restriction. Directory listings and change observations * remain workspace-scoped. File-kind checks and configured read caps apply to * every preview; this service exposes no mutations. * @@ -27,8 +27,10 @@ import type { FsDirEntry, FsInfo, FsPathInfo, FsTarget } from '@deepseek-ai/dsh- import type {} from '@deepseek-ai/dsh-sandbox-policy' import type {} from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-session-persistence' +import type {} from '@deepseek-ai/dsh-session-projection-cache' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { Remote, RemoteError, TypertRemoteService, type TypertLookup } from '@deepseek-ai/dsh-typert-protocol' +import type {} from '@deepseek-ai/dsh-working-directory' import { WorkspaceChangeFeed } from './changes.ts' import type { WorkspaceByteRange, @@ -55,10 +57,39 @@ declare module '@deepseek-ai/cordis' { export interface WorkspaceFileScope { /** Session identity received on the wire. */ readonly sessionId: SessionId - /** Session workspace root, or the deployment fallback when its header has no cwd. */ + /** + * Session workspace root: the checkout the Session works in, read from the + * working-directory service for a live Session and from the projection cache + * for a stored one; its header directory when neither records a root, and + * the deployment fallback when the header has no directory. + */ readonly workspaceRoot: string } +/** + * Resolve the workspace root a Session's file views and directory listings + * use, without loading its event body or activating an Agent. + * @param ctx - Host context carrying the Session store and the sandbox policy fallback, and optionally persistence, + * the projection cache, and the working-directory service. + * @param sessionId - Session identity received on the wire. + * @param signal - cancellation for the persistence read of a stored Session. + * @returns the scope, or undefined when no live or stored Session has that identity. + */ +export async function resolveWorkspaceFileScope( + ctx: Context, sessionId: SessionId, signal?: AbortSignal, +): Promise { + const live = ctx.get('sessions')?.get(sessionId) + if (live !== undefined) { + const directories = ctx.get('workingDirectory') + const root = directories !== undefined && directories.anchorsOf(live).length > 0 ? directories.rootOf(live) : live.header.cwd + return { sessionId, workspaceRoot: root ?? ctx.sandboxPolicy.workspaceRoot } + } + const stored = await ctx.get('sessionPersistence')?.stat(sessionId, signal === undefined ? undefined : { signal }) + if (stored === undefined) return undefined + const cached = ctx.get('sessionProjectionCache')?.cachedSnapshot(stored.header, ['workspaceRoot'])?.values.workspaceRoot + return { sessionId, workspaceRoot: cached ?? stored.header.cwd ?? ctx.sandboxPolicy.workspaceRoot } +} + declare module '@deepseek-ai/dsh-typert-protocol' { interface TypertLookupMap { /** Resolve a Session id to its workspace root without loading its event body or activating an Agent. */ @@ -206,18 +237,7 @@ export class WorkspaceFiles extends TypertRemoteService { resource: 'session', hostTypeSymbol: '@deepseek-ai/dsh-api-workspace-files#WorkspaceFileScope', wireTypeSymbol: '@deepseek-ai/dsh-session/types#SessionId', - resolve: async (sessionId) => { - const live = scope.sessions.get(sessionId)?.header - const stored = live === undefined - ? await scope.get('sessionPersistence')?.stat(sessionId) - : undefined - const header = live ?? stored?.header - if (header === undefined) return undefined - return { - sessionId, - workspaceRoot: header.cwd ?? scope.sandboxPolicy.workspaceRoot, - } - }, + resolve: sessionId => resolveWorkspaceFileScope(scope, sessionId), }) }) } diff --git a/packages/api/workspace-files/tests/scope.spec.ts b/packages/api/workspace-files/tests/scope.spec.ts index d954063bfd..96adb39120 100644 --- a/packages/api/workspace-files/tests/scope.spec.ts +++ b/packages/api/workspace-files/tests/scope.spec.ts @@ -3,7 +3,7 @@ import { Context } from '@deepseek-ai/cordis' import SessionStore, { SESSION_FORMAT_VERSION, SessionId, type SessionHeader } from '@deepseek-ai/dsh-session' import TypertRegistry from '@deepseek-ai/dsh-typert-registry' import { describe, expect, it, vi } from 'vitest' -import WorkspaceFiles from '../src/index.ts' +import WorkspaceFiles, { resolveWorkspaceFileScope } from '../src/index.ts' const CAPS = { maxBytes: 1024, @@ -24,10 +24,54 @@ function header(id: SessionId, cwd?: string): SessionHeader { } describe('Workspace Files Session scope lookup', () => { + it('prefers the recorded workspace root of a live or stored Session over its header directory', async () => { + const liveId = SessionId('live-relocated') + const coldId = SessionId('cold-relocated') + const plainId = SessionId('cold-plain') + const liveRoot = resolve('live-workspace') + const liveWorktree = resolve('live-workspace', '.agents', 'worktrees', 'topic') + const coldRoot = resolve('cold-workspace') + const coldWorktree = resolve('elsewhere', 'cold-topic') + const stat = vi.fn(async (id: SessionId) => { + if (id === coldId) return { header: header(coldId, coldRoot) } + if (id === plainId) return { header: header(plainId, coldRoot) } + return undefined + }) + const cachedSnapshot = vi.fn((meta: SessionHeader) => + meta.id === coldId ? { asOfSeq: 4, values: { workspaceRoot: coldWorktree } } : undefined) + const ctx = new Context() + ctx.provide('fs', {} as never) + ctx.provide('sandboxPolicy', { workspaceRoot: resolve('fallback-workspace') } as never) + ctx.provide('sessionPersistence', { stat } as never) + ctx.provide('sessionProjectionCache', { cachedSnapshot } as never) + ctx.provide('workingDirectory', { + anchorsOf: () => [liveRoot, liveWorktree], + rootOf: () => liveWorktree, + } as never) + const sessions = await ctx.plugin(SessionStore) + const typert = await ctx.plugin(TypertRegistry) + const workspaceFiles = await ctx.plugin(WorkspaceFiles, CAPS) + try { + ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } }) + await expect(resolveWorkspaceFileScope(ctx, liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveWorktree }) + await expect(resolveWorkspaceFileScope(ctx, coldId)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldWorktree }) + await expect(resolveWorkspaceFileScope(ctx, plainId)).resolves.toEqual({ sessionId: plainId, workspaceRoot: coldRoot }) + expect(cachedSnapshot).toHaveBeenCalledWith(expect.objectContaining({ id: coldId }), ['workspaceRoot']) + const lookup = ctx.typert.lookups.get('workspaceFileScope') + if (lookup === undefined) throw new Error('workspaceFileScope lookup did not register') + await expect(lookup.resolve(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveWorktree }) + } finally { + await workspaceFiles.dispose() + await sessions.dispose() + await typert.dispose() + } + }) + it('uses live or stored headers without an Agent and leaves with its plugin', async () => { const liveId = SessionId('live-subagent') const coldId = SessionId('cold-subagent') const fallbackId = SessionId('cold-without-cwd') + const liveFallbackId = SessionId('live-without-cwd') const missingId = SessionId('missing') const liveRoot = resolve('live-workspace') const coldRoot = resolve('cold-workspace') @@ -47,6 +91,7 @@ describe('Workspace Files Session scope lookup', () => { try { ctx.sessions.create(liveId, { meta: { cwd: liveRoot, origin: 'subagent' } }) + ctx.sessions.create(liveFallbackId, { meta: { origin: 'subagent' } }) expect(ctx.get('agents')).toBeUndefined() const lookup = ctx.typert.lookups.get('workspaceFileScope') expect(lookup).toMatchObject({ @@ -60,11 +105,15 @@ describe('Workspace Files Session scope lookup', () => { if (lookup === undefined) throw new Error('workspaceFileScope lookup did not register') await expect(lookup.resolve(liveId)).resolves.toEqual({ sessionId: liveId, workspaceRoot: liveRoot }) + await expect(lookup.resolve(liveFallbackId)).resolves.toEqual({ sessionId: liveFallbackId, workspaceRoot: fallbackRoot }) expect(stat).not.toHaveBeenCalled() + const signal = new AbortController().signal + await expect(resolveWorkspaceFileScope(ctx, coldId, signal)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldRoot }) + expect(stat).toHaveBeenLastCalledWith(coldId, { signal }) await expect(lookup.resolve(coldId)).resolves.toEqual({ sessionId: coldId, workspaceRoot: coldRoot }) await expect(lookup.resolve(fallbackId)).resolves.toEqual({ sessionId: fallbackId, workspaceRoot: fallbackRoot }) await expect(lookup.resolve(missingId)).resolves.toBeUndefined() - expect(stat.mock.calls.map(([id]) => id)).toEqual([coldId, fallbackId, missingId]) + expect(stat.mock.calls.map(([id]) => id)).toEqual([coldId, coldId, fallbackId, missingId]) await workspaceFiles.dispose() expect(ctx.typert.lookups.get('workspaceFileScope')).toBeUndefined() diff --git a/packages/api/workspace-files/tsconfig.host.json b/packages/api/workspace-files/tsconfig.host.json index 3bf11f5177..366c50f186 100644 --- a/packages/api/workspace-files/tsconfig.host.json +++ b/packages/api/workspace-files/tsconfig.host.json @@ -34,6 +34,12 @@ }, { "path": "../../util/deque" + }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/working-directory" } ] } diff --git a/packages/api/workspace-files/tsconfig.json b/packages/api/workspace-files/tsconfig.json index 2eca820546..7241e8a434 100644 --- a/packages/api/workspace-files/tsconfig.json +++ b/packages/api/workspace-files/tsconfig.json @@ -6,6 +6,12 @@ }, { "path": "./tsconfig.client.json" + }, + { + "path": "../../session/session-projection-cache" + }, + { + "path": "../../session/working-directory" } ] } diff --git a/packages/client/tsdown.client.ts b/packages/client/tsdown.client.ts index 5eaf0b2a35..8b6f86b342 100644 --- a/packages/client/tsdown.client.ts +++ b/packages/client/tsdown.client.ts @@ -82,7 +82,7 @@ function styleInjectionModule( * Everything else under @deepseek-ai/* is either a module-table entry * (external) or a leak the purity gate rejects. */ -export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-spill-policy\/notice$)/ +export const INLINE_SAFE = /^(?:@deepseek-ai\/dsh-(?:file-reference|session|llm|tools|brand|official-bundles|deque|output-retention|typert-protocol|util-crypto|util-time|util-values|util-workspace-path)(?:\/|$)|@deepseek-ai\/dsh-util-file-drag$|@deepseek-ai\/dsh-token-meter\/client$|@deepseek-ai\/dsh-commands\/builtin$|@deepseek-ai\/dsh-native-command\/types$|@deepseek-ai\/dsh-host-open-in-app\/shared$|@deepseek-ai\/dsh-plugin-manager\/registry$|@deepseek-ai\/dsh-agent-preset-registry\/display$|@deepseek-ai\/dsh-api-workspace-controller\/default-workspace$|@deepseek-ai\/dsh-api-session-controller\/client\/directories$|@deepseek-ai\/dsh-spill-policy\/notice$)/ /** * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index d3a6df8b96..93460cef8e 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -6,6 +6,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type {} from '@deepseek-ai/dsh-api-remotes/client' import type { SessionBinding } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectories } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { GroupKey } from '@deepseek-ai/dsh-client-ui-conversation/client' import { createSnapshotStore, type ObservableSnapshot } from '@deepseek-ai/dsh-client-store' import type { SessionId } from '@deepseek-ai/dsh-session/types' @@ -270,9 +271,8 @@ export function apply(ctx: Context): void { // its top or at line 400, so the same tab is revealed and told where // to land. openFile: async (path, options) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - const url = fileAddressFor(sessionId, cwd, resolveWorkspacePath(current ?? undefined, path)) + const directories = sessionDirectories(ctx.sessions, sessionId) + const url = fileAddressFor(sessionId, directories.root, resolveWorkspacePath(directories.cwd, path)) if (options?.line === undefined) ctx.sidebarRight.openResource(url) else ctx.sidebarRight.openResource(url, { params: { line: options.line } }) await Promise.resolve() diff --git a/packages/client/ui-chat/src/client/file-path.ts b/packages/client/ui-chat/src/client/file-path.ts index 9c23fdc21d..60821b158e 100644 --- a/packages/client/ui-chat/src/client/file-path.ts +++ b/packages/client/ui-chat/src/client/file-path.ts @@ -2,7 +2,7 @@ import type { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' -import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectories } from '@deepseek-ai/dsh-api-session-controller/client/directories' /** * Bind path resolution to the originating Session without capturing its current directory. @@ -11,9 +11,5 @@ import type {} from '@deepseek-ai/dsh-api-session-controller/client' * @returns Resolver using the live working directory, falling back to the workspace root. */ export function sessionFilePath(ctx: Context, sessionId: SessionId): (path: string) => string { - return (path) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - return resolveWorkspacePath(current ?? cwd, path) - } + return path => resolveWorkspacePath(sessionDirectories(ctx.sessions, sessionId).cwd, path) } diff --git a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx index e4500c4a52..ccc18f207e 100644 --- a/packages/client/ui-deliverables/src/client/ChangedFiles.tsx +++ b/packages/client/ui-deliverables/src/client/ChangedFiles.tsx @@ -34,10 +34,10 @@ function Counts({ added, deleted, t }: { added: number; deleted: number } & Prop * @param props - the recorded summary, the review opener, and localized copy. * @returns the card. */ -export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { +export function ChangedFiles({ changes, workspaceRoot, openReview, t, sessionId, useChangesDiff, loadChangesDiff }: { /** The served summary with the sequence of the event that announced it. */ changes: Pick & { seq: number } - cwd: string | undefined + workspaceRoot: string | undefined /** Open the turn's review on the file at an original summary index. */ openReview: (index: number) => void } & PropsLocale & PreviewProps) { @@ -70,16 +70,17 @@ export function ChangedFiles({ changes, cwd, openReview, t, sessionId, useChange {singleFile === undefined ? header : <> } /> - + } {singleFile === undefined &&
    {rows.map((file, index) => (
  • } + display={resolveWorkspacePath(workspaceRoot, file.path)} useChangesDiff={useChangesDiff} + loadChangesDiff={loadChangesDiff} t={t} />} anchor={} /> - +
  • ))}
} diff --git a/packages/client/ui-deliverables/src/client/Deliverables.tsx b/packages/client/ui-deliverables/src/client/Deliverables.tsx index 89cfa24afa..5fc5553d6f 100644 --- a/packages/client/ui-deliverables/src/client/Deliverables.tsx +++ b/packages/client/ui-deliverables/src/client/Deliverables.tsx @@ -1,4 +1,5 @@ /** The changed-files card, shown only while the Host serves the turn's summary, and explicitly declared files for a closing turn. */ +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useEffect, useState } from 'react' import type { TurnTailOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import { Button, IconChevronDownOutlineRegular, IconChevronUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' @@ -74,7 +75,7 @@ export function Deliverables({ const { getTriggerProps } = useContextMenu() const [expanded, setExpanded] = useState(false) const showCodeDiff = useShowCodeDiff(value => value) - const cwd = useSessions(state => state.byId[sessionId]?.cwd) + const workspaceRoot = useSessions(state => selectSessionRoot(state, sessionId)) const states = usePresentedOpen(value => value) const host = usePresentedHost(value => value) const announced = showCodeDiff ? matched.changes : null @@ -93,7 +94,7 @@ export function Deliverables({ if (host === null) void reloadPresentedHost() }, [host, reloadPresentedHost]) return <> - {changes !== null && { openChangesReview({ sessionId, seq: changes.seq, turn: changes.turn }, index) }} />} {matched.presented.length > 0 &&
} {host !== null && host !== 'error' && !host.available && {t('presented.unavailable')}}
- {presented.map(file => { openFile(file.path) }} diff --git a/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx b/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx index 6e71d25d15..67a79040c2 100644 --- a/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx +++ b/packages/client/ui-deliverables/src/client/PresentedFileCard.tsx @@ -20,9 +20,9 @@ function cardDescription(description: string | undefined, fallback: string): str * @param props - durable file metadata, Sidebar preview, Host capabilities, gesture status, and localized copy. * @returns the file card and its anchored action menu. */ -export function PresentedFileCard({ file, cwd, phase, host, onPreview, contextMenuProps, actions, t }: { +export function PresentedFileCard({ file, workspaceRoot, phase, host, onPreview, contextMenuProps, actions, t }: { file: PresentedPath - cwd: string | undefined + workspaceRoot: string | undefined phase: PresentedOpenPhase | undefined host: PresentedHost | null onPreview: () => void @@ -37,7 +37,7 @@ export function PresentedFileCard({ file, cwd, phase, host, onPreview, contextMe : t(reveal === 'directory' && phase === 'revealing' ? 'presented.directoryOpening' : reveal === 'directory' && phase === 'revealError' ? 'presented.directoryError' : `presented.${phase}`) return
- + onClick={() => { tab.actions.openResource(fileAddressFor(sessionId, workspaceRoot, file.path)) }}> + } {file !== undefined && renderSlot('deliverables.review.file.actions', { actionUrl: changedFileUrl(sessionId, seq, index), available: native, diff --git a/packages/client/ui-deliverables/src/present-open.ts b/packages/client/ui-deliverables/src/present-open.ts index 6023625644..0b783032eb 100644 --- a/packages/client/ui-deliverables/src/present-open.ts +++ b/packages/client/ui-deliverables/src/present-open.ts @@ -1,7 +1,7 @@ /** Serve change summaries and comparisons, and open declared or changed workspace files verified by the viewed Session's filesystem. */ import type { Context } from '@deepseek-ai/cordis' import type {} from '@deepseek-ai/dsh-api-session-controller' -import type {} from '@deepseek-ai/dsh-api-workspace-files' +import { resolveWorkspaceFileScope } from '@deepseek-ai/dsh-api-workspace-files' import type {} from '@deepseek-ai/dsh-fs' import type {} from '@deepseek-ai/dsh-sandbox-policy' import { remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol' @@ -112,14 +112,13 @@ async function handlePresentOpen(ctx: Context, request: Request): Promise select(useSyncExternalStore(subscribe, getSnapshot))} />) return { view, diffs, loadChangesDiff, openReview, row: screen.getByRole('button', { name: 'View changes to main.ts' }) } diff --git a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts index 0043997b3b..01941a9e5a 100644 --- a/packages/client/ui-deliverables/tests/changes-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/changes-open.host.spec.ts @@ -37,7 +37,7 @@ async function fixture() { const outside = join(root, 'outside.txt') await writeFile(outside, 'outside') const data: WorkspaceChangesSummary = { - turn: 1, cwd, total: 3, added: 3, deleted: 0, snapshot: { before: 'a'.repeat(40), after: 'b'.repeat(40) }, + turn: 1, root: cwd, total: 3, added: 3, deleted: 0, snapshot: { before: 'a'.repeat(40), after: 'b'.repeat(40) }, files: [changed('src/lib/a.ts'), changed('src/b.ts'), changed(outside, '~/outside.txt')], } const ctx = new Context() diff --git a/packages/client/ui-deliverables/tests/present-open.host.spec.ts b/packages/client/ui-deliverables/tests/present-open.host.spec.ts index 6d6057d204..fa46b0b0c9 100644 --- a/packages/client/ui-deliverables/tests/present-open.host.spec.ts +++ b/packages/client/ui-deliverables/tests/present-open.host.spec.ts @@ -45,6 +45,9 @@ async function fixture() { return { session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'present-call', files: [file] } } as SessionEvent } }) ctx.provide('sessionQuery', { readEvent } as never) + // Every viewed Session is live with that header, so the workspace scope reads its original project without an Agent. + const live = vi.fn((id: SessionId) => ({ id, header: session })) + ctx.provide('sessions', { get: live } as never) const opener = vi.fn(async (_request: { path: string; action?: 'reveal' }, _signal: AbortSignal) => ({ opened: true as const })) const applications = vi.fn(async () => [{ id: 'player', name: 'Player', default: true, icon: null }]) ctx.provide('sessionController', { workspacePathApplications: applications, resolveAgent, openWorkspacePath: opener, workspaceDesktop: () => ({ name: 'desktop', available: true, fileManager: 'finder' }) } as never) @@ -56,7 +59,8 @@ async function fixture() { `http://localhost${PRESENT_OPEN_PATH}${query}`, { method: 'POST', signal: signal ?? null }, ), connection.browserPeer) return { - browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, resolveAgent, + browserPeer: connection.browserPeer, applications, root, cwd, ctx, fiber, file, session, readEvent, open, opener, handler, + resolveAgent, live, } } @@ -230,6 +234,14 @@ it('opens a viewed child Session without activating an Agent', async () => { expect(resolveAgent).not.toHaveBeenCalled() }) +it('refuses a presented file whose Session is neither live nor stored once its event was read', async () => { + const { session, readEvent, live, open, opener } = await fixture() + readEvent.mockResolvedValueOnce({ session, target: { type: 'deliverables/presented', data: { turn: 1, callId: 'gone', files: [{ path: '日记模板.docx' }] } } as SessionEvent }) + live.mockReturnValueOnce(undefined as never) + expect((await open('?sessionId=gone&seq=7&index=0')).status).toBe(404) + expect(opener).not.toHaveBeenCalled() +}) + it('uses the deployment workspace root when the viewed Session has no cwd', async () => { const { session, open, cwd, file, opener } = await fixture() delete session.cwd diff --git a/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx b/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx index 0b009d5915..d182e1c1ab 100644 --- a/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx +++ b/packages/client/ui-deliverables/tests/presented-file-card.client.spec.tsx @@ -10,7 +10,7 @@ afterEach(cleanup) const props = () => { const onMenu = vi.fn() return { - cwd: undefined, + workspaceRoot: undefined, file: { path: 'out/report.pdf', description: 'Final report', seq: 4, index: 1 }, host: { name: 'remote-desktop', available: true, fileManager: 'finder' as const }, phase: undefined, @@ -34,10 +34,10 @@ it('localizes reveal failures and restores the description when progress clears' it('shows the basename while retaining the full location for hover and actions', () => { const p = props() const path = '/work/reports/result.pdf' - const view = render() + const view = render() expect(view.getByTitle(path)).toBeTruthy() expect(view.getByText('result.pdf')).toBeTruthy() - view.rerender() + view.rerender() expect(view.getByTitle('/work/out/report.pdf')).toBeTruthy() expect(view.getByText('report.pdf')).toBeTruthy() }) diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 2f6fb14295..f59bd2d3cc 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -9,6 +9,7 @@ import type {} from '@deepseek-ai/dsh-api-workspace-files/remote' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' import type { OpenInAppController } from './controller.ts' +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' @@ -62,7 +63,7 @@ export function registerContextMenus( id: 'open-in-app.directory', target: 'directory', order: 100, resolve: async ({ sessionId, path }, signal) => { await paths.load() - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionRoot(ctx.sessions.list.getSnapshot(), sessionId) const absolutePath = resolveWorkspacePath(cwd, path) signal.throwIfAborted() return [ @@ -88,7 +89,7 @@ export function registerContextMenus( const application = apps?.find(app => app.default) // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionRoot(ctx.sessions.list.getSnapshot(), sessionId) ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { destination, ...(line === undefined ? {} : { params: { line } }), }) @@ -104,7 +105,7 @@ export function registerContextMenus( ...absolutePath === undefined || application === undefined ? {} : { run: () => open(absolutePath, 'open', application.id) } }, { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const cwd = selectSessionRoot(ctx.sessions.list.getSnapshot(), sessionId) await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) ctx.contextMenus.notify(t('menu.copied'), true) } }, diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index 49e5fe25e4..018a8c9446 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -20,6 +20,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-documentpreview/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-files/client' import type {} from '@deepseek-ai/dsh-api-gateway/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type {} from '@deepseek-ai/dsh-api-session-controller/remote' import { OPEN_IN_APP_ICON_PREFIX_ROUTE } from '@deepseek-ai/dsh-host-open-in-app/shared' import { OpenInAppController } from './controller.ts' @@ -77,10 +78,11 @@ export function apply(ctx: ClientContext): void { }, OpenInAppToast)) const target = () => { if (ctx.layout.panelInfo.getSnapshot().activePanelId !== null) return undefined - const session = Object.values(ctx.sessions.list.getSnapshot().byId) - .find(row => (row.retainedBy.mainView ?? 0) > 0) + const list = ctx.sessions.list.getSnapshot() + const session = Object.values(list.byId).find(row => (row.retainedBy.mainView ?? 0) > 0) + const root = session === undefined ? undefined : selectSessionRoot(list, session.id) const appId = controller.currentApp() - return session?.cwd && appId !== undefined ? { appId, path: session.cwd } : undefined + return root && appId !== undefined ? { appId, path: root } : undefined } ctx.effect(() => ctx.shortcuts.register({ id: 'workspace.openLocal' as ShortcutCommandId, label: () => t('open.tooltip'), aliases: ['open workspace locally', 'open in app'], @@ -117,8 +119,8 @@ export function apply(ctx: ClientContext): void { props: PropsRuntime<'conversation.session.header.utilities'> & Omit, ) { const { sessionId, useSessions } = props - const cwd = useSessions(state => state.byId[sessionId]?.cwd) - return cwd ? createElement(OpenInAppAction, { ...props, absolutePath: cwd }) : null + const root = useSessions(state => selectSessionRoot(state, sessionId)) + return root ? createElement(OpenInAppAction, { ...props, absolutePath: root }) : null } ctx.slots.inject('conversation.session.header.utilities', () => ctx.slots.register({ name: 'conversation.session.header.utilities', diff --git a/packages/client/ui-open-in-app/src/client/session-reveal.tsx b/packages/client/ui-open-in-app/src/client/session-reveal.tsx index 0dcf0c3a86..26668b9d01 100644 --- a/packages/client/ui-open-in-app/src/client/session-reveal.tsx +++ b/packages/client/ui-open-in-app/src/client/session-reveal.tsx @@ -1,5 +1,6 @@ /** Native directory reveal contributed to the captured Session's structured menu. */ import type { Context } from '@deepseek-ai/cordis' +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { OpenInAppController } from './controller.ts' import type { OpenInAppToastSource } from './open-toast.tsx' @@ -21,7 +22,7 @@ export function registerSessionReveal( id: 'open-in-app.reveal', target: 'session', order: 500, observe: () => [controller.apps, ctx.sessions.list, ctx.locale], resolve: ({ sessionId }) => { - const directory = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + const directory = selectSessionRoot(ctx.sessions.list.getSnapshot(), sessionId) const applications = controller.apps.getSnapshot() const manager = applications?.find(id => ['finder', 'explorer', 'filemanager'].includes(id)) return [{ diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 10407f9f54..5b8a3bae30 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -41,7 +41,7 @@ async function boot() { .mockResolvedValue({ status: 'saved', path: '/downloads/file.svg' }) const copyImage = vi.fn<(source: FileActionSource) => Promise>().mockResolvedValue() const fileActions = { save, copyImage, canSaveAs: true } - const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } } }) + const sessions = createSnapshotStore({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) const sidebar = { openResourceIn: vi.fn(), openTabIn: vi.fn() } const browserTab = vi.fn(() => ({})) const directoryFetch = vi.fn(async () => new Response(JSON.stringify({ apps: ['vscode', 'finder'] }))) @@ -242,10 +242,10 @@ it('offers only folder reveal and path copy, retaining the captured directory', const menu = await h.resolve(target) expect(menu.source.getSnapshot().map(item => item.id)).toEqual(['open-in-app.directory/reveal', 'open-in-app.directory/copyPath']) expect(h.remote.workspaceFiles.stat).not.toHaveBeenCalled() - h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/changed' } }, projectionsBySession: {} }) menu.select('open-in-app.directory/reveal') await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenCalledWith({ path: '/workspace/src', action: 'reveal' }) }) - h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } } }) + h.sessions.set({ byId: { [sessionId]: { cwd: '/workspace' } }, projectionsBySession: {} }) await h.choose(target, 'open-in-app.directory/copyPath') expect(h.writeText).toHaveBeenLastCalledWith('/workspace/src') h.paths.desktop.set(false) diff --git a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts index 30fff9b342..f3c82de92a 100644 --- a/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menus.client.spec.ts @@ -34,7 +34,7 @@ it('offers image actions on file targets, copies absolute paths, and keeps save } } ctx.provide('remote', remote as never) ctx.provide('contextMenus', { register: registry.register.bind(registry), notify } as never) - ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } } }) } as never) + ctx.provide('sessions', { list: createSnapshotStore({ byId: { [id]: { cwd: '/workspace' } }, projectionsBySession: {} }) } as never) ctx.provide('fileActions', { save, copyImage: copy, canSaveAs: true } as never) const paths = new OpenInAppPathController(remote) const directories = new OpenInAppController() diff --git a/packages/client/ui-reference/src/client/index.ts b/packages/client/ui-reference/src/client/index.ts index ab66cffa5e..6a67b043aa 100644 --- a/packages/client/ui-reference/src/client/index.ts +++ b/packages/client/ui-reference/src/client/index.ts @@ -21,6 +21,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' import type { ISessions } from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectories } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { relativeTime } from '@deepseek-ai/dsh-client-ui-primitives' import type { UserTextNodeProps } from '@deepseek-ai/dsh-client-ui-conversation/client' import { FileReference, FolderReference, type FileReferenceInjected } from './FileReference.tsx' @@ -62,10 +63,10 @@ export function apply(ctx: ClientContext): void { yield ctx.slots.register({ name: 'conversation.user.text.node', key: 'file', priority: 100, locale: NS, inject: (sessionId: UserTextNodeProps<'file'>['sessionId']): FileReferenceInjected => ({ - resolveFilePath: path => resolveWorkspacePath(sessions.list.getSnapshot().byId[sessionId]?.cwd, path), + // A user reference is relative to the workspace root the user sees, not to the model's current directory. + resolveFilePath: path => resolveWorkspacePath(sessionDirectories(sessions, sessionId).root, path), openFile: (path) => { - const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(sessionId, cwd, path)) + ctx.sidebarRight.openResource(fileAddressFor(sessionId, sessionDirectories(sessions, sessionId).root, path)) }, }), }, FileReference) @@ -165,8 +166,7 @@ export function apply(ctx: ClientContext): void { openReference(session, { ref, appearance }) { if (appearance !== 'file') return false const path = ref.startsWith('@"') ? ref.slice(2, -1) : ref.slice(1) - const cwd = sessions.list.getSnapshot().byId[session.sessionId]?.cwd - ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, cwd, path)) + ctx.sidebarRight.openResource(fileAddressFor(session.sessionId, sessionDirectories(sessions, session.sessionId).root, path)) return true }, codec: { diff --git a/packages/client/ui-sidebar-files/README.i18n.yaml b/packages/client/ui-sidebar-files/README.i18n.yaml index d420350ecc..cb2229fd3a 100644 --- a/packages/client/ui-sidebar-files/README.i18n.yaml +++ b/packages/client/ui-sidebar-files/README.i18n.yaml @@ -21,8 +21,8 @@ en: 803d10142360264b zh: 042568a8ba293037 /deepseek-ai-dsh-client-ui-sidebar-files/the-tree: - en: c6d5d2d068bdec7b - zh: dd41bcfa3e9080ad + en: 50426845c6d77ccd + zh: 4eded68d11addbab /deepseek-ai-dsh-client-ui-sidebar-files/reusable-tree-factory: en: 0a3e9645426b4203 zh: 0478669e4157f15c @@ -33,8 +33,8 @@ en: 5a6febb45089991a zh: b17ed755fd098b83 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work: - en: dd317b62980a9269 - zh: 0be3b9924f6b6c67 + en: ca59c47fa68bc440 + zh: ebe18d06be6fd739 /deepseek-ai-dsh-client-ui-sidebar-files/known-limitations-and-deferred-work/dev-note: en: 1ec99e9fb6b4c948 zh: c4f7883934307c3c diff --git a/packages/client/ui-sidebar-files/README.md b/packages/client/ui-sidebar-files/README.md index 7443828930..34b3d6be80 100644 --- a/packages/client/ui-sidebar-files/README.md +++ b/packages/client/ui-sidebar-files/README.md @@ -55,7 +55,7 @@ The tree marks the row of the current file with `aria-current`. While the tree i ## The tree -The root is the session's working directory, read from `useSessions().byId[sessionId].cwd`. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Dotfiles are shown like any other entry. +The root is the session's workspace root, selected with `selectSessionRoot` from the list snapshot: the projected `workspaceRoot`, else the header directory. Filesystem roots such as `/` and Windows drive roots are valid tree roots. Every level is keyed by absolute path; a child's path is its parent's joined with the entry name by `/`. A level is listed when it is first expanded, through `remote.workspaceFiles.list(sessionId, absolutePath)` on the `@deepseek-ai/dsh-api-workspace-files` namespace. The rows are drawn by the [tree Factory](#tree-factory), which orders them; `workspace-tree.ts` passes every listed entry with its listing's name and type as `meta.kind`, the root key without trailing separators, and localized failure lines. The Factory reads its own copy from the files locale. Dotfiles are shown like any other entry. | Entry type | Row | |---|---| @@ -95,7 +95,7 @@ None; directory listings travel over the Remote and assemble no model request. - **Listing only.** No search, artifact filter, drag-and-drop, or rename. -- **One root.** The tree is rooted at the session's working directory; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. +- **One root.** The tree is rooted at the session's workspace root; there is no way to browse above it, and the Host refuses paths outside the workspace root anyway. ### Dev Note diff --git a/packages/client/ui-sidebar-files/README.zh.md b/packages/client/ui-sidebar-files/README.zh.md index 69e40033ca..156c28bd69 100644 --- a/packages/client/ui-sidebar-files/README.zh.md +++ b/packages/client/ui-sidebar-files/README.zh.md @@ -55,7 +55,7 @@ kind: "package-reference" ## 树 -根是会话的工作目录,读自 `useSessions().byId[sessionId].cwd`。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。dotfiles 与其他条目一样显示。 +根是会话的工作区根,用 `selectSessionRoot` 从列表快照选出:投影的 `workspaceRoot`,否则为 header 目录。`/` 和 Windows 盘根等文件系统根路径均可作为树的根。每一层以绝对路径为键;子路径是父路径以 `/` 拼上条目名。一层在首次展开时经 `@deepseek-ai/dsh-api-workspace-files` 命名空间的 `remote.workspaceFiles.list(sessionId, absolutePath)` 列出。各行由[目录树 Factory](#tree-factory) 绘制并排序;`workspace-tree.ts` 传入每个已列出的条目,名字取目录列表中的拼写,类型作为 `meta.kind`,根的键去掉末尾分隔符,并传入已本地化的失败行。Factory 自行从 files locale 读取文案。dotfiles 与其他条目一样显示。 | 条目类型 | 行 | |---|---| @@ -95,7 +95,7 @@ kind: "package-reference" - **只有列目录。**没有搜索、产物过滤、拖拽或重命名。 -- **只有一个根。**树以会话工作目录为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 +- **只有一个根。**树以会话工作区根为根;没有办法浏览到它之上,而 Host 本来也拒绝工作区根之外的路径。 ### 开发备注 diff --git a/packages/client/ui-sidebar-files/package.json b/packages/client/ui-sidebar-files/package.json index f9e978df9e..eb3d742217 100644 --- a/packages/client/ui-sidebar-files/package.json +++ b/packages/client/ui-sidebar-files/package.json @@ -50,10 +50,13 @@ "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-api-remotes": "workspace:*", + "@deepseek-ai/dsh-api-session-controller": "workspace:*", "@deepseek-ai/dsh-api-workspace-files": "workspace:*", "@deepseek-ai/dsh-client-locale": "workspace:*", + "@deepseek-ai/dsh-client-shortcuts": "workspace:*", "@deepseek-ai/dsh-client-store": "workspace:*", "@deepseek-ai/dsh-client-test-runtime": "workspace:*", + "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*", "@deepseek-ai/dsh-client-ui-dockkit": "workspace:*", "@deepseek-ai/dsh-client-ui-primitives": "workspace:*", "@deepseek-ai/dsh-client-ui-renderer": "workspace:*", @@ -64,11 +67,9 @@ "@deepseek-ai/dsh-typert-protocol": "workspace:*", "@deepseek-ai/dsh-util-workspace-path": "workspace:*", "@testing-library/react": "^16.3.3", - "react": "^18.2.0", "clsx": "^2.0.0", - "react-dom": "^18.2.0", - "@deepseek-ai/dsh-client-shortcuts": "workspace:*", - "@deepseek-ai/dsh-client-ui-context-menu": "workspace:*" + "react": "^18.2.0", + "react-dom": "^18.2.0" }, "files": [ "locale/*.json", diff --git a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx index 6ce68e82b2..4fac4ee79b 100644 --- a/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileNavigator.tsx @@ -7,6 +7,7 @@ * follows `PUSH_FROM`, `FILL_BELOW`, and `FULLSCREEN_QUERY`; the package * README describes its behavior. */ +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { CSSProperties, ReactNode } from 'react' import clsx from 'clsx' @@ -75,14 +76,14 @@ export function FileNavigator({ const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const paneId = panel.id - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const workspaceRoot = useSessions(sessions => selectSessionRoot(sessions, sessionId)) const state = useStore(store => store.byPane[paneId]) const rowWidth = useRowWidth(paneId) const canOpen = useCanOpen(check => check) const open = page || state?.open === true // Measured by the face; the viewport rule is CSS's, read again when a file opens. const mode = navigatorMode(rowWidth) - const tree = state?.tree?.root === cwd ? state?.tree : undefined + const tree = state?.tree?.root === workspaceRoot ? state?.tree : undefined const [dragging, setDragging] = useState(false) const drag = useRef<{ readonly x: number; readonly width: number } | undefined>(undefined) // Stable, so each element registers once per drawing rather than on every render. @@ -98,8 +99,8 @@ export function FileNavigator({ useEffect(() => attach(paneId, tab.id, tab.signal), [attach, paneId, tab.id, tab.signal]) // Only a navigator that can draw a tree keeps the workspace command on its tab. - useEffect(() => page || cwd === undefined ? undefined : placeBeside(tab.id), [page, cwd, placeBeside, tab.id]) - useEffect(() => cwd === undefined || !open ? undefined : hold(paneId, cwd), [cwd, open, paneId, hold]) + useEffect(() => page || workspaceRoot === undefined ? undefined : placeBeside(tab.id), [page, workspaceRoot, placeBeside, tab.id]) + useEffect(() => workspaceRoot === undefined || !open ? undefined : hold(paneId, workspaceRoot), [workspaceRoot, open, paneId, hold]) const relativePath = tree === undefined ? undefined : relativeFileOf(tab.contentId, sessionId, tree.root) const location = useMemo( @@ -132,7 +133,7 @@ export function FileNavigator({ } }, [tree, paneId, sessionId, toggle, canOpen, onOpen, getTriggerProps]) - if (cwd === undefined || !open) return null + if (workspaceRoot === undefined || !open) return null const geometry = navigatorGeometry(rowWidth, state?.width ?? DEFAULT_NAVIGATOR_WIDTH) // The page's tree always fills the page; a preview's follows its row. const shown = page ? undefined : mode @@ -146,7 +147,7 @@ export function FileNavigator({ data-files-navigator={paneId} data-files-navigator-mode={shown} data-files-state="tree" - data-files-root={cwd} + data-files-root={workspaceRoot} > {shown !== undefined && shown !== 'fill' && (
tab.actions.bindCommands({ refresh: () => { refresh(panel.id) } }), [tab.actions, panel.id, refresh], ) - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const workspaceRoot = useSessions(sessions => selectSessionRoot(sessions, sessionId)) // The setting belongs to a listed tree, so there is nothing to set before one. const autoRefresh = useStore((store) => { const tree = store.byPane[panel.id]?.tree - return tree?.root === cwd ? tree?.autoRefresh : undefined + return tree?.root === workspaceRoot ? tree?.autoRefresh : undefined }) - if (cwd === undefined) { + if (workspaceRoot === undefined) { return (

{t('noWorkspace')}

@@ -68,8 +69,8 @@ export function FilesBody(props: FilesBodyProps): ReactNode { return (
- +
{navigator}
diff --git a/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx index f30da3999d..5a0ae758df 100644 --- a/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx +++ b/packages/client/ui-sidebar-files/src/client/NavigatorToggle.tsx @@ -5,6 +5,7 @@ * the pane reads, and registers itself with the face, which hands it the * keyboard when Escape closes the navigator. */ +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { useCallback } from 'react' import type { ReactNode } from 'react' import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' @@ -42,11 +43,11 @@ export function NavigatorToggle( { useTabInfo, sessionId, useSessions, useStore, actions, toggleDrawn, t }: FactoryComponentPropsOf<'sidebar.files.navigator.toggle'>, ): ReactNode { const { panel } = useTabInfo() - const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) + const workspaceRoot = useSessions(sessions => selectSessionRoot(sessions, sessionId)) const open = useStore(store => store.byPane[panel.id]?.open) === true // Stable, so the control registers once per drawing rather than on every render. const toggleRef = useCallback((button: HTMLElement | null) => { toggleDrawn(panel.id, button) }, [toggleDrawn, panel.id]) - if (cwd === undefined) return null + if (workspaceRoot === undefined) return null const label = t(open ? 'navigator.hide' : 'navigator.show') return ( diff --git a/packages/client/ui-sidebar-files/tests/mount.client.tsx b/packages/client/ui-sidebar-files/tests/mount.client.tsx index 35a660f264..7dc6e20340 100644 --- a/packages/client/ui-sidebar-files/tests/mount.client.tsx +++ b/packages/client/ui-sidebar-files/tests/mount.client.tsx @@ -131,7 +131,7 @@ function harness(placement: Placement, controller: AbortController) { close: vi.fn(), } const sessionsAt = (cwd: string | null): SessionListState => - ({ byId: cwd === null ? {} : { [SESSION]: { cwd } } } as unknown as SessionListState) + ({ byId: cwd === null ? {} : { [SESSION]: { cwd } }, projectionsBySession: {} } as unknown as SessionListState) const useTabInfo = (): SidebarRightTabInfo => ({ sidebar: { expanded: true, fullscreen: false }, panel: { id: PANE, isFloating: placement.isFloating ?? false }, diff --git a/packages/client/ui-sidebar-files/tsconfig.json b/packages/client/ui-sidebar-files/tsconfig.json index 47b76f17ba..716d7b6823 100644 --- a/packages/client/ui-sidebar-files/tsconfig.json +++ b/packages/client/ui-sidebar-files/tsconfig.json @@ -49,6 +49,9 @@ }, { "path": "../ui-context-menu" + }, + { + "path": "../../api/session-controller/tsconfig.client.json" } ] } diff --git a/packages/client/ui-tool/src/client/tool/file-menu.ts b/packages/client/ui-tool/src/client/tool/file-menu.ts index 0b0e5377fd..25e2fe5eef 100644 --- a/packages/client/ui-tool/src/client/tool/file-menu.ts +++ b/packages/client/ui-tool/src/client/tool/file-menu.ts @@ -1,7 +1,7 @@ /** Tool-owned path resolution supplied by the existing toolview registration. */ import type { Context } from '@deepseek-ai/cordis' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import type {} from '@deepseek-ai/dsh-api-session-controller/client' +import { sessionDirectories } from '@deepseek-ai/dsh-api-session-controller/client/directories' import { resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' /** File paths are resolved when a gesture begins, not when the Slot is mounted. */ @@ -17,10 +17,6 @@ export interface ToolFileInjected { */ export function toolFileInject(ctx: Context): (sessionId: SessionId) => ToolFileInjected { return sessionId => ({ - resolveFilePath: (path) => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - const current = ctx.sessions.binding(sessionId)?.session.projections.faceOf('workingDirectory').getSnapshot() as string | null | undefined - return resolveWorkspacePath(current ?? cwd, path) - }, + resolveFilePath: path => resolveWorkspacePath(sessionDirectories(ctx.sessions, sessionId).cwd, path), }) } diff --git a/packages/client/ui-workspace/src/client/tree.ts b/packages/client/ui-workspace/src/client/tree.ts index 054c584d4b..d7e7aaeb19 100644 --- a/packages/client/ui-workspace/src/client/tree.ts +++ b/packages/client/ui-workspace/src/client/tree.ts @@ -6,6 +6,7 @@ import { type SessionListState, type SessionSearchResultItem, type SessionSummary, } from '@deepseek-ai/dsh-api-session-controller/client' +import { selectSessionRoot } from '@deepseek-ai/dsh-api-session-controller/client/directories' import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client' import type { SessionStatusSnapshot, @@ -59,7 +60,7 @@ export interface SessionNode { /** In the registry-global archive set: shown grayed in place and not openable. */ archived: boolean updatedAt: number - /** Session working directory; absent when the Host reports none or an empty path. */ + /** Workspace root the Session works in; absent when the Host reports none or an empty path. */ cwd?: string } @@ -394,6 +395,8 @@ function sessionNode( ): SessionNode { const status = statuses.get(s.id) const pendingInteraction = visiblePendingKind(status?.pendingInteraction?.kind) + // Rows show the checkout the Session works in; grouping stays with the header's original project. + const root = selectSessionRoot(list, s.id) return { id: s.id, title: sessionTitle(s), @@ -404,7 +407,7 @@ function sessionNode( pinned: !archived.has(s.id) && pinned.has(s.id), archived: archived.has(s.id), updatedAt: s.updatedAt, - ...(s.cwd === undefined || s.cwd === '' ? {} : { cwd: s.cwd }), + ...(root === undefined || root === '' ? {} : { cwd: root }), ...(pendingInteraction === undefined ? {} : { pendingInteraction }), } } diff --git a/packages/context/agent-instructions/README.i18n.yaml b/packages/context/agent-instructions/README.i18n.yaml index 4e32e2bec5..b9ba8cf726 100644 --- a/packages/context/agent-instructions/README.i18n.yaml +++ b/packages/context/agent-instructions/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-agent-instructions/use-this-package: - en: a6f5c0d19634d0e9 - zh: 74c88e1f76381a30 + en: c6e8901a72b403cc + zh: 2e88224dbb3c96b5 /deepseek-ai-dsh-agent-instructions/use-this-package/what-the-agent-gets: en: 1435be3e04948c50 zh: a3946e05a9a221dd diff --git a/packages/context/agent-instructions/README.md b/packages/context/agent-instructions/README.md index 49a66930d6..0f1dcc5861 100644 --- a/packages/context/agent-instructions/README.md +++ b/packages/context/agent-instructions/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Changing the Session's working directory reloads the applicable project instruction chain before the next request. +Entering another checkout reloads the applicable project instruction chain before the next request; a directory change inside the workspace root keeps the baseline. Mount this plugin when agents should work from the workspace's own instruction files. `dsh-base` already includes it with a 65,536-byte budget for each instruction chain, so base-backed profiles only need to replace the row when they want another `maxBytes`; providerless trees load nothing until a filesystem provider is present. diff --git a/packages/context/agent-instructions/README.zh.md b/packages/context/agent-instructions/README.zh.md index b584ccac1f..d9cff3782f 100644 --- a/packages/context/agent-instructions/README.zh.md +++ b/packages/context/agent-instructions/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -切换 Session 工作目录后,下一次请求前会重新加载适用的项目指令链。 +进入另一个检出目录后,下一次请求前会重新加载适用的项目指令链;工作区根内部的目录切换保持基线不变。 当 agent 需要依据工作区自身的指令文件工作时,挂载此插件。`dsh-base` 已包含它,并为每条指令链给予 65,536 字节预算,因此基于 base 的 profile 仅在需要其他 `maxBytes` 时替换该配置行;没有文件系统提供方的树加载不到任何内容,直到提供方出现。 diff --git a/packages/context/agent-instructions/src/index.ts b/packages/context/agent-instructions/src/index.ts index ec752e0715..5c17d98862 100644 --- a/packages/context/agent-instructions/src/index.ts +++ b/packages/context/agent-instructions/src/index.ts @@ -123,7 +123,9 @@ export function apply(ctx: Context, config: Config): void { const changes: AgentInstructionChange[] = [] let desiredBaseline = false const authorityMessages = [...claimed] - const cwd = await ctx.workingDirectory.ensure(agent, signal) + // The baseline describes the checkout the Session works in; a cd inside it keeps the same baseline. + await ctx.workingDirectory.ensure(agent, signal) + const cwd = ctx.workingDirectory.rootOf(agent.session) const projectRoot = await findProjectRoot(cwd, resolved.projectRootMarkers, fileSystem, signal) const identity = workspaceBaselineIdentity(resolved, cwd, projectRoot) if (touchedPaths.length === 0 && pending.length > 0 diff --git a/packages/context/file-reference-local/README.i18n.yaml b/packages/context/file-reference-local/README.i18n.yaml index 03975d6195..4cc8762828 100644 --- a/packages/context/file-reference-local/README.i18n.yaml +++ b/packages/context/file-reference-local/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-file-reference-local/use-this-package: - en: 1fd922f09d15163f - zh: e1d68a27a676256d + en: 39ca139cd37ecf34 + zh: d7a240da196bdff8 /deepseek-ai-dsh-file-reference-local/use-this-package/enabling-the-provider: en: 62b9ce096fa4a94e zh: 53081797c34d64eb diff --git a/packages/context/file-reference-local/README.md b/packages/context/file-reference-local/README.md index 04669af8af..d517e11f15 100644 --- a/packages/context/file-reference-local/README.md +++ b/packages/context/file-reference-local/README.md @@ -25,9 +25,9 @@ Agents and host UIs can complete `@file` mentions with ranked paths from each ag ## Use this package -Changing the Session's working directory discards the previous directory's search index; the next completion searches the new directory. +Entering another checkout discards the previous workspace root's search index; the next completion searches the new root. A directory change inside the root keeps the index. -Mount this provider when `@file` completion should discover the Harness host's own filesystem — the namespace the shipped `read` tool operates on. Each agent's workspace is indexed from its Session's current working directory. +Mount this provider when `@file` completion should discover the Harness host's own filesystem — the namespace the shipped `read` tool operates on. Each agent's workspace is indexed from its Session's workspace root. ### Enabling the provider diff --git a/packages/context/file-reference-local/README.zh.md b/packages/context/file-reference-local/README.zh.md index 319dbab044..706087a2d6 100644 --- a/packages/context/file-reference-local/README.zh.md +++ b/packages/context/file-reference-local/README.zh.md @@ -25,9 +25,9 @@ agent(智能体)及宿主 UI 可以用各 agent 本地工作区中经过排 ## 使用本包 -切换 Session 工作目录后,旧目录的搜索索引会被丢弃;下一次补全会搜索新目录。 +进入另一个检出目录后,旧工作区根的搜索索引会被丢弃;下一次补全会搜索新的根。根内部的目录切换保留索引。 -当 `@file` 补全应发现 Harness 宿主自身的文件系统——即随附 `read` 工具所操作的命名空间——时,挂载此提供方。每个 agent 的工作区从其 Session 当前工作目录开始建立索引。 +当 `@file` 补全应发现 Harness 宿主自身的文件系统——即随附 `read` 工具所操作的命名空间——时,挂载此提供方。每个 agent 的工作区从其 Session 工作区根开始建立索引。 ### 启用提供方 diff --git a/packages/context/file-reference-local/src/index.ts b/packages/context/file-reference-local/src/index.ts index a179cebafb..7845926b3a 100644 --- a/packages/context/file-reference-local/src/index.ts +++ b/packages/context/file-reference-local/src/index.ts @@ -118,7 +118,9 @@ export class LocalFileReferenceService extends FileReferenceService { query: string, signal: AbortSignal, ): Promise { - const cwd = await this.ctx.workingDirectory.ensure(agent, signal) + // Candidates are listed from the workspace root the user sees, after the current directory was validated. + await this.ctx.workingDirectory.ensure(agent, signal) + const cwd = this.ctx.workingDirectory.rootOf(agent.session) let cached = this.searches.get(agent) if (cached?.cwd !== cwd) { cached?.search.dispose() diff --git a/packages/context/file-reference-local/tests/service.spec.ts b/packages/context/file-reference-local/tests/service.spec.ts index df94c8ab64..2a4b75ddf8 100644 --- a/packages/context/file-reference-local/tests/service.spec.ts +++ b/packages/context/file-reference-local/tests/service.spec.ts @@ -69,7 +69,7 @@ describe('LocalFileReferenceService', () => { await ctx.plugin(SessionStore) await ctx.plugin(SessionProjectionRegistry) await ctx.plugin(AgentRegistry) - ctx.provide('workingDirectory', { ensure: vi.fn() }) + ctx.provide('workingDirectory', { ensure: vi.fn(), rootOf: vi.fn() }) await ctx.plugin(LocalFileReferenceService) try { expect(ctx.fileReferences).toBeInstanceOf(LocalFileReferenceService) @@ -111,7 +111,7 @@ describe('LocalFileReferenceService', () => { expect(renderPrompt(await ctx.systemPrompt.assemble())).not.toContain(FILE_REFERENCE_PROMPT) }) - it('rebuilds completion from the current directory after a Session directory change', async () => { + it('rebuilds completion from the workspace root after the Session enters another checkout', async () => { const ctx = await harness() try { const { agent } = await stubAgent(ctx) @@ -122,7 +122,7 @@ describe('LocalFileReferenceService', () => { const signal = new AbortController().signal expect(await ctx.fileReferences.list(agent, '', signal)).toEqual([{ path: 'README.md', kind: 'file' }]) const original = agent.session.header.cwd - await ctx.workingDirectory.set(agent, nextRoot, signal) + await ctx.workingDirectory.relocate(agent, nextRoot, { signal }) expect(await ctx.fileReferences.list(agent, '', signal)).toEqual([{ path: 'NEXT.md', kind: 'file' }]) expect(agent.session.header.cwd).toBe(original) } finally { diff --git a/packages/deliverables/workspace-changes/README.i18n.yaml b/packages/deliverables/workspace-changes/README.i18n.yaml index b3cbe0d1af..8446806ab4 100644 --- a/packages/deliverables/workspace-changes/README.i18n.yaml +++ b/packages/deliverables/workspace-changes/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-workspace-changes/use-this-package: - en: 0ab7680d831598aa - zh: 2594f3c8c99cef24 + en: 0d13b6aa2a5f604e + zh: 18349da659029d2c /deepseek-ai-dsh-workspace-changes/understand-the-implementation: en: 9bfc66bea548bda2 zh: 7023c42cdb44569b @@ -30,8 +30,8 @@ en: e7ba08477bf22c4e zh: f365439c69beb722 /deepseek-ai-dsh-workspace-changes/known-limitations-and-deferred-work: - en: c7091685e5065a40 - zh: 1e9b85962ea04187 + en: 04ab0c538589bfc2 + zh: 343e5af6ea36b5f4 /deepseek-ai-dsh-workspace-changes/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/deliverables/workspace-changes/README.md b/packages/deliverables/workspace-changes/README.md index 6cad61cf3d..b4020e9f3f 100644 --- a/packages/deliverables/workspace-changes/README.md +++ b/packages/deliverables/workspace-changes/README.md @@ -45,7 +45,7 @@ This plugin requires the `subprocess` and `fs` services. Every Session with a wo After a `write`, `edit`, or mutating `str_replace_editor` call resolves its target and obtains its mutation guard, the recorder copies that exact file before the mutation into the Session's temporary directory, once per path per turn, and copies it again at turn end; the copies are named by the SHA-1 of their bytes, so identical content is stored once. This needs no git. Repository discovery and display paths retain the original project; file captures follow the operation's resolved target even after the Session changes directories. Paths the snapshots cover keep their git counts; the copies serve the other paths — files matching an ignore pattern, files outside the repository, and every file-tool edit when there is no snapshot — with counts from a line comparison of the two copies, so repeated edits to one file count once and a shell edit after a file-tool edit is included. A path whose content is unchanged at turn end is not listed. A copy larger than `maxFileBytes` is not stored: the file is listed with `oversized` and no counts, and a path whose both sides are that large is listed too, since unread content is never known to be unchanged. A path whose only difference is a missing final newline compares as unchanged, while git still counts that line. Files under `/tmp` or the platform temporary directory are excluded unless they lie inside the repository. Changes made only through shell commands outside the snapshot coverage are not recorded. -Each file carries a durable `path` — relative to the working directory inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the working directory, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the working directory's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns. +Each turn reads the Session's current directory and workspace root when it starts, so a Session that entered a worktree is snapshotted in that checkout and lists paths relative to that root. Each file carries a durable `path` — relative to the workspace root inside it, absolute elsewhere — and a `display` path used for ordering and labels: the relative path, a `../` path for repository files above the workspace root, a `~` path under the home directory, otherwise the absolute path. Files sort by `display` in code-unit order, which lists parent and absolute paths before the workspace root's own files. The `workspace/changes` event carries only the turn number; `ctx.workspaceChanges.summary(sessionId, seq)` returns the summary the event with that sequence announced, or undefined once the Session is disposed or when this Host process never recorded it. `ctx.workspaceChanges.diff(sessionId, seq, index, signal)` compares the listed file at that index: hunks with three context lines from the two snapshot trees or the two copies, `binary` for a side git reported as binary or that holds a NUL byte, `oversized` for a side larger than `maxFileBytes`. A line comparison that runs longer than `diffTimeoutMs` degrades to one hunk replacing every line, marked `coarse`. A conversation reopened after a Host restart therefore has no card, and no comparison, for its earlier turns. The intent listeners capture every add, update, delete, and move target of `apply_patch` after policy admission and before provider mutation; a move captures both ends. Review compares each path against its first baseline and lists net changes, including the completed effects of a stopped patch. @@ -90,10 +90,10 @@ Nothing here enters a model request, so provider cache reuse is unaffected. - git 2.13 or later is required for `rev-parse --absolute-git-dir`; an unsupported repository format or another git failure abandons the turn with a warning rather than being treated as a plain directory. - The first snapshot of a Session writes every untracked, non-ignored file of the work tree into the Session's temporary directory; a repository without a `.gitignore` that carries large build outputs costs that much temporary space until the Session is disposed. - Edits the user makes during a turn are attributed to that turn. -- A working directory outside any git repository lists file-tool edits only, so shell edits are missing from its card; a shadow repository under the Harness home is deferred until its exclude rules can replace a missing `.gitignore` reliably. +- A current directory outside any git repository lists file-tool edits only, so shell edits are missing from its card; a shadow repository under the Harness home is deferred until its exclude rules can replace a missing `.gitignore` reliably. - Outside snapshot coverage only paths a file tool names are captured: a file only a shell command changes there is absent, and a file both changed before its first file-tool call is compared from that call onward. - Every file-tool edit copies its whole file once per turn, up to `maxFileBytes`, even for paths the snapshots also cover; the copies go with the Session's temporary directory. -- A comparison serves the listed file's complete text to the client, including ignored files, repository files above the working directory, and files outside the workspace; the summary route serves only paths and counts. A deployment that must keep such content on the Host composes this plugin out. +- A comparison serves the listed file's complete text to the client, including ignored files, repository files above the workspace root, and files outside the workspace; the summary route serves only paths and counts. A deployment that must keep such content on the Host composes this plugin out. - A comparison that degrades to whole-file replacement carries every line of both sides, up to twice `maxFileBytes`. - Windows paths keep native separators in `path`; `display` is always slash-separated. diff --git a/packages/deliverables/workspace-changes/README.zh.md b/packages/deliverables/workspace-changes/README.zh.md index a36f75dea4..0caab8f011 100644 --- a/packages/deliverables/workspace-changes/README.zh.md +++ b/packages/deliverables/workspace-changes/README.zh.md @@ -45,7 +45,7 @@ kind: "package-reference" 在 `write`、`edit`、`apply_patch` 或有修改作用的 `str_replace_editor` 调用解析目标并取得修改防护之后,记录器在实际修改前把该文件复制到 Session 的临时目录,每轮每个路径只复制第一次,轮次结束时再复制一次;副本按其字节的 SHA-1 命名,相同内容只存一份。这一步不需要 git。仓库定位与显示路径保留原始项目;即使 Session 切换目录,文件捕获仍跟随该操作已解析的目标。快照覆盖到的路径保留 git 的行数;其余路径由副本提供,也就是匹配忽略模式的文件、仓库之外的文件,以及没有快照时的每一次文件工具编辑,行数来自两份副本的逐行对比,因此同一文件的重复编辑只计一次,文件工具编辑之后的 shell 改动也包含在内。轮次结束时内容没有变化的路径不会列出。超过 `maxFileBytes` 的副本不会保存:该文件列出时带 `oversized`,没有行数;两侧都这么大的路径同样列出,因为没读过的内容永远不能认定为没有改动。只差一个末尾换行的路径对比为两侧相同,而 git 仍会把那一行计入行数。`/tmp` 与平台临时目录下的文件被排除,除非它们位于仓库内。快照覆盖范围之外只通过 shell 命令做出的改动不会被记录。 -每个文件携带持久的 `path`——位于工作目录内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作目录之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作目录自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。 +每个 turn 开始时读取 Session 的当前目录和工作区根,因此进入 worktree 的 Session 在该检出目录中拍快照,并以该根为基准列出相对路径。每个文件携带持久的 `path`——位于工作区根内时为相对路径,否则为绝对路径——以及用于排序和标签的 `display` 路径:相对路径,仓库内位于工作区根之上的文件为 `../` 路径,家目录下的文件为 `~` 路径,其余为绝对路径。文件按 `display` 的码元顺序排序,因此上级路径和绝对路径排在工作区根自身文件之前。`workspace/changes` 事件只携带轮号;`ctx.workspaceChanges.summary(sessionId, seq)` 返回该序号的事件宣告的摘要,Session 已释放或本 Host 进程从未记录时返回 undefined。`ctx.workspaceChanges.diff(sessionId, seq, index, signal)` 对比该下标所列的文件:从两棵快照树或两份副本得出带三行上下文的 hunk;git 报告为二进制或某一侧含 NUL 字节时返回 `binary`;某一侧超过 `maxFileBytes` 时返回 `oversized`。逐行对比运行超过 `diffTimeoutMs` 时退化为一个替换全部行的 hunk,并标记 `coarse`。因此 Host 重启后重新打开的对话,先前轮次既没有卡片也没有对比。 intent 监听器在策略准入后、提供方修改前捕获 `apply_patch` 的每个新增、更新、删除和移动目标;移动捕获两端。Review 将每个路径与首次基线比较并列出净变化,包括中止补丁已经完成的效果。 @@ -90,10 +90,10 @@ git 通过 `subprocess` 能力运行,使用净化后的环境、`GIT_CONFIG_CO - 需要 git 2.13 或更高版本以支持 `rev-parse --absolute-git-dir`;不支持的仓库格式或其他 git 失败会带着警告放弃本轮,而不是被当成普通目录。 - Session 的首次快照会把工作树里所有未跟踪且未被忽略的文件写进 Session 的临时目录;没有 `.gitignore` 却带着大体积构建产物的仓库,在 Session 释放前会占用同等的临时空间。 - 用户在轮次进行中自己做的编辑会被算到该轮。 -- 不在任何 git 仓库内的工作目录只列文件工具的编辑,卡片里因此没有 shell 改动;Harness home 下的影子仓库暂缓,直到其排除规则能可靠地代替缺失的 `.gitignore`。 +- 不在任何 git 仓库内的当前目录只列文件工具的编辑,卡片里因此没有 shell 改动;Harness home 下的影子仓库暂缓,直到其排除规则能可靠地代替缺失的 `.gitignore`。 - 快照覆盖范围之外只捕获文件工具点名的路径:那里只被 shell 命令改动的文件不会出现,在首次文件工具调用之前被两者都改过的文件从该调用起开始对比。 - 每次文件工具编辑都会把整个文件复制一次,每轮每个路径一次,上限 `maxFileBytes`,即使快照也覆盖该路径;副本随 Session 的临时目录一起删除。 -- 对比会把所列文件的完整文本送到客户端,包括被忽略的文件、工作目录之上的仓库文件和工作区外的文件;摘要路由只送路径和行数。必须把这类内容留在 Host 上的部署应把本插件组合出去。 +- 对比会把所列文件的完整文本送到客户端,包括被忽略的文件、工作区根之上的仓库文件和工作区外的文件;摘要路由只送路径和行数。必须把这类内容留在 Host 上的部署应把本插件组合出去。 - 退化为整文件替换的对比携带两侧的全部行,最多两倍 `maxFileBytes`。 - Windows 路径在 `path` 中保留原生分隔符;`display` 始终用斜杠分隔。 diff --git a/packages/deliverables/workspace-changes/package.json b/packages/deliverables/workspace-changes/package.json index 8201b79125..e23514c498 100644 --- a/packages/deliverables/workspace-changes/package.json +++ b/packages/deliverables/workspace-changes/package.json @@ -40,31 +40,32 @@ "peerDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-fs": "workspace:*" + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/cordis-plugin-include": "workspace:~", "@deepseek-ai/cordis-plugin-loader": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", "@deepseek-ai/dsh-subprocess": "workspace:*", "@deepseek-ai/dsh-subprocess-local": "workspace:*", - "@deepseek-ai/dsh-tools": "workspace:*", - "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-fs": "workspace:*", - "@deepseek-ai/dsh-fs-local": "workspace:*", - "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", - "@deepseek-ai/dsh-agent-loop": "workspace:*", - "@deepseek-ai/dsh-working-directory": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", "@deepseek-ai/dsh-tool-executor-native": "workspace:*", "@deepseek-ai/dsh-tool-fs": "workspace:*", - "@deepseek-ai/dsh-tool-testkit": "workspace:*", "@deepseek-ai/dsh-tool-str-replace-editor": "workspace:*", - "@deepseek-ai/dsh-fs-observation-policy": "workspace:*", - "@deepseek-ai/dsh-system-prompt": "workspace:*" + "@deepseek-ai/dsh-tool-testkit": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/deliverables/workspace-changes/src/index.ts b/packages/deliverables/workspace-changes/src/index.ts index 1448153ef9..c679a75c1c 100644 --- a/packages/deliverables/workspace-changes/src/index.ts +++ b/packages/deliverables/workspace-changes/src/index.ts @@ -15,9 +15,10 @@ import type {} from '@deepseek-ai/dsh-agent' import type { Session, SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-subprocess' import type {} from '@deepseek-ai/dsh-tools' +import type {} from '@deepseek-ai/dsh-working-directory' import type { FsTarget } from '@deepseek-ai/dsh-fs' import { GitRunner } from './git.ts' -import { TurnRecorder } from './recorder.ts' +import { TurnRecorder, type TurnDirectories } from './recorder.ts' import type { WorkspaceChanges } from './types.ts' export type { @@ -56,11 +57,25 @@ export const Config: z = z.object({ diffTimeoutMs: z.number().default(100), }) +/** The original directory of a summarized Session: a top-level Session with a recorded directory. */ function eligible(session: Session): string | undefined { const { cwd, origin, delegationDepth } = session.header return origin === 'subagent' || (delegationDepth ?? 0) > 0 ? undefined : cwd } +/** + * The directories a turn starts from: the Session's current directory, which + * locates the repository, and its workspace root, which listed paths are + * relative to. Without the working-directory service both are the original + * project. + */ +function directoriesOf(ctx: Context, session: Session, original: string): TurnDirectories { + const directories = ctx.get('workingDirectory') + return directories === undefined + ? { cwd: original, root: original } + : { cwd: directories.get(session), root: directories.rootOf(session) } +} + /** * Resolve the git executable once. On macOS the Xcode stub at `/usr/bin/git` * opens an installer dialog instead of running, so it counts as absent until @@ -129,10 +144,10 @@ export function apply(ctx: Context, config: Config): void { }) return runner } - const recorderFor = (session: Session, cwd: string): TurnRecorder => { + const recorderFor = (session: Session, original: string): TurnRecorder => { let recorder = recorders.get(session) if (recorder === undefined) { - recorder = new TurnRecorder(session, cwd, { + recorder = new TurnRecorder(session, () => directoriesOf(ctx, session, original), { git: gitRunner(), tempRoot: tmpdir(), maxFiles: config.maxFiles, maxFileBytes: config.maxFileBytes, diffTimeoutMs: config.diffTimeoutMs, warn: (message) => { ctx.logger.warn(message) }, @@ -144,8 +159,8 @@ export function apply(ctx: Context, config: Config): void { } ctx.on('session/event', (session, event) => { if (event.type === 'turn/start') { - const cwd = eligible(session) - if (cwd !== undefined) recorderFor(session, cwd).start(event.data.turn) + const original = eligible(session) + if (original !== undefined) recorderFor(session, original).start(event.data.turn) return } if (event.type === 'tool/result') recorders.get(session)?.observe(event) diff --git a/packages/deliverables/workspace-changes/src/paths.ts b/packages/deliverables/workspace-changes/src/paths.ts index 306f5bbe61..ae2aaa4c7a 100644 --- a/packages/deliverables/workspace-changes/src/paths.ts +++ b/packages/deliverables/workspace-changes/src/paths.ts @@ -76,7 +76,7 @@ export function isTemporaryPath(path: string, roots: readonly string[]): boolean /** * Sort key and label of a changed file; see `WorkspaceChangedFile.display`. * @param absolute - canonical absolute file path. - * @param cwd - canonical Session working directory. + * @param cwd - canonical Session workspace root. * @param root - repository top-level directory. * @param home - canonical home directory, or empty to skip the `~` form. * @returns the slash-separated display path. @@ -88,9 +88,9 @@ export function displayPathOf(absolute: string, cwd: string, root: string, home: } /** - * The durable `path` field: relative inside the working directory, absolute elsewhere. + * The durable `path` field: relative inside the workspace root, absolute elsewhere. * @param absolute - canonical absolute file path. - * @param cwd - canonical Session working directory. + * @param cwd - canonical Session workspace root. * @returns the path the Web client opens the file through. */ export function durablePathOf(absolute: string, cwd: string): string { diff --git a/packages/deliverables/workspace-changes/src/recorder.ts b/packages/deliverables/workspace-changes/src/recorder.ts index d0abb9e7ad..c12af610f5 100644 --- a/packages/deliverables/workspace-changes/src/recorder.ts +++ b/packages/deliverables/workspace-changes/src/recorder.ts @@ -27,10 +27,20 @@ export interface RecorderEnvironment { warn: (message: string) => void } -/** Canonical paths every comparison and display uses, resolved once per Session. */ -interface Paths { - /** Canonical original project directory for repository discovery and display paths. */ +/** The directories a turn starts from, read when the turn opens. */ +export interface TurnDirectories { + /** The Session's current directory, which locates the repository the turn is snapshotted in. */ cwd: string + /** The Session's workspace root, which listed paths are relative to. */ + root: string +} + +/** Canonical paths every comparison and display uses, resolved when a turn opens. */ +interface Paths { + /** Canonical current directory for repository discovery. */ + cwd: string + /** Canonical workspace root that listed paths are relative to. */ + root: string /** Canonical home directory abbreviated as `~` in display paths. */ home: string /** Temporary roots whose files outside the workspace never enter a summary. */ @@ -69,6 +79,8 @@ interface TurnRecord { /** Everything one turn accumulates; a new turn gets a new object so queued work for an older turn keeps its own. */ interface TurnState { readonly turn: number + /** The workspace root recorded for the turn, as the directory service spells it. */ + readonly root: string /** * The turn-start snapshot once it exists. `null` means no repository or no git, so the turn summarizes file-tool * captures only; `'failed'` means the repository exists but its snapshot failed, so the turn records nothing. @@ -83,8 +95,8 @@ interface TurnState { recordedAfterSeq: number } -function freshState(turn: number): TurnState { - return { turn, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1 } +function freshState(turn: number, root: string): TurnState { + return { turn, root, baseline: null, captures: new Map(), lastToolResultSeq: -1, attemptedAfterSeq: -1, recordedAfterSeq: -1 } } /** A listed file with the sources of its two sides. */ @@ -100,18 +112,22 @@ const OVERSIZED = Symbol('oversized') * comparisons this recorder keeps. Snapshot objects and captured copies live in * a temporary directory owned by the recorder; disposal removes it together * with the summaries. Tool execution waits for pending work so a snapshot or - * capture never races a mutation. A working directory outside any repository, + * capture never races a mutation. A current directory outside any repository, * or a Host without git, gets no snapshot; its summary lists the files the file - * tools changed. + * tools changed. Each turn reads the Session's directories again, so a turn + * that starts in another checkout is snapshotted there and lists paths + * relative to that workspace root. */ export class TurnRecorder { private chain: Promise = Promise.resolve() /** The open turn; before the first `turn/start` it is an empty placeholder no event can match. */ - private state = freshState(0) - /** Canonical paths, resolved by the first turn. */ + private state = freshState(0, '') + /** Canonical paths of the open turn, resolved when it starts. */ private paths: Paths | undefined - /** The located repository, reused across turns once found; null keeps retrying each turn. */ - private repository: Repository | null = null + /** Host facts shared by every turn, resolved by the first. */ + private host: Pick | undefined + /** Located repositories by canonical current directory, reused across turns; an absent entry keeps retrying each turn. */ + private readonly repositories = new Map() /** Temporary directory holding this Session's snapshot objects, scratch indexes, and captured copies. */ private scratch: Promise | undefined /** Records by the sequence of the event that announced them. */ @@ -120,7 +136,7 @@ export class TurnRecorder { constructor( private readonly session: Session, - private readonly cwd: string, + private readonly directories: () => TurnDirectories, private readonly env: RecorderEnvironment, ) {} @@ -129,11 +145,13 @@ export class TurnRecorder { * @param turn - the turn number from `turn/start`. */ start(turn: number): void { - const state = freshState(turn) + const { cwd, root } = this.directories() + const state = freshState(turn, root) this.state = state void this.enqueue(async (signal) => { try { - this.paths ??= { cwd: await realpath(this.cwd), home: await canonicalPath(homedir()), temporaryRoots: await temporaryRoots() } + this.host ??= { home: await canonicalPath(homedir()), temporaryRoots: await temporaryRoots() } + this.paths = { cwd: await realpath(cwd), root: await realpath(root), ...this.host } const repository = await this.locate(this.paths.cwd, signal) if (repository === null) return const tree = await snapshotTree(repository.git, repository.workspace, signal) @@ -271,15 +289,17 @@ export class TurnRecorder { return this.scratch } - /** The repository enclosing the working directory, located once; null keeps retrying each turn. */ + /** The repository enclosing one current directory, located once per directory; null keeps retrying each turn. */ private async locate(cwd: string, signal: AbortSignal): Promise { - if (this.repository !== null) return this.repository + const located = this.repositories.get(cwd) + if (located !== undefined) return located const git = await this.env.git if (git === null) return null const workspace = await locateGitWorkspace(git, cwd, () => this.scratchDir(), signal) if (workspace === null) return null - this.repository = { git, workspace } - return this.repository + const repository = { git, workspace } + this.repositories.set(cwd, repository) + return repository } /** One side's text, null for an absent file, or {@link OVERSIZED} for a snapshot side beyond the byte cap. */ @@ -302,7 +322,7 @@ export class TurnRecorder { const { baseline } = state if (paths === undefined || baseline === 'failed' || state.lastToolResultSeq < 0) return state.attemptedAfterSeq = state.lastToolResultSeq - // Without a snapshot the working directory itself bounds the workspace. + // Without a snapshot the current directory itself bounds the workspace. const root = baseline?.workspace.root ?? paths.cwd const listed = new Map() let snapshot: WorkspaceChangesSummary['snapshot'] @@ -353,7 +373,7 @@ export class TurnRecorder { this.records.set(event.seq, { summary: { turn: state.turn, - cwd: this.cwd, + root: state.root, files: kept.map(entry => entry.file), total: sorted.length, added: sorted.reduce((sum, entry) => sum + entry.file.added, 0), @@ -389,10 +409,10 @@ function isBinary(capture: Capture): boolean { interface Counts { added: number; deleted: number; binary: boolean; oversized?: boolean } -function changedFile({ cwd, home }: Paths, root: string, absolute: string, counts: Counts): WorkspaceChangedFile { +function changedFile({ root: workspaceRoot, home }: Paths, root: string, absolute: string, counts: Counts): WorkspaceChangedFile { return { - path: durablePathOf(absolute, cwd), - display: displayPathOf(absolute, cwd, root, home), + path: durablePathOf(absolute, workspaceRoot), + display: displayPathOf(absolute, workspaceRoot, root, home), added: counts.added, deleted: counts.deleted, ...counts.binary ? { binary: true as const } : {}, diff --git a/packages/deliverables/workspace-changes/src/types.ts b/packages/deliverables/workspace-changes/src/types.ts index 8e48381480..1956d19c7e 100644 --- a/packages/deliverables/workspace-changes/src/types.ts +++ b/packages/deliverables/workspace-changes/src/types.ts @@ -3,10 +3,10 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' /** One file changed during a turn, with line counts from git or from the whole-file captures around its file-tool edits. */ export interface WorkspaceChangedFile { - /** Path relative to the Session working directory, or an absolute Host path outside it. */ + /** Path relative to the Session workspace root, or an absolute Host path outside it. */ path: string /** - * Sort key and label: the relative path inside the working directory, a + * Sort key and label: the relative path inside the workspace root, a * `../` path for repository files above it, a `~` path under the home * directory, otherwise the absolute path. Always slash-separated. */ @@ -25,8 +25,8 @@ export interface WorkspaceChangedFile { export interface WorkspaceChangesSummary { /** The turn whose file changes this summary describes. */ turn: number - /** The Session working directory `path` values are relative to. */ - cwd: string + /** The Session workspace root `path` values are relative to, as it stood when the turn started. */ + root: string /** Changed files in `display` order, capped at the plugin's `maxFiles`. */ files: WorkspaceChangedFile[] /** Complete changed-file count, including files omitted by the cap. */ diff --git a/packages/deliverables/workspace-changes/tests/current-directory.spec.ts b/packages/deliverables/workspace-changes/tests/current-directory.spec.ts index 57e2ee6ced..7751ca2322 100644 --- a/packages/deliverables/workspace-changes/tests/current-directory.spec.ts +++ b/packages/deliverables/workspace-changes/tests/current-directory.spec.ts @@ -62,7 +62,7 @@ it.each(['write', 'edit', 'str_replace_editor'] as const)('captures the resolved const announcement = events.findLast(event => event.type === 'workspace/changes') expect(announcement).toBeDefined() const summary = ctx.workspaceChanges.summary(agent.id, announcement!.seq) - expect(summary).toMatchObject({ cwd: origin, total: 1, files: [{ path: 'current/witness.txt', added: 1, deleted: 1 }] }) + expect(summary).toMatchObject({ root: origin, total: 1, files: [{ path: 'current/witness.txt', added: 1, deleted: 1 }] }) expect(summary!.snapshot).toBeUndefined() expect(await ctx.workspaceChanges.diff(agent.id, announcement!.seq, 0, new AbortController().signal)).toMatchObject({ kind: 'text', hunks: [{ lines: ['-before', '+after'] }] }) }) diff --git a/packages/deliverables/workspace-changes/tests/git.spec.ts b/packages/deliverables/workspace-changes/tests/git.spec.ts index ea7948939f..700edd5800 100644 --- a/packages/deliverables/workspace-changes/tests/git.spec.ts +++ b/packages/deliverables/workspace-changes/tests/git.spec.ts @@ -176,7 +176,7 @@ describe('TurnRecorder', () => { const gate = new Promise((resolve) => { release = resolve }) const tempRoot = await scratchDir('dsh-git-store-', cleanups) const env = { git: gate, tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100, warn: (m: string) => { warnings.push(m) } } - const disposed = new TurnRecorder(session, cwd, env) + const disposed = new TurnRecorder(session, () => ({ cwd: cwd, root: cwd }), env) disposed.start(1) await new Promise(resolve => setTimeout(resolve, 5)) const disposal = disposed.dispose() @@ -188,7 +188,7 @@ describe('TurnRecorder', () => { expect(disposed.summary(1)).toBeUndefined() const { git: missing } = await runner(undefined, '/nonexistent/git-binary') - const failing = new TurnRecorder(session, cwd, { ...env, git: Promise.resolve(missing) }) + const failing = new TurnRecorder(session, () => ({ cwd: cwd, root: cwd }), { ...env, git: Promise.resolve(missing) }) failing.start(1) await failing.settled() expect(warnings).toHaveLength(1) @@ -202,13 +202,13 @@ describe('TurnRecorder', () => { git: Promise.resolve(runnerGit), tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100, warn: (m: string) => { throw new Error(m) }, } - const plain = new TurnRecorder(ctx.sessions.create(SessionId('plain'), { meta: { cwd: tempRoot } }), tempRoot, env) + const plain = new TurnRecorder(ctx.sessions.create(SessionId('plain'), { meta: { cwd: tempRoot } }), () => ({ cwd: tempRoot, root: tempRoot }), env) plain.start(1) await plain.settled() await plain.dispose() const cwd = await scratchDir('dsh-recorder-repo-', cleanups) git(cwd, 'init', '-q', '-b', 'main') - const repo = new TurnRecorder(ctx.sessions.create(SessionId('repo'), { meta: { cwd } }), cwd, env) + const repo = new TurnRecorder(ctx.sessions.create(SessionId('repo'), { meta: { cwd } }), () => ({ cwd, root: cwd }), env) repo.start(1) await repo.settled() const [objects, ...others] = (await readdir(tempRoot)).filter(entry => entry.startsWith('dsh-workspace-changes-')) @@ -231,7 +231,7 @@ describe('TurnRecorder', () => { git: Promise.resolve(runnerGit), tempRoot, maxFiles: 10, maxFileBytes: 1024, diffTimeoutMs: 100, warn: (m: string) => { throw new Error(m) }, } - const recorder = new TurnRecorder(session, cwd, env) + const recorder = new TurnRecorder(session, () => ({ cwd: cwd, root: cwd }), env) startTurn(session, 1) recorder.start(1) await recorder.settled() diff --git a/packages/deliverables/workspace-changes/tests/loader-composition.spec.ts b/packages/deliverables/workspace-changes/tests/loader-composition.spec.ts index 26c795c087..dc18778a1a 100644 --- a/packages/deliverables/workspace-changes/tests/loader-composition.spec.ts +++ b/packages/deliverables/workspace-changes/tests/loader-composition.spec.ts @@ -77,7 +77,7 @@ describe('real Loader composition', () => { const [recorded, ...rest] = changes(context, session) expect(rest).toEqual([]) expect(recorded).toEqual({ - turn: 1, cwd, total: 1, added: 1, deleted: 0, + turn: 1, root: cwd, total: 1, added: 1, deleted: 0, files: [{ path: 'tracked.txt', display: 'tracked.txt', added: 1, deleted: 0 }], snapshot: { before: expect.stringMatching(/^[0-9a-f]+$/) as string, after: expect.stringMatching(/^[0-9a-f]+$/) as string }, }) diff --git a/packages/deliverables/workspace-changes/tests/plugin.spec.ts b/packages/deliverables/workspace-changes/tests/plugin.spec.ts index 7d86ad3670..caa8ea5af5 100644 --- a/packages/deliverables/workspace-changes/tests/plugin.spec.ts +++ b/packages/deliverables/workspace-changes/tests/plugin.spec.ts @@ -88,7 +88,7 @@ describe('workspace-changes in a repository', () => { expect(events.map(event => event.data)).toEqual([{ turn: 1 }]) const [recorded, ...rest] = changes(ctx, session) expect(rest).toEqual([]) - expect(recorded).toMatchObject({ turn: 1, cwd, total: 5, added: 7, deleted: 1 }) + expect(recorded).toMatchObject({ turn: 1, root: cwd, total: 5, added: 7, deleted: 1 }) expect(recorded!.snapshot!.before).toMatch(/^[0-9a-f]{40,64}$/) expect(recorded!.snapshot!.after).toMatch(/^[0-9a-f]{40,64}$/) expect(recorded!.files).toEqual([ @@ -357,7 +357,7 @@ describe('workspace-changes without a repository', () => { endTurn(session, 1) await settle(ctx, session) expect(changes(ctx, session)).toEqual([{ - turn: 1, cwd, total: 3, added: 7, deleted: 1, + turn: 1, root: cwd, total: 3, added: 7, deleted: 1, files: [ { path: 'existing.txt', display: 'existing.txt', added: 3, deleted: 1 }, { path: 'mixed.txt', display: 'mixed.txt', added: 2, deleted: 0 }, @@ -497,7 +497,7 @@ describe('workspace-changes without git', () => { endTurn(session, turn) await settle(ctx, session) } - expect(changes(ctx, session)).toEqual([{ turn: 2, cwd, total: 1, added: 1, deleted: 0, files: [{ path: 'w.txt', display: 'w.txt', added: 1, deleted: 0 }] }]) + expect(changes(ctx, session)).toEqual([{ turn: 2, root: cwd, total: 1, added: 1, deleted: 0, files: [{ path: 'w.txt', display: 'w.txt', added: 1, deleted: 0 }] }]) expect(await ctx.workspaceChanges.diff(session.id, announcedSeq(session), 0, signal)).toMatchObject({ kind: 'text', before: false, after: true, hunks: [{ lines: ['+w'] }] }) expect(info).toHaveBeenCalledTimes(1) expect(info.mock.calls[0]![0]).toContain('git is unavailable') diff --git a/packages/deliverables/workspace-changes/tests/worktree.spec.ts b/packages/deliverables/workspace-changes/tests/worktree.spec.ts new file mode 100644 index 0000000000..aa77404c72 --- /dev/null +++ b/packages/deliverables/workspace-changes/tests/worktree.spec.ts @@ -0,0 +1,91 @@ +/** Turns recorded in the checkout the Session works in: a worktree entered through the working-directory service. */ +import { mkdir, realpath, writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { unsupportedInbox, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit' +import LocalFileSystem from '@deepseek-ai/dsh-fs-local' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory' +import * as WorkspaceChanges from '../src/index.ts' +import { changes, endTurn, git, mutate, scratchDir, settle, startTurn, toolCall } from './support.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + for (const cleanup of cleanups.reverse()) await cleanup() + cleanups.length = 0 +}) + +function agentFor(ctx: Context, session: Session): Agent { + const scope = ctx.plugin(() => {}) + return { + id: session.id, session, options: {}, status: 'idle', ctx: scope.ctx, model: unsupportedModel(), + inbox: unsupportedInbox(), + send() {}, followup() {}, steer() {}, inject() {}, cancel() {}, + whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal), + } +} + +it('snapshots the worktree the Session entered, lists paths relative to it, and leaves the original checkout out', async () => { + // Production headers record canonical paths; anchors compare as recorded, so the fixture does too. + const main = await realpath(await scratchDir('dsh-workspace-changes-worktree-', cleanups)) + git(main, 'init', '-q', '-b', 'main') + await writeFile(join(main, 'a.txt'), 'main\n') + git(main, 'add', '-A') + git(main, 'commit', '-q', '-m', 'init') + await mkdir(join(main, '.agents', 'worktrees'), { recursive: true }) + await writeFile(join(main, '.agents', 'worktrees', '.gitignore'), '*\n') + const worktree = join(main, '.agents', 'worktrees', 'x') + git(main, 'worktree', 'add', '-q', '-b', 'x', worktree) + + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(LocalSubprocessRuntime) + await ctx.plugin(LocalFileSystem, { cwd: main }) + await ctx.plugin(WorkingDirectoryService, {}) + await ctx.plugin(WorkspaceChanges, {} as WorkspaceChanges.Config) + const session = ctx.sessions.create(SessionId('worktree-turns'), { meta: { cwd: main } }) + const agent = agentFor(ctx, session) + await ctx.workingDirectory.relocate(agent, worktree) + + // A shell-only edit inside the worktree is a change of the worktree's repository. + startTurn(session, 1) + await settle(ctx, session) + await writeFile(join(worktree, 'a.txt'), 'edited in the worktree\n') + // Someone else edits the original checkout meanwhile; it is not this turn's work. + await writeFile(join(main, 'a.txt'), 'edited in the original checkout\n') + toolCall(session, 1, 'bash', { command: 'edit' }) + endTurn(session, 1) + await settle(ctx, session) + + // A file-tool edit lists its path relative to the worktree, not to the original project. + startTurn(session, 2) + await settle(ctx, session) + await mutate(ctx, session, 2, 'write', {}, join(worktree, 'b.txt'), () => writeFile(join(worktree, 'b.txt'), 'new\n')) + endTurn(session, 2) + await settle(ctx, session) + + // Back in the original project, the next turn is snapshotted there again. + await ctx.workingDirectory.set(agent, main) + startTurn(session, 3) + await settle(ctx, session) + await writeFile(join(main, 'a.txt'), 'edited again in the original checkout\n') + toolCall(session, 3, 'bash', { command: 'edit' }) + endTurn(session, 3) + await settle(ctx, session) + + const snapshot = { before: expect.stringMatching(/^[0-9a-f]+$/) as string, after: expect.stringMatching(/^[0-9a-f]+$/) as string } + expect(changes(ctx, session)).toEqual([ + { turn: 1, root: worktree, total: 1, added: 1, deleted: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 1 }], snapshot }, + { turn: 2, root: worktree, total: 1, added: 1, deleted: 0, files: [{ path: 'b.txt', display: 'b.txt', added: 1, deleted: 0 }], snapshot }, + { turn: 3, root: main, total: 1, added: 1, deleted: 1, files: [{ path: 'a.txt', display: 'a.txt', added: 1, deleted: 1 }], snapshot }, + ]) +}) diff --git a/packages/deliverables/workspace-changes/tsconfig.json b/packages/deliverables/workspace-changes/tsconfig.json index 3daa220c27..dc2a76c38e 100644 --- a/packages/deliverables/workspace-changes/tsconfig.json +++ b/packages/deliverables/workspace-changes/tsconfig.json @@ -31,6 +31,9 @@ }, { "path": "../../fs/fs" + }, + { + "path": "../../session/working-directory" } ] } diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 80a5b5d31b..be7002b51f 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 6b4ef4961f236526 - zh: 41be8aa5aec35b05 + en: bfc731a029531cc3 + zh: da3b4723c57129a0 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: 1597090848784354 zh: e0dcabfa803fe421 @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 03a5b04c9e7bf1b1 - zh: f606dabcf0ed2f1e + en: 66f58fc72137f1f4 + zh: 681dfb6a2addf42e /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 813c110216..27f0377bb5 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -29,7 +29,7 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese. -- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. +- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable roots; a project that is itself a linked worktree keeps the option, because the sandbox policy grants its shared Git directory. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the tab, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the tab's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the tab's first row shows a warning glyph. - **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button. @@ -127,7 +127,6 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Messages during a turn** — a message that enters while the Agent runs a turn or other maintenance gets no hold: a requested worktree is then created at the first step, where a failure ends the turn without the message, and a removed worktree is not checked, so the working-directory service moves the Session back to the project directory. - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. -- **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. - **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope needs a remote whose default branch HEAD shares history with, or a worktree the Session created. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index cc6d281d7f..16f5f55001 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -29,7 +29,7 @@ kind: "package-reference" 面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。 -- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 +- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内时,该选项不可用,提示中说明原因;项目本身是链接 worktree 时该选项保留,因为沙箱策略会授权其共享 Git 目录。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(标签页中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,标签页中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间标签页顶部一行显示警示图标。 - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 @@ -127,7 +127,6 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **一轮进行中的消息**——Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留:所请求的 worktree 改为在第一步创建,失败时这一轮结束且不带这条消息;已删除的 worktree 不会被检查,工作目录服务会把 Session 移回项目目录。 - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 -- **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 - **变更范围**——待办:单个提交与上一轮的范围。“分支”范围需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/panel.ts b/packages/experimental/client-ui-forge/src/panel.ts index ec64d82ce5..5e099232d1 100644 --- a/packages/experimental/client-ui-forge/src/panel.ts +++ b/packages/experimental/client-ui-forge/src/panel.ts @@ -315,11 +315,13 @@ export class SessionPanel { /** Decide whether the Session's sandbox lets the worktree service write the checkout and its shared Git directory. */ private async blockerOf(inspection: Inspection): Promise { + await this.ctx.sandboxPolicy.prepare(this.session, this.lifetime.signal) const policy = this.ctx.sandboxPolicy.resolve({ session: this.session }) if (policy.mode === 'danger-full-access') return null if (policy.mode === 'read-only') return 'read-only' const root = this.ctx.fs.processPath(await this.ctx.fs.resolve(policy.workspaceRoot, { signal: this.lifetime.signal })) - return within(root, inspection.checkout.root) && within(root, inspection.commonDir) ? null : 'outside-writable-root' + const writable = [root, ...policy.additionalWritableRoots ?? []] + return within(root, inspection.checkout.root) && writable.some(directory => within(directory, inspection.commonDir)) ? null : 'outside-writable-root' } /** Measure the `branch` scope; a failed measurement only hides the local changes card. */ diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index e379ac3126..28eb4de137 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -681,20 +681,11 @@ describe('forgePanel worktree blockers', () => { expect(writable.worktree).toEqual(UNAVAILABLE) }) - it.each([ - ['a linked worktree whose shared Git directory lies outside it', async (root: string, repo: string): Promise => { - const linked = join(root, 'linked') - await git(repo, 'worktree', 'add', '-b', 'feat', linked) - return linked - }], - ['a subdirectory of its checkout', async (_root: string, repo: string): Promise => { - const nested = join(repo, 'src') - await mkdir(nested) - return nested - }], - ])('blocks a worktree for a Session rooted in %s until the Session gets full access', async (_label, place) => { - const { root, repo } = await project() - const opened = await open(await place(root, repo)) + it('blocks a worktree for a Session rooted in a subdirectory of its checkout until the Session gets full access', async () => { + const { repo } = await project() + const nested = join(repo, 'src') + await mkdir(nested) + const opened = await open(nested) const follower = reader(opened) const blocked = await follower.until(ready) @@ -706,6 +697,21 @@ describe('forgePanel worktree blockers', () => { expect(unblocked.worktree.blocker).toBeNull() }) + it('offers a worktree to a Session rooted in a linked worktree because the policy grants its shared Git directory', async () => { + const { root, repo } = await project() + const linked = join(root, 'linked') + await git(repo, 'worktree', 'add', '-b', 'feat', linked) + const opened = await open(linked) + const follower = reader(opened) + + const inspected = await follower.until(ready) + + expect(inspected.repository).toEqual(demo) + expect(inspected.checkout).toMatchObject({ state: 'ready', checkout: { root: linked, linked: true } }) + expect(inspected.worktree.blocker).toBeNull() + expect(opened.ctx.sandboxPolicy.resolve({ session: opened.session }).additionalWritableRoots).toEqual([join(repo, '.git')]) + }) + it('shows no blocker after an inspection fails', async () => { const opened = await open(await plain()) const follower = reader(opened) diff --git a/packages/experimental/worktree/README.i18n.yaml b/packages/experimental/worktree/README.i18n.yaml index 5c6bd272cd..1bf112b5c0 100644 --- a/packages/experimental/worktree/README.i18n.yaml +++ b/packages/experimental/worktree/README.i18n.yaml @@ -18,8 +18,8 @@ en: 9c903d30822184d1 zh: 9ed5df5b262cbbf3 /deepseek-ai-dsh-experimental-worktree/understand-the-implementation: - en: 6971a7ca9073bef1 - zh: b977c28a75c7f963 + en: 4bdfbcafc7cba398 + zh: fae006fcc491b72c /deepseek-ai-dsh-experimental-worktree/further-exploration: en: 5bcd45f0bba56207 zh: fd6342fd6bac5179 diff --git a/packages/experimental/worktree/README.md b/packages/experimental/worktree/README.md index df4f42c15a..c5466499bd 100644 --- a/packages/experimental/worktree/README.md +++ b/packages/experimental/worktree/README.md @@ -46,7 +46,7 @@ The default checkout directory is `/.agents/worktrees/ Implementation internals — click to expand -Git and directory allocation run through the mounted subprocess and sandbox providers with the calling Session's existing file policy. Creation does not widen write access to the destination or shared Git administration directory. Directory creation claims the destination exclusively; cancellation and failed setup can leave retained artifacts, whose path appears in the error. Service disposal aborts pending operations and waits for their settlement. +Git and directory allocation run through the mounted subprocess and sandbox providers with the calling Session's existing file policy. Creation runs under the Session's resolved policy; the sandbox policy grants a linked source checkout's shared Git administration directory before the first write, and creation widens nothing else. Directory creation claims the destination exclusively; cancellation and failed setup can leave retained artifacts, whose path appears in the error. Service disposal aborts pending operations and waits for their settlement. | Source | Responsibility | |---|---| diff --git a/packages/experimental/worktree/README.zh.md b/packages/experimental/worktree/README.zh.md index ed0997cef2..20be5cfcae 100644 --- a/packages/experimental/worktree/README.zh.md +++ b/packages/experimental/worktree/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference"
实现细节——点击展开 -Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调用 Session 的文件策略。创建操作不会扩大目标目录或共享 Git 管理目录的写权限。目录创建独占申请目标路径;取消或初始化失败可能留下已有产物,错误会包含其路径。服务销毁会中止待完成操作,并等待它们结束。 +Git 与目录分配通过挂载的子进程及沙箱提供方执行,沿用调用 Session 的文件策略。创建操作在 Session 解析后的策略下运行;沙箱策略会在首次写入前授权链接源检出目录的共享 Git 管理目录,创建操作不再扩大其他写权限。目录创建独占申请目标路径;取消或初始化失败可能留下已有产物,错误会包含其路径。服务销毁会中止待完成操作,并等待它们结束。 | 源码 | 职责 | |---|---| diff --git a/packages/experimental/worktree/src/index.ts b/packages/experimental/worktree/src/index.ts index f947539778..2f36d887fe 100644 --- a/packages/experimental/worktree/src/index.ts +++ b/packages/experimental/worktree/src/index.ts @@ -190,11 +190,15 @@ export class WorktreeService extends Service { const path = this.ctx.fs.processPath(destination) if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) try { - await this.prepareDirectory(policy, repositoryRoot, poolPath, path, signal) - await run(repositoryRoot, ['--work-tree', repositoryRoot, 'worktree', 'add', '--no-checkout', '-b', branch, '--', path, baseCommit]) - const overrides = await filterOverrides(run, path) + // A linked source checkout writes its shared Git directory outside the root; the policy grants it before the first write. + await this.ctx.sandboxPolicy.prepare(agent.session, signal) + const writing = this.ctx.sandboxPolicy.resolve({ session: agent.session }) + const write = this.gitRunner(writing, signal) + await this.prepareDirectory(writing, repositoryRoot, poolPath, path, signal) + await write(repositoryRoot, ['--work-tree', repositoryRoot, 'worktree', 'add', '--no-checkout', '-b', branch, '--', path, baseCommit]) + const overrides = await filterOverrides(write, path) onPhase?.('checkout') - await run(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', baseCommit], undefined, overrides) + await write(path, ['--work-tree', path, 'reset', '--hard', '--no-recurse-submodules', baseCommit], undefined, overrides) const { cwd: canonicalPath } = await this.ctx.workingDirectory.relocate(agent, path, { signal }) return { path: canonicalPath, branch, baseCommit, repositoryRoot } } catch (error) { @@ -209,9 +213,11 @@ export class WorktreeService extends Service { onPhase: ((phase: CreateWorktreePhase) => void) | undefined, ): Promise { onPhase?.('prepare') + if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) + // The shared Git directory of a linked source checkout joins the policy before the registration is rewritten. + await this.ctx.sandboxPolicy.prepare(agent.session, signal) const policy = this.ctx.sandboxPolicy.resolve({ session: agent.session }) const run = this.gitRunner(policy, signal) - if (await this.ctx.fs.lstat(path, undefined, signal) !== undefined) throw new Error(`worktree path already exists: ${path}`) const root = await this.ctx.fs.resolve(repositoryRoot, { signal }) const pool = await this.ctx.fs.resolve(this.config.directory, { cwd: repositoryRoot, signal }) const target = await this.ctx.fs.resolve(path, { cwd: repositoryRoot, signal }) diff --git a/packages/experimental/worktree/tests/sandbox.spec.ts b/packages/experimental/worktree/tests/sandbox.spec.ts index 90bdd7594b..9f27c015f9 100644 --- a/packages/experimental/worktree/tests/sandbox.spec.ts +++ b/packages/experimental/worktree/tests/sandbox.spec.ts @@ -74,16 +74,24 @@ describe.skipIf(!sandboxUsable)('worktree standing sandbox policy', () => { expect(confine.mock.calls.every(call => call[1].mode === 'workspace-write' && call[1].workspaceRoot === root)).toBe(true) }) - it('does not widen a linked-checkout grant to the shared Git administration directory', async () => { + it('creates from a linked checkout once the policy grants its shared Git administration directory', async () => { root = await repository(process.cwd()) + const administration = join(root, '.git') const linked = join(root, 'linked') await git(root, 'worktree', 'add', '-b', 'linked', linked) ctx = await harness(linked, {}, 'workspace-write') const agent = testAgent(ctx, linked) const confine = vi.spyOn(ctx.sandbox, 'confine') - await expect(ctx.worktrees.create(agent, { name: 'denied-admin' })).rejects.toThrow(/permission denied|operation not permitted|read-only file system/i) - expect(ctx.workingDirectory.get(agent.session)).toBe(linked) - expect(await git(root, 'branch', '--list', 'denied-admin')).toBe('') + const created = await ctx.worktrees.create(agent, { name: 'shared-admin' }) + const checkout = join(linked, '.agents', 'worktrees', 'shared-admin') + + expect(created.path).toBe(checkout) + expect(await git(checkout, 'branch', '--show-current')).toBe('shared-admin') + expect(await git(root, 'worktree', 'list', '--porcelain')).toContain(`worktree ${checkout}`) + expect(ctx.workingDirectory.get(agent.session)).toBe(checkout) + expect(ctx.workingDirectory.rootOf(agent.session)).toBe(checkout) expect(confine.mock.calls.every(call => call[1].mode === 'workspace-write' && call[1].workspaceRoot === linked)).toBe(true) + // The registration write lands in the shared Git directory outside the linked root; only the derived grant admits it. + expect(confine.mock.calls.some(call => call[1].additionalWritableRoots?.includes(administration))).toBe(true) }) }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 4f2b6b027e..d3ee9a4b6e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -2553,7 +2553,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ { key: 'sandboxPolicy', summary: 'The sandbox-policy service (`ctx.sandboxPolicy`).', - description: 'The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session\'s mode log and immutable cwd travel together to every enforcing capability.', + description: 'The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment default mode, fallback workspace root, and current request-time policy section. Tool layers call resolve for each execution so a session\'s mode log and workspace root travel together to every enforcing capability.\n\nA session\'s workspace root comes from the working-directory service when it is mounted: the checkout the Session works in, which a worktree relocation moves. A linked checkout keeps its Git administration directory and the repository\'s common directory outside that root; prepare derives them through the execution-world filesystem once per root, and `resolve` adds the derived directories to `additionalWritableRoots`. Tool executions await that derivation in `tools/pre-execute`; Session creation and every directory change start it early.', methods: [ { signature: 'readonly defaultMode: SandboxMode', @@ -2562,7 +2562,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'readonly workspaceRoot: string', - description: 'The absolute `workspace-write` fallback root for calls without a session cwd.', + description: 'The absolute `workspace-write` fallback root for calls without a session root.', parameters: [], }, { @@ -2572,9 +2572,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy', - description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session cwd is its workspace-write boundary; the configured root is the fallback for agentless calls and sessions without a cwd.', + description: 'Resolve the complete policy for one capability call. An approved explicit mode outranks the session\'s last `sandbox/mode` event, which outranks the deployment default. A session\'s workspace root is its workspace-write boundary, and the Git administration directories prepare derived for that root join the configured extra writable directories; the configured root is the fallback for agentless calls and sessions without a recorded directory.', parameters: [{ name: 'request', description: 'optional session and approved mode override.' }], - returns: 'the fully resolved per-call mode and absolute workspace root.', + returns: 'the fully resolved per-call mode, absolute workspace root, and extra writable directories.', }, { signature: 'overrideOf(session: Session): SandboxMode | undefined', @@ -2582,6 +2582,12 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'session', description: 'session whose log supplies the override.' }], returns: 'the last logged mode, or `undefined` without one.', }, + { + signature: 'async prepare(session: Session, signal?: AbortSignal): Promise', + description: 'Derive the Git administration directories of the session\'s workspace root so the next resolve grants them: a linked checkout\'s `.git` file names its administration directory, whose `commondir` names the repository\'s common directory. Directories inside the root, missing directories, and a root without a `.git` entry add nothing. One derivation runs per root; its result is kept once the root\'s `.git` entry was read, and a failed read is logged and retried on the next call.', + parameters: [{ name: 'session', description: 'session whose workspace root is inspected.' }, { name: 'signal', description: 'caller cancellation, checked before and after the shared derivation.' }], + returns: 'the derived directories outside the root, canonical in the execution world.', + }, ], }, { @@ -3849,9 +3855,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: '@Remote environment(agent: Agent, signal: AbortSignal): TerminalEnvironment', - description: 'Read the Session\'s current directory and terminal limits without filesystem validation or shell lookup.', + description: 'Read the Session\'s workspace root and terminal limits without filesystem validation or shell lookup.', parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'signal', description: 'request cancellation.' }], - returns: 'the logged current directory and terminal limits; retained terminals keep their own process directories.', + returns: 'the logged workspace root and terminal limits; retained terminals keep their own process directories.', }, { signature: '@Remote shells(agent: Agent, signal: AbortSignal): Promise', @@ -10183,7 +10189,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'WorkspaceChangesSummary', - declaration: 'export interface WorkspaceChangesSummary {\n turn: number;\n cwd: string;\n files: WorkspaceChangedFile[];\n total: number;\n added: number;\n deleted: number;\n snapshot?: {\n before: string;\n after: string;\n };\n}', + declaration: 'export interface WorkspaceChangesSummary {\n turn: number;\n root: string;\n files: WorkspaceChangedFile[];\n total: number;\n added: number;\n deleted: number;\n snapshot?: {\n before: string;\n after: string;\n };\n}', }, { name: 'WorkspaceCreateRequest', diff --git a/packages/lsp/tool-lsp/README.i18n.yaml b/packages/lsp/tool-lsp/README.i18n.yaml index 15406bd1ed..447b8fc823 100644 --- a/packages/lsp/tool-lsp/README.i18n.yaml +++ b/packages/lsp/tool-lsp/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-lsp/use-this-package: - en: 9cc52be87b57e19a - zh: 9fa78b6fe3027c1f + en: bb712ee4db551290 + zh: 5c93ff97f40f6a6b /deepseek-ai-dsh-tool-lsp/use-this-package/the-tool: en: 46cbff3bda30f0bc zh: 66e209ae78fb4683 diff --git a/packages/lsp/tool-lsp/README.md b/packages/lsp/tool-lsp/README.md index baa4804ace..b1ebc8491f 100644 --- a/packages/lsp/tool-lsp/README.md +++ b/packages/lsp/tool-lsp/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Queries use the Session's current working directory as their workspace root. Changing directory affects subsequent queries without changing an already running server's root. +Queries use the Session's workspace root. Entering another checkout affects subsequent queries without changing an already running server's root. An agent uses `lsp` when textual matches are ambiguous or before a change that needs precise definitions, implementations, or references; the tool's prompt guidance tells it to prefer `search`/`read` for ordinary navigation. diff --git a/packages/lsp/tool-lsp/README.zh.md b/packages/lsp/tool-lsp/README.zh.md index db825eb415..7ad84d9641 100644 --- a/packages/lsp/tool-lsp/README.zh.md +++ b/packages/lsp/tool-lsp/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -查询使用 Session 的当前工作目录作为工作区根目录。切换目录会影响后续查询,但不会改变已运行服务器的根目录。 +查询使用 Session 的工作区根。进入另一个检出目录会影响后续查询,但不会改变已运行服务器的根目录。 当文本匹配有歧义,或修改前需要精确的定义、实现或引用时,agent(智能体)使用 `lsp`;该工具的提示词指引会告诉它,普通导航应优先使用 `search`/`read`。 diff --git a/packages/lsp/tool-lsp/src/index.ts b/packages/lsp/tool-lsp/src/index.ts index 3a3314a44e..49475d3501 100644 --- a/packages/lsp/tool-lsp/src/index.ts +++ b/packages/lsp/tool-lsp/src/index.ts @@ -181,7 +181,7 @@ export function apply(ctx: Context, config: Config): void { timeoutMs: resolved.timeoutMs, async execute(args, exec) { const input = parseLspArgs(args) - const workspaceRoot = exec.agent === undefined ? undefined : await ctx.workingDirectory.ensure(exec.agent, exec.signal) + const workspaceRoot = exec.agent === undefined ? undefined : ctx.workingDirectory.rootOf(exec.agent.session) if (workspaceRoot === undefined) { throw new LspError('the lsp tool requires a session workspace cwd', 'LSP_WORKSPACE_REQUIRED') } diff --git a/packages/sandbox/sandbox-local/README.i18n.yaml b/packages/sandbox/sandbox-local/README.i18n.yaml index 32a828bd3a..1fea81388b 100644 --- a/packages/sandbox/sandbox-local/README.i18n.yaml +++ b/packages/sandbox/sandbox-local/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7282c9ec77fd6f01 zh: 10e385a9489105e3 /deepseek-ai-dsh-sandbox-local/use-this-package/failures-and-recovery: - en: 9b648f1bfdd55e76 - zh: d9265bdf2e272581 + en: 0938d1e31319d3b4 + zh: 1a77fd6d54a13682 /deepseek-ai-dsh-sandbox-local/understand-the-implementation: en: 15db6ec303151ccc zh: 91f62c1f64192f92 @@ -54,8 +54,8 @@ en: e290ccc9b3c92c08 zh: 469589ac12cdadab /deepseek-ai-dsh-sandbox-local/known-limitations-and-deferred-work: - en: 7cd5c6a4cc971803 - zh: 4e4f495b654d95c5 + en: b2a6a72e340bc620 + zh: 9d9b2894850a131d /deepseek-ai-dsh-sandbox-local/known-limitations-and-deferred-work/dev-note: en: cc273320f6a1beaf zh: 5c57a312ddc50651 diff --git a/packages/sandbox/sandbox-local/README.md b/packages/sandbox/sandbox-local/README.md index de7a26c4bc..122ba4ba41 100644 --- a/packages/sandbox/sandbox-local/README.md +++ b/packages/sandbox/sandbox-local/README.md @@ -56,7 +56,7 @@ With the provider mounted, a command runs under the mode you resolve per call. E An unsupported platform or an unusable runner fails closed: `confine()` rejects with `SANDBOX_UNAVAILABLE` and names the runner options for the platform, and the consumer surfaces that error rather than running the command unconfined. A runner that starts but refuses its profile is identified by its fatal stderr signature and exit code, so a broken sandbox is not mistaken for a denied command. The `runnerCommand` override is an operator assertion: it skips functional probes and assumes the configured runner implements the bwrap-compatible profile honestly. -Seatbelt, bwrap, and Landlock include the policy's explicit `additionalWritableRoots` under `workspace-write`. Read-only ignores those grants. Invalid extra directories raise `SANDBOX_INVALID_ROOT` before the command starts. +Seatbelt, bwrap, Landlock, and Windows ACL include the policy's `additionalWritableRoots` under `workspace-write`; Windows ACL grants each extra root a standing ACE under the workspace SID and passes it to the runner as `--writable`. Read-only ignores those grants. Invalid extra directories raise `SANDBOX_INVALID_ROOT` before the command starts. ----- @@ -130,7 +130,6 @@ No direct invalidation; the named consumers own any request-prefix changes. These limits define when the provider is a poor fit or needs special operational care. They are current package constraints, not a general platform comparison or a task backlog. -- **Windows extra roots** — Windows ACL rejects every workspace-write subprocess carrying extra directories with `SANDBOX_UNSUPPORTED_POLICY`, before grants or child creation. Filesystem tools can enforce these grants independently. Remove the extra grants or use a supported host for process operations. - **Windows ACL enforcement is partial** — NTFS hard links alias one file object across workspace and external paths, reads stay unconfined, and a tree another AppContainer tool has ACL'd with a package SID is unreadable to the Low-integrity child. The provider reports `enforcement: 'partial'` rather than overstating that boundary as full. - **Landlock may be partial** — older supported kernel ABIs confine only the access classes they expose, reported as `enforcement: 'partial'` rather than overstated as full. - **Seatbelt depends on deprecated `sandbox-exec`** — macOS still ships it, but this provider cannot replace or probe that private policy engine if Apple removes it. diff --git a/packages/sandbox/sandbox-local/README.zh.md b/packages/sandbox/sandbox-local/README.zh.md index bb03e87ea6..330cc0f21a 100644 --- a/packages/sandbox/sandbox-local/README.zh.md +++ b/packages/sandbox/sandbox-local/README.zh.md @@ -56,7 +56,7 @@ kind: "package-reference" 不受支持的平台或不可用的 runner 会拒绝执行:`confine()` 以 `SANDBOX_UNAVAILABLE` 拒绝 并列出该平台的 runner 选项,消费方会呈现该错误,而不是让命令不受限制地运行。启动后拒绝自身 profile 的 runner 由其致命 stderr 签名与退出码识别,因此损坏的沙箱不会被误认为被拒绝的命令。`runnerCommand` 覆盖是操作方断言:它跳过功能探测,并假定配置的 runner 诚实实现与 bwrap 兼容的 profile。 -Seatbelt、bwrap 和 Landlock 在 `workspace-write` 下包含策略显式指定的 `additionalWritableRoots`。只读模式忽略这些授权。无效的额外目录会在命令启动前触发 `SANDBOX_INVALID_ROOT`。 +Seatbelt、bwrap、Landlock 和 Windows ACL 在 `workspace-write` 下包含策略的 `additionalWritableRoots`;Windows ACL 为每个额外根目录添加一条工作区 SID 的常驻 ACE,并以 `--writable` 传给 runner。只读模式忽略这些授权。无效的额外目录会在命令启动前触发 `SANDBOX_INVALID_ROOT`。 ----- @@ -130,7 +130,6 @@ Windows 档为每个工作区保留一个确定性写入 SID 和常驻 ACE,同 这些限制说明提供方何时不合适,或何时需要特别运维。它们是当前包约束,不是通用平台对比或任务积压。 -- **Windows 额外根目录**——Windows ACL 在授权或创建子进程前,以 `SANDBOX_UNSUPPORTED_POLICY` 拒绝所有携带额外目录的 workspace-write 子进程。文件系统工具可独立执行这些授权。运行进程操作前,请移除额外授权或使用支持此功能的主机。 - **Windows ACL 只能实现部分强制执行**——NTFS 硬链接会使工作区路径与外部路径指向同一个文件对象,读取仍不受限,且被其他 AppContainer 工具以包 SID 标记过的目录树对 Low 完整性子进程不可读。提供方报告 `enforcement: 'partial'`,而不会把该边界夸大为完整强制执行。 - **Landlock 可能只实现部分强制执行**——较旧且受支持的内核 ABI 只能限制自身公开的访问类别,因此报告 `enforcement: 'partial'`,不会夸大为完整强制执行。 - **Seatbelt 依赖已弃用的 `sandbox-exec`**——macOS 仍会提供它,但若 Apple 移除该私有策略引擎,该提供方无法替换或探测。 diff --git a/packages/sandbox/sandbox-local/src/index.ts b/packages/sandbox/sandbox-local/src/index.ts index acf4b4e738..987aabad61 100644 --- a/packages/sandbox/sandbox-local/src/index.ts +++ b/packages/sandbox/sandbox-local/src/index.ts @@ -34,7 +34,7 @@ import { } from '@deepseek-ai/node-addon-system/landlock-run' import { Context } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' -import { SandboxProvider, SandboxUnavailableError, SandboxUnsupportedPolicyError, canonicalPath } from '@deepseek-ai/dsh-sandbox' +import { SandboxProvider, SandboxUnavailableError, canonicalPath, workspaceWritableRoots } from '@deepseek-ai/dsh-sandbox' import type { ConfinedArgv, ConfinedSandboxMode, RunnerFailureRule, SandboxEnforcement, SandboxPolicy } from '@deepseek-ai/dsh-sandbox' import type { SessionId } from '@deepseek-ai/dsh-session' import { AclWriteGrant, assertTempRootOutsideWorkspace, registerAclDiagnosisSkill, tempWriteSid, workspaceWriteSid } from '@deepseek-ai/dsh-sandbox-windows-acl' @@ -273,6 +273,8 @@ export class LocalSandboxProvider extends SandboxProvider { * dispose). */ private readonly workspaceGrants = new Map() + /** Extra roots already carrying a standing ACE, keyed by workspace root and extra root. */ + private readonly extraGrants = new Set() private readonly tempCapabilities = new Map() constructor(ctx: Context, config: Config) { @@ -358,18 +360,20 @@ export class LocalSandboxProvider extends SandboxProvider { * The windows-acl runner argv for one policy. With a calling session (the * policy's `sessionId`) under workspace-write, the grants are materialized * once per provider lifetime — the standing workspace-root grant per - * workspace and a revocable, RANDOM private-temp capability per live + * workspace, one standing grant per extra writable root under the same + * workspace SID, and a revocable, RANDOM private-temp capability per live * session/workspace pair. The runner receives `--write-sid` plus - * `--temp-write-sid` and grants nothing itself. Agentless workspace-write - * calls pass the ambient temp ROOT and no SID flags: the runner creates and - * removes a random private child directory for that one invocation. + * `--temp-write-sid`, one `--writable` per extra root, and grants nothing + * itself. Agentless workspace-write calls pass the ambient temp ROOT, the + * extra roots, and no SID flags: the runner creates and removes a random + * private child directory and grants the roots for that one invocation. * @param policy - the resolved per-call policy. * @returns the runner invocation. */ private windowsAclRunnerArgv(policy: SandboxPolicy): string[] { - if (policy.mode === 'workspace-write' && (policy.additionalWritableRoots?.length ?? 0) > 0) { - throw new SandboxUnsupportedPolicyError('Windows ACL confinement does not support additional writable directories; remove the extra grants or use a supported host') - } + // Canonical, validated extra roots; the workspace root itself leads that list. + const extras = policy.mode === 'workspace-write' ? workspaceWritableRoots(policy).slice(1) : [] + const writable = extras.flatMap(directory => ['--writable', directory]) const sessionId = policy.sessionId if (sessionId === undefined || policy.mode === 'read-only') { return [ @@ -377,9 +381,10 @@ export class LocalSandboxProvider extends SandboxProvider { '--workspace', policy.workspaceRoot, '--temp', tmpdir(), '--mode', policy.mode, + ...writable, ] } - const temp = this.materializeAclGrant(sessionId, policy.workspaceRoot) + const temp = this.materializeAclGrant(sessionId, policy.workspaceRoot, extras) return [ ...this.windowsAclRunnerInvocation(), '--workspace', policy.workspaceRoot, @@ -387,6 +392,7 @@ export class LocalSandboxProvider extends SandboxProvider { '--mode', policy.mode, '--write-sid', workspaceWriteSid(policy.workspaceRoot), '--temp-write-sid', temp.writeSid, + ...writable, ] } @@ -401,12 +407,14 @@ export class LocalSandboxProvider extends SandboxProvider { * removed before the error propagates. * @param sessionId - the policy's calling-session identity. * @param workspaceRoot - the resolved policy root. + * @param extras - canonical extra writable roots that share the workspace SID. * @returns the pair's private temp directory and write capability. */ - private materializeAclGrant(sessionId: SessionId, workspaceRoot: string): AclTempCapability { + private materializeAclGrant(sessionId: SessionId, workspaceRoot: string, extras: readonly string[]): AclTempCapability { assertTempRootOutsideWorkspace(workspaceRoot, tmpdir()) const writeSid = workspaceWriteSid(workspaceRoot) - if (!this.workspaceGrants.has(workspaceRoot)) { + let workspaceGrant = this.workspaceGrants.get(workspaceRoot) + if (workspaceGrant === undefined) { const grant = AclWriteGrant.create(writeSid) try { grant.add(workspaceRoot, true) @@ -422,6 +430,14 @@ export class LocalSandboxProvider extends SandboxProvider { throw error } this.workspaceGrants.set(workspaceRoot, grant) + workspaceGrant = grant + } + // Each extra root carries one standing ACE for the workspace SID, applied once per provider lifetime. + for (const extra of extras) { + const extraKey = JSON.stringify([workspaceRoot, extra]) + if (this.extraGrants.has(extraKey)) continue + workspaceGrant.add(extra, true) + this.extraGrants.add(extraKey) } const key = JSON.stringify([String(sessionId), workspaceRoot]) const existing = this.tempCapabilities.get(key) diff --git a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts index 646377e85c..f811410b14 100644 --- a/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts +++ b/packages/sandbox/sandbox-local/tests/acl-grants.spec.ts @@ -157,6 +157,34 @@ describe('windows-acl write grants (LocalSandboxProvider)', () => { } }) + it('grants each extra writable root one standing ACE under the workspace SID and passes it as --writable', async () => { + try { + const { sandbox, fiber } = await setup() + const ws = workspaceRoot() + const extra = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-acl-grants-extra-'))) + scratch.push(ws, extra) + const policy: SandboxPolicy = { + mode: 'workspace-write', workspaceRoot: ws, additionalWritableRoots: [extra], sessionId: SessionId('linked'), + } + + const confined = await sandbox.confine(['true'], policy) + expect(confined.argv.slice(confined.argv.indexOf('--temp-write-sid') + 2)).toEqual(['--writable', extra, '--', 'true']) + expect(mockState.grants[0]).toEqual(expect.objectContaining({ + writeSid: WORKSPACE_SID, added: [{ path: ws, standing: true }, { path: extra, standing: true }], + })) + + // The same pair applies its ACE once per provider lifetime, for this session and for another on the workspace. + await sandbox.confine(['true'], policy) + await sandbox.confine(['true'], { ...policy, sessionId: SessionId('linked-peer') }) + expect(mockState.grants[0]?.added).toHaveLength(2) + expect(mockState.grants).toHaveLength(3) + + await fiber.dispose() + } finally { + cleanup() + } + }) + it('read-only materializes no capability; upgrade creates them and downgrade leaves them reusable', async () => { try { const { sandbox, fiber } = await setup() diff --git a/packages/sandbox/sandbox-local/tests/local.spec.ts b/packages/sandbox/sandbox-local/tests/local.spec.ts index e80b7e8476..6c1fde7614 100644 --- a/packages/sandbox/sandbox-local/tests/local.spec.ts +++ b/packages/sandbox/sandbox-local/tests/local.spec.ts @@ -430,18 +430,23 @@ describe('the default seatbelt probe (sandbox-exec contract)', () => { }) describe('the windows-acl probe (runner invocation contract)', () => { - it('refuses unsupported extra grants before a Windows runner or ACL mutation', async () => { + it('passes validated extra grants to the runner as --writable and ignores them under read-only', async () => { + const extra = realpathSync.native(mkdtempSync(join(tmpdir(), 'dsh-acl-extra-'))) const { ctx, sandbox } = await setup({}, { chain: ['windows-acl'], probeWindowsAcl: () => true, windowsAclRunnerArgs: ['node', 'windows-acl-runner.js'], }) try { - await expect(sandbox.confine(['true'], { ...WW, additionalWritableRoots: ['/extra'] })) - .rejects.toThrow('Windows ACL confinement does not support additional writable directories') - await expect(sandbox.confine(['true'], { ...RO, additionalWritableRoots: ['/extra'] })).resolves.toBeDefined() + const confined = await sandbox.confine(['true'], { ...WW, additionalWritableRoots: [extra] }) + expect(confined.argv.slice(-6)).toEqual(['--mode', 'workspace-write', '--writable', extra, '--', 'true']) + await expect(sandbox.confine(['true'], { ...WW, additionalWritableRoots: ['/missing-extra-root'] })) + .rejects.toThrow(expect.objectContaining({ name: 'SandboxInvalidRootError' })) + const readOnly = await sandbox.confine(['true'], { ...RO, additionalWritableRoots: [extra] }) + expect(readOnly.argv).not.toContain('--writable') } finally { await ctx.fiber.dispose() + rmSync(extra, { recursive: true, force: true }) } }) // The product chain reaches windows-acl only unprobed (win32's sole diff --git a/packages/sandbox/sandbox-policy/README.i18n.yaml b/packages/sandbox/sandbox-policy/README.i18n.yaml index 4e91831598..b8e086068d 100644 --- a/packages/sandbox/sandbox-policy/README.i18n.yaml +++ b/packages/sandbox/sandbox-policy/README.i18n.yaml @@ -21,11 +21,11 @@ en: 6704447e52ec295b zh: 9ed812d9e29d5533 /deepseek-ai-dsh-sandbox-policy/use-this-package/minimal-configuration: - en: 069de80f17900193 - zh: 2833f134c8dcb2e4 + en: 4d7544c30a258090 + zh: 682de04c6acf9eee /deepseek-ai-dsh-sandbox-policy/use-this-package/switching-a-session-s-mode: - en: 957d72691e470e5c - zh: c22a3a750af0e4a3 + en: dabffeed89b56cc8 + zh: 8a0ca5051bd55725 /deepseek-ai-dsh-sandbox-policy/use-this-package/failures-and-recovery: en: 9cef5f64a050f468 zh: 5dc42c148b2c902d @@ -33,11 +33,11 @@ en: 2d560aa6681fcfb8 zh: e1c6361a6fa40c63 /deepseek-ai-dsh-sandbox-policy/understand-the-implementation/resolution-precedence: - en: f1f38b10c23947d2 - zh: 7a591e743d6793f5 + en: 9d2e5344a4073a42 + zh: 7e471207e33f6174 /deepseek-ai-dsh-sandbox-policy/understand-the-implementation/the-per-session-store: - en: d13dabff02f2acfd - zh: f593888b4ffddf36 + en: 9cf6f3359616bbe1 + zh: 716398c7cb8c97e4 /deepseek-ai-dsh-sandbox-policy/understand-the-implementation/model-visible-text: en: af0d19c6de17a272 zh: d90e538f9ac85b77 diff --git a/packages/sandbox/sandbox-policy/README.md b/packages/sandbox/sandbox-policy/README.md index c2ff904ac7..47683b5366 100644 --- a/packages/sandbox/sandbox-policy/README.md +++ b/packages/sandbox/sandbox-policy/README.md @@ -45,16 +45,16 @@ Load the package with a default mode; the fail-safe default is `read-only`, and | Field | Default | Meaning | |---|---|---| | `mode` | `read-only` | The deployment default mode a session starts from, validated at load | -| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a cwd; relative values fail at load. Normal agent calls use the session's immutable cwd | +| `workspaceRoot` | `process.cwd()` | Absolute fallback root for agentless calls or sessions without a recorded directory; relative values fail at load. Normal agent calls use the session's workspace root | | `additionalWritableRoots` | `[]` | Explicit physical absolute directories also writable under `workspace-write`; other confined modes grant no access to them | -For a linked Git worktree, the caller can grant its shared Git directory with `additionalWritableRoots`. The caller selects that directory explicitly; the policy does not inspect Git files or grant a parent checkout. These grants are deployment configuration shared by the composition's sessions, rather than saved Session permissions. Granting the entire Git directory also permits changes to hooks and configuration that a later host Git invocation can execute outside the sandbox; use that grant only for trusted tasks. Use physical absolute directory paths. The enforcing host rejects missing paths, files, and symlinked roots, including a directory replaced by a symlink between calls. Remote grants are validated on the remote host. +A session's workspace root is the checkout it works in, read from the [working-directory service](../../session/working-directory/README.md): entering a worktree moves the boundary with it, and a `cd` inside the root leaves it. For a linked Git worktree, `prepare(session)` reads the checkout's `.git` pointer and `commondir` through the execution-world filesystem and adds its Git administration directory and the repository's common directory to the resolved `additionalWritableRoots`; directories inside the root, missing directories, and a root whose `.git` is a directory add nothing. Session creation, every directory change, and each tool execution start that derivation, and tool executions wait for it. The policy grants no parent checkout beyond those directories. These grants are deployment configuration shared by the composition's sessions, rather than saved Session permissions. Granting the entire Git directory also permits changes to hooks and configuration that a later host Git invocation can execute outside the sandbox; use that grant only for trusted tasks. Use physical absolute directory paths. The enforcing host rejects missing paths, files, and symlinked roots, including a directory replaced by a symlink between calls. Remote grants are validated on the remote host. The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-sandbox-policy) is the exhaustive source for every accepted field and its JSDoc. ### Switching a session's mode -A session's mode can be switched at runtime through a UI policy control or an explicit switch; the switch is recorded in the session log and takes effect on the session's next confined call. The switch survives restart through replay, and each session keeps its own mode — two sessions never see each other's state. A switched session keeps its immutable workspace cwd as the writable boundary. +A session's mode can be switched at runtime through a UI policy control or an explicit switch; the switch is recorded in the session log and takes effect on the session's next confined call. The switch survives restart through replay, and each session keeps its own mode — two sessions never see each other's state. A switched session keeps its workspace root as the writable boundary. ### Failures and recovery @@ -72,11 +72,11 @@ This section explains policy resolution, the per-session store, and the model-vi ### Resolution precedence -`resolve({ session, mode })` returns one complete per-call policy: an approved explicit mode outranks the session's last `sandbox/mode` event, which outranks the deployment default. The session's immutable `cwd` supplies the workspace root; otherwise the configured fallback applies. Absolute execution-world spelling is preserved. Enforcing providers canonicalize the root on their own filesystem, so remote `symlink/..` paths are never resolved on the Harness host. +`resolve({ session, mode })` returns one complete per-call policy: an approved explicit mode outranks the session's last `sandbox/mode` event, which outranks the deployment default. The session's workspace root supplies the boundary, falling back to its header directory and then the configured root; the derived Git administration directories of that root join the configured extra directories. Absolute execution-world spelling is preserved. Enforcing providers canonicalize the root on their own filesystem, so remote `symlink/..` paths are never resolved on the Harness host. ### The per-session store -A runtime switch is one log-only `sandbox/mode` event on the session it applies to — the switch IS its event, and nothing mutates mode state out of band. `effective = explicit grant ?? fold(events) ?? deployment default`, so an override survives restart by replay and two sessions never see each other's state. Workspace identity needs no event: the immutable `SessionHeader.cwd` recorded at creation is the root for every call in that session. The event stays log-only; before each request, the owner contributes the current fact to the full runtime-context snapshot, and the agent loop logs that snapshot as a sourced `user/message`. +A runtime switch is one log-only `sandbox/mode` event on the session it applies to — the switch IS its event, and nothing mutates mode state out of band. `effective = explicit grant ?? fold(events) ?? deployment default`, so an override survives restart by replay and two sessions never see each other's state. Workspace identity needs no event of its own: the working-directory service's `workspaceRoot` projection names the root for every call in that session, and the derived Git administration directories are an in-memory fact of this process, read again after a restart. The event stays log-only; before each request, the owner contributes the current fact to the full runtime-context snapshot, and the agent loop logs that snapshot as a sourced `user/message`. ### Model-visible text diff --git a/packages/sandbox/sandbox-policy/README.zh.md b/packages/sandbox/sandbox-policy/README.zh.md index f097626989..e8d50b2c29 100644 --- a/packages/sandbox/sandbox-policy/README.zh.md +++ b/packages/sandbox/sandbox-policy/README.zh.md @@ -45,16 +45,16 @@ kind: "package-reference" | 字段 | 默认值 | 含义 | |---|---|---| | `mode` | `read-only` | 会话起始的部署默认模式,加载时验证 | -| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有 cwd 的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的不可变 cwd | +| `workspaceRoot` | `process.cwd()` | 无 agent 调用或没有记录目录的会话所用的绝对回退根目录;相对值在加载时拒绝。普通 agent 调用使用会话的工作区根 | | `additionalWritableRoots` | `[]` | 在 `workspace-write` 下额外允许写入的显式物理绝对目录;其他受限模式不授予这些目录的写权限 | -对于关联的 Git worktree,调用方可通过 `additionalWritableRoots` 授予共享 Git 目录的写权限。调用方必须显式选择该目录;策略不会读取 Git 文件或授权父检出目录。这些授权是组合中所有会话共享的部署配置,而非保存的 Session 权限。授权整个 Git 目录也允许修改钩子和配置,后续主机 Git 调用可能在沙箱之外执行它们;仅对可信任务使用此授权。使用物理绝对目录路径。执行限制的主机拒绝不存在的路径、文件和符号链接根目录,包括两次调用之间被替换为符号链接的目录。远端授权在远端主机上验证。 +会话的工作区根是它所在的检出目录,从[工作目录服务](../../session/working-directory/README.zh.md)读取:进入 worktree 会一并移动边界,根内部的 `cd` 不改变边界。对于关联的 Git worktree,`prepare(session)` 通过执行环境的文件系统读取检出目录的 `.git` 指针与 `commondir`,把它的 Git 管理目录和仓库公共目录加入解析出的 `additionalWritableRoots`;位于根内部的目录、不存在的目录,以及 `.git` 本身是目录的根都不增加任何内容。会话创建、每次目录变更和每次工具执行都会启动该推导,工具执行会等待它完成。除这些目录之外,策略不授权父检出目录。这些授权是组合中所有会话共享的部署配置,而非保存的 Session 权限。授权整个 Git 目录也允许修改钩子和配置,后续主机 Git 调用可能在沙箱之外执行它们;仅对可信任务使用此授权。使用物理绝对目录路径。执行限制的主机拒绝不存在的路径、文件和符号链接根目录,包括两次调用之间被替换为符号链接的目录。远端授权在远端主机上验证。 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-sandbox-policy)是每个受支持字段及其 JSDoc 的穷尽式真源。 ### 切换会话模式 -会话的模式可以在运行时通过 UI 策略控件或显式切换来更改;切换记录在会话日志中,并在该会话的下一次受限调用时生效。切换通过回放跨重启保留,每个会话保持自己的模式——两个会话绝不会看到彼此状态。切换后的会话继续以不可变的工作区 cwd 作为写入边界。 +会话的模式可以在运行时通过 UI 策略控件或显式切换来更改;切换记录在会话日志中,并在该会话的下一次受限调用时生效。切换通过回放跨重启保留,每个会话保持自己的模式——两个会话绝不会看到彼此状态。切换后的会话继续以工作区根作为写入边界。 ### 失败与恢复 @@ -72,11 +72,11 @@ kind: "package-reference" ### 解析优先级 -`resolve({ session, mode })` 返回一份完整的逐调用策略:已批准的显式模式优先于会话最后一条 `sandbox/mode` 事件,后者又优先于部署默认值。会话的不可变 `cwd` 提供工作区根目录;否则使用配置的回退值。执行环境中的绝对路径写法保持不变。执行限制的提供方在自己的文件系统上规范化根目录,因此远端 `symlink/..` 路径绝不会在 Harness 主机上解析。 +`resolve({ session, mode })` 返回一份完整的逐调用策略:已批准的显式模式优先于会话最后一条 `sandbox/mode` 事件,后者又优先于部署默认值。会话的工作区根提供边界,依次回退到 header 目录和配置的根;该根推导出的 Git 管理目录与配置的额外目录合并。执行环境中的绝对路径写法保持不变。执行限制的提供方在自己的文件系统上规范化根目录,因此远端 `symlink/..` 路径绝不会在 Harness 主机上解析。 ### 逐会话存储 -运行时切换是在对应会话日志中追加的一条仅写入日志的 `sandbox/mode` 事件——切换本身就是事件,任何机制都不会在带外修改模式状态。`effective = explicit grant ?? fold(events) ?? deployment default`,因此覆盖通过回放跨重启保留,两个会话也绝不会看到彼此状态。工作区标识无需事件:创建时记录的不可变 `SessionHeader.cwd` 是该会话每次调用使用的根。事件仍只进入日志;在每次请求前,归属方会把当前事实贡献给完整运行时上下文快照,agent loop(智能体循环)将该快照记录为一条带来源的 `user/message`。 +运行时切换是在对应会话日志中追加的一条仅写入日志的 `sandbox/mode` 事件——切换本身就是事件,任何机制都不会在带外修改模式状态。`effective = explicit grant ?? fold(events) ?? deployment default`,因此覆盖通过回放跨重启保留,两个会话也绝不会看到彼此状态。工作区标识无需自己的事件:工作目录服务的 `workspaceRoot` 投影给出该会话每次调用使用的根,推导出的 Git 管理目录是本进程的内存事实,重启后重新读取。事件仍只进入日志;在每次请求前,归属方会把当前事实贡献给完整运行时上下文快照,agent loop(智能体循环)将该快照记录为一条带来源的 `user/message`。 ### 模型可见文本 diff --git a/packages/sandbox/sandbox-policy/package.json b/packages/sandbox/sandbox-policy/package.json index 308b8d078c..eefd5f8fd2 100644 --- a/packages/sandbox/sandbox-policy/package.json +++ b/packages/sandbox/sandbox-policy/package.json @@ -29,23 +29,33 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-session-projection": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" }, "dependencies": { "@deepseek-ai/schemastery": "workspace:~", "zod": "4.4.3" }, "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@deepseek-ai/dsh-fs": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", "@deepseek-ai/dsh-sandbox": "workspace:*", "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*", "@deepseek-ai/dsh-system-prompt": "workspace:*", - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-session-projection": "workspace:*" + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-user-approval": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*" } } diff --git a/packages/sandbox/sandbox-policy/src/index.ts b/packages/sandbox/sandbox-policy/src/index.ts index 36fdc1f2e8..5d64be9f16 100644 --- a/packages/sandbox/sandbox-policy/src/index.ts +++ b/packages/sandbox/sandbox-policy/src/index.ts @@ -2,8 +2,9 @@ * The sandbox POLICY home (`ctx.sandboxPolicy`): the single owner of the * deployment's sandbox fallbacks plus per-session resolution: the file-effect * {@link SandboxMode}, the `workspace-write` root, the explicit extra writable - * directories, and the override kit (the `sandbox/mode` event, its fold, and - * its write path; the fold is the `sandboxMode` session-projection unit + * directories, the Git administration directories a linked checkout writes + * outside that root, and the override kit (the `sandbox/mode` event, its fold, + * and its write path; the fold is the `sandboxMode` session-projection unit * registered here, while the event and write path come from * `./session-mode.ts`). * Before each agent request, the owner also contributes the resolved policy to @@ -26,10 +27,14 @@ import { Context, Service } from '@deepseek-ai/cordis' import { z as zod } from 'zod' import z from '@deepseek-ai/schemastery' import type {} from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-fs' +import type { FileSystem } from '@deepseek-ai/dsh-fs' import type { SandboxExecutionPolicy, SandboxMode } from '@deepseek-ai/dsh-sandbox' import type { Session } from '@deepseek-ai/dsh-session' import type { ProjectionHandle } from '@deepseek-ai/dsh-session-projection' import type {} from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-tools' +import { within } from '@deepseek-ai/dsh-working-directory' export { SANDBOX_MODES, setSandboxMode } from './session-mode.ts' @@ -78,6 +83,26 @@ function renderPolicyContext(policy: SandboxExecutionPolicy): string { } } +/** The `gitdir:` pointer line of a linked checkout's `.git` file. */ +const GITDIR_POINTER = /^gitdir:[ \t]*(.+?)[ \t\r]*$/m + +/** + * Read one short pointer file inside a Git administration directory through the execution-world filesystem. + * @returns the text, or undefined when the path is not a regular file. + */ +async function pointerText(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise { + const entry = await fs.lstat(path, { cwd }, signal) + if (entry?.type !== 'file') return undefined + return fs.readText(await fs.resolve(path, { cwd, signal }), signal) +} + +/** Resolve a pointer target to a canonical directory, or undefined when it is not an existing directory. */ +async function pointerDirectory(fs: FileSystem, path: string, cwd: string, signal: AbortSignal): Promise { + const target = await fs.resolve(path, { cwd, signal }) + const info = await fs.stat(target, signal) + return info?.type === 'directory' ? fs.processPath(target) : undefined +} + declare module '@deepseek-ai/cordis' { interface Context { sandboxPolicy: SandboxPolicyService @@ -95,16 +120,18 @@ export interface Config { /** File-sandbox mode a session starts from (default: `read-only`). */ mode?: SandboxMode /** - * Absolute fallback root for agentless calls and sessions without a cwd (default: - * `process.cwd()`). Normal agent calls use their session cwd instead. + * Absolute fallback root for agentless calls and sessions without a recorded + * directory (default: `process.cwd()`). Normal agent calls use their + * session's workspace root instead. */ workspaceRoot?: string /** * Extra physical absolute directories that `workspace-write` may also write under - * (default: none). The supervisor names them explicitly; there is no - * automatic repository or gitfile discovery. Entries are execution-world - * paths: this service validates absoluteness and detaches the list, while - * the enforcing host rejects missing, non-directory, or symlinked paths. They grant nothing under + * (default: none). The supervisor names them explicitly; the Git + * administration directories of a linked checkout are derived separately + * and need no entry here. Entries are execution-world paths: this service + * validates absoluteness and detaches the list, while the enforcing host + * rejects missing, non-directory, or symlinked paths. They grant nothing under * `read-only`. */ additionalWritableRoots?: string[] @@ -112,7 +139,7 @@ export interface Config { /** Inputs that select the sandbox policy for one capability call. */ export interface SandboxPolicyRequest { - /** Calling session; its immutable cwd becomes the workspace boundary. */ + /** Calling session; its workspace root becomes the workspace boundary. */ session?: Session /** Explicit approved mode override, which outranks session policy. */ mode?: SandboxMode @@ -129,7 +156,16 @@ const sandboxModeStateSchema = zod.union([ * The sandbox-policy service (`ctx.sandboxPolicy`). Owns the deployment * default mode, fallback workspace root, and current request-time policy * section. Tool layers call {@link resolve} for each execution so a session's - * mode log and immutable cwd travel together to every enforcing capability. + * mode log and workspace root travel together to every enforcing capability. + * + * A session's workspace root comes from the working-directory service when + * it is mounted: the checkout the Session works in, which a worktree + * relocation moves. A linked checkout keeps its Git administration directory + * and the repository's common directory outside that root; {@link prepare} + * derives them through the execution-world filesystem once per root, and + * `resolve` adds the derived directories to `additionalWritableRoots`. Tool + * executions await that derivation in `tools/pre-execute`; Session creation and + * every directory change start it early. */ export class SandboxPolicyService extends Service { // Inline schema call: the config catalog walks `static Config` statically. @@ -145,11 +181,16 @@ export class SandboxPolicyService extends Service { /** The deployment default mode — the fallback beneath a session override. */ readonly defaultMode: SandboxMode - /** The absolute `workspace-write` fallback root for calls without a session cwd. */ + /** The absolute `workspace-write` fallback root for calls without a session root. */ readonly workspaceRoot: string /** The frozen extra writable directories shared by every resolved policy, or `undefined` for none. */ readonly additionalWritableRoots: readonly string[] | undefined private sandboxModeProjectionHandle!: ProjectionHandle + /** Derived Git administration directories by workspace root; present only once the root's `.git` entry was read. */ + private readonly gitAdministration = new Map() + /** Derivations in flight by workspace root. */ + private readonly derivations = new Map>() + private readonly lifecycle = new AbortController() constructor(ctx: Context, config: Config) { super(ctx, 'sandboxPolicy') @@ -183,23 +224,39 @@ export class SandboxPolicyService extends Service { }, }) }) + ctx.on('session/created', (session) => { this.prewarm(session) }) + ctx.on('session/event', (session, event) => { + if (event.type === 'working-directory/change') this.prewarm(session) + }) + ctx.on('tools/pre-execute', async (exec, next) => { + if (exec.agent !== undefined) await this.prepare(exec.agent.session, exec.signal) + return next() + }) + ctx.effect(() => async () => { + this.lifecycle.abort(new Error('sandbox-policy service disposed')) + await Promise.allSettled(this.derivations.values()) + }) } /** * Resolve the complete policy for one capability call. An approved explicit * mode outranks the session's last `sandbox/mode` event, which outranks the - * deployment default. A session cwd is its workspace-write boundary; the + * deployment default. A session's workspace root is its workspace-write + * boundary, and the Git administration directories {@link prepare} derived + * for that root join the configured extra writable directories; the * configured root is the fallback for agentless calls and sessions without a - * cwd. + * recorded directory. * @param request - optional session and approved mode override. - * @returns the fully resolved per-call mode and absolute workspace root. + * @returns the fully resolved per-call mode, absolute workspace root, and extra writable directories. */ resolve(request: SandboxPolicyRequest = {}): SandboxExecutionPolicy { const { session } = request + const workspaceRoot = resolveWorkspaceRoot(this.rootOf(session)) + const additional = this.additionalRootsWith(session === undefined ? undefined : this.gitAdministration.get(workspaceRoot)) return { mode: request.mode ?? (session === undefined ? undefined : this.overrideOf(session)) ?? this.defaultMode, - workspaceRoot: resolveWorkspaceRoot(session?.header.cwd ?? this.workspaceRoot), - ...this.additionalWritableRoots === undefined ? {} : { additionalWritableRoots: this.additionalWritableRoots }, + workspaceRoot, + ...additional === undefined ? {} : { additionalWritableRoots: additional }, ...session === undefined ? {} : { sessionId: session.id }, } } @@ -212,6 +269,88 @@ export class SandboxPolicyService extends Service { overrideOf(session: Session): SandboxMode | undefined { return this.sandboxModeProjectionHandle.stateOf(session) ?? undefined } + + /** + * Derive the Git administration directories of the session's workspace root + * so the next {@link resolve} grants them: a linked checkout's `.git` file + * names its administration directory, whose `commondir` names the + * repository's common directory. Directories inside the root, missing + * directories, and a root without a `.git` entry add nothing. One derivation + * runs per root; its result is kept once the root's `.git` entry was read, + * and a failed read is logged and retried on the next call. + * @param session - session whose workspace root is inspected. + * @param signal - caller cancellation, checked before and after the shared derivation. + * @returns the derived directories outside the root, canonical in the execution world. + */ + async prepare(session: Session, signal?: AbortSignal): Promise { + signal?.throwIfAborted() + const root = this.rootOf(session) + const settled = this.gitAdministration.get(root) + if (settled !== undefined) return settled + let derivation = this.derivations.get(root) + if (derivation === undefined) { + derivation = this.derive(root).finally(() => { this.derivations.delete(root) }) + this.derivations.set(root, derivation) + } + const derived = await derivation + signal?.throwIfAborted() + return derived + } + + private prewarm(session: Session): void { + // Failures are logged inside the derivation; disposal rejects the pending wait. + void this.prepare(session).catch(() => undefined) + } + + private async derive(root: string): Promise { + const fs = this.ctx.get('fs') + if (fs === undefined) return [] + const signal = this.lifecycle.signal + try { + const pointer = await fs.lstat('.git', { cwd: root }, signal) + if (pointer === undefined) return [] + const outside: string[] = [] + if (pointer.type === 'file') { + const text = await fs.readText(await fs.resolve('.git', { cwd: root, signal }), signal) + const target = GITDIR_POINTER.exec(text)?.[1] + const gitDirectory = target === undefined ? undefined : await pointerDirectory(fs, target, root, signal) + if (gitDirectory !== undefined) { + outside.push(gitDirectory) + const common = (await pointerText(fs, 'commondir', gitDirectory, signal))?.trim() + const commonDirectory = common === undefined || common.length === 0 + ? undefined + : await pointerDirectory(fs, common, gitDirectory, signal) + if (commonDirectory !== undefined) outside.push(commonDirectory) + } + } + signal.throwIfAborted() + const derived = Object.freeze(outside.filter((directory, index) => !within(root, directory) + && !outside.some((other, otherIndex) => otherIndex !== index && other !== directory && within(other, directory)) + && outside.indexOf(directory) === index)) + this.gitAdministration.set(root, derived) + return derived + } catch (error) { + if (signal.aborted) throw error + this.ctx.logger.warn(`sandbox-policy: could not derive the Git administration directories of ${JSON.stringify(root)}: ${String(error)}`) + return [] + } + } + + /** + * The session's workspace root: the working-directory root when one is recorded, else the header directory, + * else the deployment fallback. + */ + private rootOf(session: Session | undefined): string { + if (session === undefined) return this.workspaceRoot + const directories = this.ctx.get('workingDirectory') + if (directories !== undefined && directories.anchorsOf(session).length > 0) return directories.rootOf(session) + return session.header.cwd ?? this.workspaceRoot + } + + private additionalRootsWith(derived: readonly string[] | undefined): readonly string[] | undefined { + if (derived === undefined || derived.length === 0) return this.additionalWritableRoots + return Object.freeze([...new Set([...this.additionalWritableRoots ?? [], ...derived])]) + } } export default SandboxPolicyService diff --git a/packages/session/working-directory/tests/admission.spec.ts b/packages/sandbox/sandbox-policy/tests/admission.spec.ts similarity index 100% rename from packages/session/working-directory/tests/admission.spec.ts rename to packages/sandbox/sandbox-policy/tests/admission.spec.ts diff --git a/packages/sandbox/sandbox-policy/tests/workspace-root.spec.ts b/packages/sandbox/sandbox-policy/tests/workspace-root.spec.ts new file mode 100644 index 0000000000..0eb32d3c48 --- /dev/null +++ b/packages/sandbox/sandbox-policy/tests/workspace-root.spec.ts @@ -0,0 +1,246 @@ +/** The workspace-write boundary follows the Session's workspace root, and a linked checkout's Git administration directories join it. */ +import { execFile } from 'node:child_process' +import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { promisify } from 'node:util' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { unsupportedInbox, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit' +import LocalFileSystem from '@deepseek-ai/dsh-fs-local' +import SandboxPolicyService from '@deepseek-ai/dsh-sandbox-policy' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import WorkingDirectoryService from '@deepseek-ai/dsh-working-directory' + +const execute = promisify(execFile) + +async function git(cwd: string, ...args: string[]): Promise { + const result = await execute('git', ['-c', 'core.hooksPath=/dev/null', ...args], { + cwd, + env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '', GIT_DIR: undefined, GIT_WORK_TREE: undefined }, + }) + return result.stdout.trim() +} + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + for (const cleanup of cleanups.reverse()) await cleanup() + cleanups.length = 0 +}) + +/** A scratch directory holding a committed repository and room for checkouts beside it. */ +async function scratch(): Promise<{ base: string; repo: string }> { + const base = await realpath(await mkdtemp(join(tmpdir(), 'dsh-policy-root-'))) + cleanups.push(() => rm(base, { recursive: true, force: true })) + const repo = join(base, 'repo') + await mkdir(repo) + await git(repo, 'init', '-q', '-b', 'main') + await git(repo, 'config', 'user.name', 'Policy fixture') + await git(repo, 'config', 'user.email', 'policy@example.invalid') + await git(repo, 'config', 'commit.gpgSign', 'false') + await writeFile(join(repo, 'tracked.txt'), 'initial\n') + await git(repo, 'add', 'tracked.txt') + await git(repo, 'commit', '-q', '-m', 'initial') + return { base, repo } +} + +async function mounted(base: string, config: { mode?: 'workspace-write'; additionalWritableRoots?: string[] } = {}) { + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(LocalFileSystem, { cwd: base }) + await ctx.plugin(WorkingDirectoryService, {}) + const fiber = await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: base, ...config }) + return { ctx, fiber } +} + +function agentFor(ctx: Context, session: Session): Agent { + const scope = ctx.plugin(() => {}) + return { + id: session.id, session, options: {}, status: 'idle', ctx: scope.ctx, model: unsupportedModel(), + inbox: unsupportedInbox(), + send() {}, followup() {}, steer() {}, inject() {}, cancel() {}, + whenIdle: async () => {}, runMaintenance: task => task(new AbortController().signal), + } +} + +/** Run the tool pre-execution waterfall the way the tool pipeline does for one Agent. */ +async function preExecute(ctx: Context, agent: Agent): Promise { + const exec = { agent, signal: new AbortController().signal } + await ctx.waterfall('tools/pre-execute', exec as never, () => Promise.resolve(undefined as never)) +} + +describe('workspace root as the write boundary', () => { + it('follows the Session into a worktree and back to the original project', async () => { + const { base, repo } = await scratch() + const { ctx } = await mounted(base) + const worktree = join(repo, '.agents', 'worktrees', 'topic') + await mkdir(join(repo, '.agents', 'worktrees'), { recursive: true }) + await git(repo, 'worktree', 'add', '-q', '-b', 'topic', worktree) + const session = ctx.sessions.create(SessionId('boundary'), { meta: { cwd: repo } }) + const agent = agentFor(ctx, session) + expect(ctx.sandboxPolicy.resolve({ session }).workspaceRoot).toBe(repo) + + await ctx.workingDirectory.set(agent, join(repo, '.agents')) + expect(ctx.sandboxPolicy.resolve({ session }).workspaceRoot).toBe(repo) + + await ctx.workingDirectory.relocate(agent, worktree) + expect(ctx.sandboxPolicy.resolve({ session }).workspaceRoot).toBe(worktree) + // An agentless tool execution has no root to prepare and passes through. + await ctx.waterfall('tools/pre-execute', { signal: new AbortController().signal } as never, () => Promise.resolve(undefined as never)) + await preExecute(ctx, agent) + expect(ctx.sandboxPolicy.resolve({ session })).toEqual({ + mode: 'workspace-write', workspaceRoot: worktree, additionalWritableRoots: [join(repo, '.git')], sessionId: session.id, + }) + + await ctx.workingDirectory.set(agent, repo) + expect(ctx.sandboxPolicy.resolve({ session })).toEqual({ mode: 'workspace-write', workspaceRoot: repo, sessionId: session.id }) + }) + + it('falls back to the configured root for a Session without a recorded directory while the directory service is mounted', async () => { + const { base } = await scratch() + const { ctx } = await mounted(base) + const session = ctx.sessions.create(SessionId('no-directory')) + expect(ctx.sandboxPolicy.resolve({ session }).workspaceRoot).toBe(base) + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([]) + }) +}) + +describe('Git administration directories of a linked checkout', () => { + it('derives the common directory for a Session opened inside a linked worktree and merges configured extras', async () => { + const { base, repo } = await scratch() + const extra = join(base, 'extra') + await mkdir(extra) + const { ctx } = await mounted(base, { additionalWritableRoots: [extra] }) + const worktree = join(base, 'elsewhere', 'wt') + await mkdir(join(base, 'elsewhere')) + await git(repo, 'worktree', 'add', '-q', '-b', 'wt', worktree) + const session = ctx.sessions.create(SessionId('linked'), { meta: { cwd: worktree } }) + // Session creation starts the derivation; a tool execution waits for it. + await preExecute(ctx, agentFor(ctx, session)) + const policy = ctx.sandboxPolicy.resolve({ session }) + expect(policy.workspaceRoot).toBe(worktree) + expect(policy.additionalWritableRoots).toEqual([extra, join(repo, '.git')]) + expect(Object.isFrozen(policy.additionalWritableRoots)).toBe(true) + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([join(repo, '.git')]) + expect(ctx.sandboxPolicy.resolve()).toEqual({ mode: 'workspace-write', workspaceRoot: base, additionalWritableRoots: [extra] }) + }) + + it('adds nothing for a checkout whose .git is a directory and retries a root that has no .git entry yet', async () => { + const { base, repo } = await scratch() + const { ctx } = await mounted(base) + const plain = ctx.sessions.create(SessionId('plain'), { meta: { cwd: repo } }) + expect(await ctx.sandboxPolicy.prepare(plain)).toEqual([]) + expect(ctx.sandboxPolicy.resolve({ session: plain })).toEqual({ mode: 'workspace-write', workspaceRoot: repo, sessionId: plain.id }) + + const later = join(base, 'later') + const session = ctx.sessions.create(SessionId('later'), { meta: { cwd: later } }) + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([]) + await git(repo, 'worktree', 'add', '-q', '-b', 'later', later) + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([join(repo, '.git')]) + expect(ctx.sandboxPolicy.resolve({ session }).additionalWritableRoots).toEqual([join(repo, '.git')]) + }) + + it('keeps only existing directories outside the root and tolerates malformed pointer files', async () => { + const { base } = await scratch() + const { ctx } = await mounted(base) + const administration = join(base, 'administration') + await mkdir(administration) + const handmade = join(base, 'handmade') + await mkdir(handmade) + await writeFile(join(handmade, '.git'), `gitdir: ${administration}\n`) + const handmadeSession = ctx.sessions.create(SessionId('handmade'), { meta: { cwd: handmade } }) + expect(await ctx.sandboxPolicy.prepare(handmadeSession)).toEqual([administration]) + + const blank = join(base, 'blank-common') + await mkdir(blank) + await writeFile(join(blank, 'commondir'), '') + const blankSession = ctx.sessions.create(SessionId('blank-common'), { meta: { cwd: join(base, 'blank-checkout') } }) + await mkdir(join(base, 'blank-checkout')) + await writeFile(join(base, 'blank-checkout', '.git'), `gitdir: ${blank}\n`) + expect(await ctx.sandboxPolicy.prepare(blankSession)).toEqual([blank]) + + const dangling = join(base, 'dangling') + await mkdir(dangling) + await writeFile(join(dangling, '.git'), `gitdir: ${join(base, 'missing-administration')}\n`) + expect(await ctx.sandboxPolicy.prepare(ctx.sessions.create(SessionId('dangling'), { meta: { cwd: dangling } }))).toEqual([]) + + const missingCommon = join(base, 'missing-common') + await mkdir(join(missingCommon, 'admin'), { recursive: true }) + await writeFile(join(missingCommon, 'admin', 'commondir'), '../nowhere\n') + await writeFile(join(missingCommon, '.git'), 'gitdir: admin\n') + expect(await ctx.sandboxPolicy.prepare(ctx.sessions.create(SessionId('missing-common'), { meta: { cwd: missingCommon } }))).toEqual([]) + + const malformed = join(base, 'malformed') + await mkdir(malformed) + await writeFile(join(malformed, '.git'), 'not a pointer\n') + expect(await ctx.sandboxPolicy.prepare(ctx.sessions.create(SessionId('malformed'), { meta: { cwd: malformed } }))).toEqual([]) + }) + + it('logs a failed read, grants nothing for it, and derives again on the next call', async () => { + const { base, repo } = await scratch() + const { ctx } = await mounted(base) + const worktree = join(base, 'retry') + await git(repo, 'worktree', 'add', '-q', '-b', 'retry', worktree) + const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {}) + const lstat = vi.spyOn(ctx.fs, 'lstat').mockRejectedValueOnce(new Error('disk unavailable')) + try { + const session = ctx.sessions.create(SessionId('retry'), { meta: { cwd: worktree } }) + await vi.waitFor(() => { expect(warn).toHaveBeenCalledTimes(1) }) + expect(warn.mock.calls[0]?.[0]).toContain('could not derive the Git administration directories') + expect(ctx.sandboxPolicy.resolve({ session }).additionalWritableRoots).toBeUndefined() + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([join(repo, '.git')]) + } finally { + lstat.mockRestore() + warn.mockRestore() + } + }) + + it('shares one derivation between concurrent callers and rejects callers when the service is disposed first', async () => { + const { base, repo } = await scratch() + const { ctx, fiber } = await mounted(base) + const worktree = join(base, 'shared') + await git(repo, 'worktree', 'add', '-q', '-b', 'shared', worktree) + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const lstat = ctx.fs.lstat.bind(ctx.fs) + const probe = vi.spyOn(ctx.fs, 'lstat').mockImplementation(async (path, opts, signal) => { + entered.resolve(undefined) + await release.promise + signal?.throwIfAborted() + return lstat(path, opts, signal) + }) + try { + const session = ctx.sessions.create(SessionId('shared'), { meta: { cwd: worktree } }) + await entered.promise + const first = ctx.sandboxPolicy.prepare(session) + const second = ctx.sandboxPolicy.prepare(session) + expect(probe).toHaveBeenCalledTimes(1) + const disposal = fiber.dispose() + release.resolve(undefined) + await expect(first).rejects.toThrow('sandbox-policy service disposed') + await expect(second).rejects.toThrow('sandbox-policy service disposed') + await disposal + } finally { + release.resolve(undefined) + probe.mockRestore() + } + }) + + it('derives nothing without a filesystem provider', async () => { + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SandboxPolicyService, { mode: 'workspace-write', workspaceRoot: '/fallback' }) + const session = ctx.sessions.create(SessionId('no-fs'), { meta: { cwd: '/projects/current' } }) + expect(await ctx.sandboxPolicy.prepare(session)).toEqual([]) + expect(ctx.sandboxPolicy.resolve({ session })).toEqual({ mode: 'workspace-write', workspaceRoot: '/projects/current', sessionId: session.id }) + }) +}) diff --git a/packages/sandbox/sandbox-policy/tsconfig.json b/packages/sandbox/sandbox-policy/tsconfig.json index 7a1856559d..48c63e92fa 100644 --- a/packages/sandbox/sandbox-policy/tsconfig.json +++ b/packages/sandbox/sandbox-policy/tsconfig.json @@ -31,6 +31,15 @@ }, { "path": "../../session/session-projection" + }, + { + "path": "../../fs/fs" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../session/working-directory" } ] } diff --git a/packages/sandbox/sandbox-windows-acl/README.md b/packages/sandbox/sandbox-windows-acl/README.md index 732ca20a35..8c8f5b7793 100644 --- a/packages/sandbox/sandbox-windows-acl/README.md +++ b/packages/sandbox/sandbox-windows-acl/README.md @@ -110,7 +110,7 @@ Authenticated Users is absent from both lists — the WMI namespace security che The seam-facing shape is the runner entry (`./runner`): an argv-prefix wrapper `dsh-sandbox-local` spawns in place of the caller's command, with the same architecture as bwrap/landlock-run/sandbox-exec. The runner creates the restricted token, spawns the wrapped argv under it with the caller's stdio passed straight through, wraps the child in a `KILL_ON_JOB_CLOSE` job, mirrors the child's exit code, and revokes its self-managed temp grant on exit. Every runner-side failure prints `windows-acl-run: ` to stderr and exits 127 — the seam's runner-failure rules match that signature. ```sh -node runner.js --workspace --temp --mode [--write-sid --temp-write-sid ] -- +node runner.js --workspace --temp --mode [--write-sid --temp-write-sid ] [--writable ]... -- ``` The seam materializes the deterministic workspace SID's ACE standing (once per workspace per server lifetime — the reuse cache), then creates a random private temp directory and a distinct revocable SID for each live session/workspace pair, passing both as the required `--write-sid`/`--temp-write-sid` pair; the runner verifies each against its owning path and neither grants nor revokes (`manageDacls: false`). A fork receives a different temp capability, and a fresh provider gives even the same resumed session a new path and SID, so crash residue is inert litter. Without the pair, `--temp` names a root: an agentless workspace-write runner creates a random private child, self-manages its temp SID, rewrites TMP/TEMP, and removes the child on exit. Re-granting the standing workspace ACE after a restart is idempotent: `grantWrite` reads the current DACL and skips the re-propagation when the exact ACE already stands. A workspace equal to or containing the temp root is rejected before any grant. diff --git a/packages/sandbox/sandbox-windows-acl/README.zh.md b/packages/sandbox/sandbox-windows-acl/README.zh.md index ad9de70659..21e5e8b67a 100644 --- a/packages/sandbox/sandbox-windows-acl/README.zh.md +++ b/packages/sandbox/sandbox-windows-acl/README.zh.md @@ -112,7 +112,7 @@ Authenticated Users 在两种列表中都不存在——WMI 命名空间安全 面向 seam 的形态是 runner 入口(`./runner`):`dsh-sandbox-local` 在调用者命令的位置 spawn 的 argv 前缀包装——与 bwrap/landlock-run/sandbox-exec 同一架构。runner 创建受限令牌,在它之下 spawn 包装后的 argv,调用者的 stdio 直接透传,把子进程包进 `KILL_ON_JOB_CLOSE` job,镜像子进程的退出码,并在退出时撤销其自行管理的临时授权。每个 runner 侧失败都会向 stderr 打印 `windows-acl-run: ` 并以 127 退出——seam 的 runner 失败规则匹配该签名。 ```sh -node runner.js --workspace --temp --mode [--write-sid --temp-write-sid ] -- +node runner.js --workspace --temp --mode [--write-sid --temp-write-sid ] [--writable ]... -- ``` seam 先把确定性工作区 SID 的 ACE 常驻物化(每个工作区每服务器生命周期一次——复用缓存),再为每个活跃的会话/工作区对创建随机私有临时目录和不同的可回收 SID,把两种身份作为必须成对出现的 `--write-sid`/`--temp-write-sid` 传入;runner 对照各自所属路径验证二者,既不授权也不撤销(`manageDacls: false`)。fork 获得不同的临时能力;即使恢复的是同一会话,新的提供方也会给出新的路径和 SID,因此崩溃残留只是失效垃圾。如果不带这一对标志,`--temp` 指定的是根目录:无 agent(智能体)/独立的 workspace-write runner 会创建随机私有子目录,自行管理其临时 SID,重写 TMP/TEMP,并在退出时移除该子目录。重启后重新授权常驻工作区 ACE 是幂等的:`grantWrite` 读取当前 DACL,当完全相同的 ACE 已存在时跳过重新传播。工作区若等于或包含临时根目录,会在任何授权前被拒绝。 diff --git a/packages/sandbox/sandbox-windows-acl/src/runner.ts b/packages/sandbox/sandbox-windows-acl/src/runner.ts index 8c673780a2..f1e9c5ad88 100644 --- a/packages/sandbox/sandbox-windows-acl/src/runner.ts +++ b/packages/sandbox/sandbox-windows-acl/src/runner.ts @@ -11,7 +11,8 @@ * [node, runner.js, '--workspace', , '--temp', , * '--mode', , * ['--write-sid', , - * '--temp-write-sid', ], '--', ] + * '--temp-write-sid', ], + * ['--writable', ]..., '--', ] * * Modes: * - workspace-write: the workspace and temp directories carry distinct @@ -69,6 +70,8 @@ interface ParsedArgs { mode: 'read-only' | 'workspace-write' writeSid: string | undefined tempWriteSid: string | undefined + /** Extra directories granted beside the workspace under workspace-write, in argv order. */ + writable: string[] command: string args: string[] } @@ -79,6 +82,7 @@ function parseArgs(raw: string[]): ParsedArgs { let mode: string | undefined let writeSid: string | undefined let parsedTempWriteSid: string | undefined + const writable: string[] = [] let index = 0 for (; index < raw.length; index++) { const token = raw[index] @@ -95,6 +99,7 @@ function parseArgs(raw: string[]): ParsedArgs { case '--mode': mode = value; break case '--write-sid': writeSid = value; break case '--temp-write-sid': parsedTempWriteSid = value; break + case '--writable': writable.push(value); break default: fail(`unknown argument: ${token}`) } } @@ -104,7 +109,7 @@ function parseArgs(raw: string[]): ParsedArgs { const argv = raw.slice(index) const command = argv[0] if (command === undefined) fail('missing command after --') - return { workspace, temp, mode, writeSid, tempWriteSid: parsedTempWriteSid, command, args: argv.slice(1) } + return { workspace, temp, mode, writeSid, tempWriteSid: parsedTempWriteSid, writable, command, args: argv.slice(1) } } function requireDirectory(label: string, path: string): void { @@ -119,11 +124,15 @@ async function main(): Promise { // a bogus root must fail loudly at the runner boundary, never mid-child. requireDirectory('--workspace', parsed.workspace) requireDirectory('--temp', parsed.temp) + for (const directory of parsed.writable) requireDirectory('--writable', directory) const seamManaged = parsed.writeSid !== undefined || parsed.tempWriteSid !== undefined if (parsed.mode === 'read-only' && seamManaged) { fail('read-only does not accept --write-sid or --temp-write-sid') } + if (parsed.mode === 'read-only' && parsed.writable.length > 0) { + fail('read-only does not accept --writable') + } if (parsed.mode === 'workspace-write' && (parsed.writeSid === undefined) !== (parsed.tempWriteSid === undefined)) { fail('workspace-write requires --write-sid and --temp-write-sid together') } @@ -160,7 +169,7 @@ async function main(): Promise { } } sandbox = new AclSandbox({ - writableDirs: parsed.mode === 'workspace-write' ? [parsed.workspace] : [], + writableDirs: parsed.mode === 'workspace-write' ? [parsed.workspace, ...parsed.writable] : [], tempDir: privateTempDir, mode: parsed.mode, ...writeSid === undefined ? {} : { writeSid }, diff --git a/packages/session/working-directory/package.json b/packages/session/working-directory/package.json index 295968e6ee..5f0466438e 100644 --- a/packages/session/working-directory/package.json +++ b/packages/session/working-directory/package.json @@ -38,8 +38,6 @@ "@deepseek-ai/dsh-system-prompt": "workspace:*" }, "devDependencies": { - "@deepseek-ai/dsh-sandbox-policy": "workspace:*", - "@deepseek-ai/dsh-user-approval": "workspace:*", "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-fs": "workspace:*", diff --git a/packages/skill/tool-skill/README.i18n.yaml b/packages/skill/tool-skill/README.i18n.yaml index 6a9db2d702..a10e72b69d 100644 --- a/packages/skill/tool-skill/README.i18n.yaml +++ b/packages/skill/tool-skill/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-skill/use-this-package: - en: 633cb494ab14a7ce - zh: 8647ccca09bf3e0a + en: 1ab4629399286149 + zh: 8600ec1ea260fb6a /deepseek-ai-dsh-tool-skill/use-this-package/when-to-choose-it: en: b7d33bd969826ee3 zh: 4e155a0f14b41541 diff --git a/packages/skill/tool-skill/README.md b/packages/skill/tool-skill/README.md index ddf4072758..99543c9595 100644 --- a/packages/skill/tool-skill/README.md +++ b/packages/skill/tool-skill/README.md @@ -25,7 +25,7 @@ Agents can discover and load skills during a session. When the `skill` tool is v ## Use this package -Skill discovery, catalog updates, and explicit skill invocation use the Session's current working directory. +Skill discovery, catalog updates, and explicit skill invocation use the Session's workspace root; a directory change inside that root keeps the same catalog. Mount the plugin alongside the skill registry to give agents a session skill catalog and the `skill` loader tool. It requires `ctx.agents`, `ctx.tools`, and `ctx.skills`. diff --git a/packages/skill/tool-skill/README.zh.md b/packages/skill/tool-skill/README.zh.md index f271918944..0b4f10d18b 100644 --- a/packages/skill/tool-skill/README.zh.md +++ b/packages/skill/tool-skill/README.zh.md @@ -25,7 +25,7 @@ agent 可以在会话期间发现并加载 skill。当 `skill` 工具可见时 ## 使用本包 -技能发现、目录更新与显式技能调用均使用 Session 的当前工作目录。 +技能发现、目录更新与显式技能调用均使用 Session 的工作区根;根内部的目录切换保持同一份目录。 与 skill 注册表一起挂载该插件,即可让 agent 拥有会话 skill 目录和 `skill` 加载工具。它需要 `ctx.agents`、`ctx.tools` 与 `ctx.skills`。 diff --git a/packages/skill/tool-skill/src/index.ts b/packages/skill/tool-skill/src/index.ts index f08fb82064..2a7e6e9080 100644 --- a/packages/skill/tool-skill/src/index.ts +++ b/packages/skill/tool-skill/src/index.ts @@ -133,7 +133,7 @@ export function apply(ctx: Context, config: Config = {}): void { } // The agent is its own scope key, so the lookup resolves the layered // registry exactly as this agent's composition sees it. - const cwd = exec.agent === undefined ? undefined : await ctx.workingDirectory.ensure(exec.agent, exec.signal) + const cwd = exec.agent === undefined ? undefined : ctx.workingDirectory.rootOf(exec.agent.session) const lookup = { cwd, signal: exec.signal, scope: exec.agent } const summary = (await ctx.skills.list(lookup)).find(skill => skill.name === args.name) if (!summary) { @@ -187,7 +187,7 @@ export function apply(ctx: Context, config: Config = {}): void { const names = invokedSkillNames(messages) if (names.length === 0) return decision signal.throwIfAborted() - const lookup = { cwd: await ctx.workingDirectory.ensure(agent, signal), signal, scope: agent } + const lookup = { cwd: ctx.workingDirectory.rootOf(agent.session), signal, scope: agent } const injections: UserMessage[] = [] for (const name of names) { const skill = await ctx.skills.get(name, lookup) @@ -223,7 +223,7 @@ export function apply(ctx: Context, config: Config = {}): void { signal.throwIfAborted() const toolVisible = ctx.tools.get(skillTool.name, agent) === skillTool const snapshot = toolVisible - ? await ctx.skills.snapshot({ cwd: await ctx.workingDirectory.ensure(agent, signal), signal, scope: agent }) + ? await ctx.skills.snapshot({ cwd: ctx.workingDirectory.rootOf(agent.session), signal, scope: agent }) : { skills: [], complete: true } signal.throwIfAborted() const skills = snapshot.skills.filter(isModelInvocable) diff --git a/packages/test-support/agent-loop-testkit/src/working-directory-fixture.ts b/packages/test-support/agent-loop-testkit/src/working-directory-fixture.ts index 93d4b3d7da..ceac485150 100644 --- a/packages/test-support/agent-loop-testkit/src/working-directory-fixture.ts +++ b/packages/test-support/agent-loop-testkit/src/working-directory-fixture.ts @@ -5,6 +5,7 @@ import type { Session } from '@deepseek-ai/dsh-session' /** * Supply fixed directory values without filesystem checks or durable changes. + * The workspace root equals the directory, which is the Session's only anchor. * @param ctx - context owning this test collaborator. * @param defaultDirectory - fallback for fixtures without a Session directory. */ @@ -13,6 +14,8 @@ export function provideWorkingDirectoryFixture(ctx: Context, defaultDirectory = ctx.provide('workingDirectory', { defaultDirectory, get, + rootOf: get, + anchorsOf: (session: Session): readonly string[] => [get(session)], ensure: (agent: Agent): Promise => Promise.resolve(get(agent.session)), }) } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index dfd3aa64d9..8dc6066622 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -897,6 +897,9 @@ importers: '@deepseek-ai/cordis-plugin-loader': specifier: workspace:~ version: link:../../vendor/loader + '@deepseek-ai/dsh-api-workspace-files': + specifier: workspace:* + version: link:../../packages/api/workspace-files '@deepseek-ai/dsh-brand': specifier: workspace:* version: link:../../packages/util/brand @@ -1977,9 +1980,15 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:* version: link:../../session/session-persistence + '@deepseek-ai/dsh-session-projection-cache': + specifier: workspace:* + version: link:../../session/session-projection-cache '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../util/workspace-path + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory packages/attachment/attachment: devDependencies: @@ -6381,6 +6390,9 @@ importers: '@deepseek-ai/dsh-api-remotes': specifier: workspace:* version: link:../../api/remotes + '@deepseek-ai/dsh-api-session-controller': + specifier: workspace:* + version: link:../../api/session-controller '@deepseek-ai/dsh-api-workspace-files': specifier: workspace:* version: link:../../api/workspace-files @@ -13991,6 +14003,15 @@ importers: '@deepseek-ai/dsh-agent': specifier: workspace:* version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop-testkit': + specifier: workspace:* + version: link:../../test-support/agent-loop-testkit + '@deepseek-ai/dsh-fs': + specifier: workspace:* + version: link:../../fs/fs + '@deepseek-ai/dsh-fs-local': + specifier: workspace:* + version: link:../../fs/fs-local '@deepseek-ai/dsh-sandbox': specifier: workspace:* version: link:../sandbox @@ -14000,9 +14021,21 @@ importers: '@deepseek-ai/dsh-session-projection': specifier: workspace:* version: link:../../session/session-projection + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local '@deepseek-ai/dsh-system-prompt': specifier: workspace:* version: link:../../core/system-prompt + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-user-approval': + specifier: workspace:* + version: link:../../interaction/user-approval + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory packages/sandbox/sandbox-windows-acl: dependencies: @@ -15102,9 +15135,6 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:* version: link:../../llm/llm - '@deepseek-ai/dsh-sandbox-policy': - specifier: workspace:* - version: link:../../sandbox/sandbox-policy '@deepseek-ai/dsh-session': specifier: workspace:* version: link:../../core/session @@ -15123,9 +15153,6 @@ importers: '@deepseek-ai/dsh-tools': specifier: workspace:* version: link:../../core/tools - '@deepseek-ai/dsh-user-approval': - specifier: workspace:* - version: link:../../interaction/user-approval packages/settings/settings: dependencies: diff --git a/scripts/client-bundle-purity.spec.ts b/scripts/client-bundle-purity.spec.ts index 817e458a46..72493d286b 100644 --- a/scripts/client-bundle-purity.spec.ts +++ b/scripts/client-bundle-purity.spec.ts @@ -271,6 +271,8 @@ describe('client bundle purity gate', () => { expect(() => resolveId('@deepseek-ai/dsh-native-command')).toThrow('client bundle purity') expect(() => resolveId('@deepseek-ai/dsh-host-open-in-app')).toThrow(/purity/) expect(resolveId('@deepseek-ai/dsh-plugin-manager/registry')).toBeNull() + expect(resolveId('@deepseek-ai/dsh-api-session-controller/client/directories')).toBeNull() + expect(() => resolveId('@deepseek-ai/dsh-api-session-controller/client')).toThrow(/purity/) expect(() => resolveId('@deepseek-ai/dsh-plugin-manager')).toThrow(/purity/) expect(() => resolveId('@deepseek-ai/dsh-plugin-manager/registry/internal')).toThrow(/purity/) }) diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 8b8ccac8ea..59da7d5961 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -233,8 +233,8 @@ const SERVICE_ROLES: ServiceRole[] = [ title: 'Session working directory', mode: 'seam', implementations: ['working-directory'], - consumers: ['tool-working-directory', 'tool-fs', 'tool-bash', 'tool-pwsh', 'subagent', 'sdk-jsonrpc-server'], - note: 'Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes; user context reports them while original metadata and write grants stay fixed.', + consumers: ['tool-working-directory', 'tool-fs', 'tool-bash', 'tool-pwsh', 'subagent', 'sdk-jsonrpc-server', 'sandbox-policy', 'workspace-files', 'terminal-controller', 'workspace-changes', 'file-reference-local', 'tool-skill', 'agent-instructions', 'tool-lsp'], + note: 'Two Session projections own the effective execution directory and the workspace root it is in. The filesystem validates changes and user context reports them; model tools follow the directory while the sandbox boundary, file views, and discovery follow the root, and original metadata stays fixed.', }, { key: 'mcpResources', diff --git a/tsconfig.base.json b/tsconfig.base.json index 483542be3a..a40c5962fd 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -146,6 +146,7 @@ "@deepseek-ai/dsh-api-session-controller/client": ["./packages/api/session-controller/src/client/index.ts"], "@deepseek-ai/dsh-api-session-controller/types": ["./packages/api/session-controller/src/types.ts"], "@deepseek-ai/dsh-api-session-controller/remote-events": ["./packages/api/session-controller/src/remote-events.ts"], + "@deepseek-ai/dsh-api-session-controller/client/directories": ["./packages/api/session-controller/src/client/sessions/directories.ts"], "@deepseek-ai/dsh-api-settings-controller": ["./packages/api/settings-controller/src/index.ts"], "@deepseek-ai/dsh-api-settings-controller/types": ["./packages/api/settings-controller/src/types.ts"], "@deepseek-ai/dsh-api-remote-access": ["./packages/api/remote-access/src/index.ts"],